<?php
require '../includes/db.php';
require 'includes/admin_auth.php';

$allCurrencies = ['INR', 'USD', 'USDT', 'AED', 'PKR'];

// Handle user creation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $username = strtolower(trim($_POST['username']));
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $merchant_key = uniqid('mer_');
    $secret_key = bin2hex(random_bytes(16));
    $currency = strtolower(trim($_POST['currency']));  // ensure lowercase

    // Normalize currencies to lowercase
    $currenciesRaw = $_POST['currencies'] ?? [];
    $currencies = array_map(fn($c) => strtolower(trim($c)), $currenciesRaw);

    // Normalize conversion rates
    $ratesRaw = $_POST['conversion_rates'] ?? [];
    $rates = [];
    foreach ($ratesRaw as $from_currency => $val) {
        $from_currency = strtolower(trim($from_currency));
        if ($from_currency !== $currency && is_numeric($val) && $val > 0) {
            $rates[$from_currency] = $val;
        }
    }

    $payin_fee = floatval($_POST['payin_fee'] ?? 0);
    $payout_fee = floatval($_POST['payout_fee'] ?? 0);

    // Insert into users table
    $insert = $pdo->prepare("INSERT INTO users (name, username, password, merchant_key, secret_key, currency, payin_fee, payout_fee) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $insert->execute([$name, $username, $password, $merchant_key, $secret_key, $currency, $payin_fee, $payout_fee]);

    $newUserId = $pdo->lastInsertId();

    // Insert allowed currencies
    $stmt = $pdo->prepare("INSERT INTO user_currencies (user_id, currency_code) VALUES (?, ?)");
    foreach ($currencies as $curr) {
        $stmt->execute([$newUserId, $curr]);
    }

    // Insert conversion rates
    $stmtRate = $pdo->prepare("INSERT INTO user_currency_rates (user_id, from_currency, to_currency, rate) VALUES (?, ?, ?, ?)");
    foreach ($rates as $from_currency => $rate_value) {
        $stmtRate->execute([$newUserId, $from_currency, $currency, $rate_value]);
    }

    $success = "✅ User created successfully.";
}

// Toggle user status
if (isset($_GET['toggle']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $pdo->query("UPDATE users SET status = NOT status WHERE id = $id");
    header("Location: users.php");
    exit();
}

// Fetch all users
$users = $pdo->query("SELECT * FROM users ORDER BY id DESC")->fetchAll();

// Fetch currencies for all users
$userCurrenciesMap = [];
$stmt = $pdo->query("SELECT user_id, currency_code FROM user_currencies");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $userCurrenciesMap[$row['user_id']][] = strtoupper($row['currency_code']);  // uppercase for display
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Users</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        body { background-color: #f9fafa; font-family: 'Segoe UI', sans-serif; }
        .card-header { font-weight: bold; background-color: #f1f1f1; }
        .badge-active { background-color: #28a745; }
        .badge-inactive { background-color: #6c757d; }
        .form-section { background-color: #ffffff; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .currency-badge { margin-right: 3px; }
        .rate-input { width: 100%; }
    </style>
</head>
<body class="p-4">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-people-fill"></i> Manage Users</h2>
            <a href="dashboard.php" class="btn btn-secondary"><i class="bi bi-house"></i> Dashboard</a>
        </div>

        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <!-- User Creation Form -->
        <div class="form-section mb-5">
            <h5><i class="bi bi-person-plus"></i> Create New User</h5>
            <form method="POST" class="row g-3 mt-2" id="userForm">
                <div class="col-md-3">
                    <input name="name" placeholder="Name" required class="form-control">
                </div>
                <div class="col-md-3">
                    <input name="username" type="text" placeholder="Username" required class="form-control">
                </div>
                <div class="col-md-3">
                    <select name="currency" id="defaultCurrency" class="form-select" required>
                        <option value="">-- Default Currency --</option>
                        <?php foreach ($allCurrencies as $curr): ?>
                            <option value="<?= strtolower($curr) ?>"><?= strtoupper($curr) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <input name="password" type="password" placeholder="Password" required class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Allowed Currencies</label>
                    <select name="currencies[]" id="allowedCurrencies" multiple class="form-select" required>
                        <?php foreach ($allCurrencies as $curr): ?>
                            <option value="<?= strtolower($curr) ?>"><?= strtoupper($curr) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">Hold Ctrl (Windows) or Cmd (Mac) to select multiple.</small>
                </div>
                <div class="col-md-3">
                    <input name="payin_fee" type="number" step="0.01" placeholder="Pay-In Fee (%)" class="form-control">
                </div>
                <div class="col-md-3">
                    <input name="payout_fee" type="number" step="0.01" placeholder="Payout Fee (%)" class="form-control">
                </div>
                <div class="col-12">
                    <div id="conversionRatesContainer"></div>
                </div>
                <div class="col-md-3 d-grid">
                    <button class="btn btn-primary"><i class="bi bi-check-circle"></i> Create</button>
                </div>
            </form>
        </div>

        <!-- Users Table -->
        <div class="card">
            <div class="card-header">
                <i class="bi bi-list"></i> All Users
            </div>
            <div class="card-body table-responsive">
                <table class="table table-bordered table-hover align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Username</th>
                            <th>Balance</th>
                            <th>Status</th>
                            <th>Pay-In Fee</th>
                            <th>Payout Fee</th>
                            <th>Default</th>
                            <th>Currencies</th>
                            <th>Keys</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?= $user['id'] ?></td>
                            <td><?= htmlspecialchars($user['name']) ?></td>
                            <td><?= htmlspecialchars($user['username']) ?></td>
                            <td><?= strtoupper($user['currency']) ?> <?= number_format($user['balance'], 2) ?></td>
                            <td>
                                <span class="badge <?= $user['status'] ? 'badge-active' : 'badge-inactive' ?>">
                                    <?= $user['status'] ? 'Active' : 'Inactive' ?>
                                </span>
                                <a href="?toggle=1&id=<?= $user['id'] ?>" class="btn btn-sm btn-outline-dark ms-2">
                                    <?= $user['status'] ? 'Deactivate' : 'Activate' ?>
                                </a>
                            </td>
                            <td><?= $user['payin_fee'] ?>%</td>
                            <td><?= $user['payout_fee'] ?>%</td>
                            <td><span class="badge bg-primary"><?= strtoupper($user['currency']) ?></span></td>
                            <td>
                                <?php if (!empty($userCurrenciesMap[$user['id']])): ?>
                                    <?php foreach ($userCurrenciesMap[$user['id']] as $currency): ?>
                                        <span class="badge bg-info text-dark currency-badge"><?= $currency ?></span>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <small>
                                    <strong>Merchant:</strong> <?= $user['merchant_key'] ?><br>
                                    <strong>Secret:</strong> <?= $user['secret_key'] ?>
                                </small>
                            </td>
                            <td class="d-grid gap-1">
                                <a href="user_txns.php?uid=<?= $user['id'] ?>" class="btn btn-sm btn-info">
                                    <i class="bi bi-eye"></i> View Txns
                                </a>
                                <a href="edit_user.php?id=<?= $user['id'] ?>" class="btn btn-sm btn-warning">
                                    <i class="bi bi-pencil"></i> Edit
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

<script>
document.getElementById('allowedCurrencies').addEventListener('change', updateConversionRateInputs);
document.getElementById('defaultCurrency').addEventListener('change', updateConversionRateInputs);

function updateConversionRateInputs() {
    const defaultCurrency = document.getElementById('defaultCurrency').value;
    const selectedOptions = Array.from(document.getElementById('allowedCurrencies').selectedOptions).map(o => o.value);
    const container = document.getElementById('conversionRatesContainer');
    container.innerHTML = '';

    selectedOptions.forEach(currency => {
        if (currency !== defaultCurrency) {
            const displayCurrency = currency.toUpperCase();
            const displayDefault = defaultCurrency.toUpperCase();
            const div = document.createElement('div');
            div.className = 'mb-2';
            div.innerHTML = `
                <label>Conversion Rate: 1 ${displayCurrency} = ? ${displayDefault}</label>
                <input type="number" step="0.0001" name="conversion_rates[${currency}]" class="form-control rate-input" required>
            `;
            container.appendChild(div);
        }
    });
}
</script>
</body>
</html>
