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

if (!isset($_GET['id'])) {
    header("Location: users.php");
    exit();
}

$id = intval($_GET['id']);

// Load user
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();
if (!$user) die("User not found.");

$defaultCurrency = $user['currency'] ?? '';

// Load all available currencies
$allCurrencies = $pdo->query("SELECT code, name, symbol FROM currencies ORDER BY code")->fetchAll(PDO::FETCH_ASSOC);

// Load user's enabled currencies with rates
$userCurrencies = [];
$stmt = $pdo->prepare("SELECT currency_code, payin_rate, payout_rate FROM user_currencies WHERE user_id = ?");
$stmt->execute([$id]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $code = strtolower(trim($row['currency_code']));
    $userCurrencies[$code] = [
        'payin_rate' => $row['payin_rate'],
        'payout_rate' => $row['payout_rate']
    ];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $username = strtolower(trim($_POST['username']));
    $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_DEFAULT) : null;

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

    $ratesPayinRaw = $_POST['payin_rates'] ?? [];
    $ratesPayoutRaw = $_POST['payout_rates'] ?? [];

    // Normalize all rates arrays
    $ratesPayin = [];
    $ratesPayout = [];
    foreach ($ratesPayinRaw as $code => $val) {
        $ratesPayin[strtolower(trim($code))] = floatval($val);
    }
    foreach ($ratesPayoutRaw as $code => $val) {
        $ratesPayout[strtolower(trim($code))] = floatval($val);
    }

    $defaultCurrency = strtolower(trim($_POST['currency'] ?? ''));

    // Validate defaultCurrency
    if (!in_array($defaultCurrency, $selectedCurrencies)) {
        $defaultCurrency = '';
    }

    // Update user table
    if ($password) {
        $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, password=?, currency=? WHERE id=?");
        $stmt->execute([$name, $username, $password, $defaultCurrency, $id]);
    } else {
        $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, currency=? WHERE id=?");
        $stmt->execute([$name, $username, $defaultCurrency, $id]);
    }

    // Clear and insert user_currencies
    $pdo->prepare("DELETE FROM user_currencies WHERE user_id = ?")->execute([$id]);
    $insertUC = $pdo->prepare("INSERT INTO user_currencies (user_id, currency_code, payin_rate, payout_rate) VALUES (?, ?, ?, ?)");
    foreach ($selectedCurrencies as $currency) {
        $payinRate = isset($ratesPayin[$currency]) ? $ratesPayin[$currency] : 1.0;
        $payoutRate = isset($ratesPayout[$currency]) ? $ratesPayout[$currency] : 1.0;
        $insertUC->execute([$id, $currency, $payinRate, $payoutRate]);
    }

    header("Location: ".$_SERVER['PHP_SELF']."?id=$id&success=1");
    exit();
}

if (isset($_GET['success'])) {
    $success = "✅ User updated successfully.";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit User</title>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container">
    <h2>Edit User</h2>
    <a href="users.php" class="btn btn-secondary mb-4">← Back to Users</a>

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

    <form method="POST" class="card p-4 shadow-sm">
        <div class="mb-3">
            <label class="form-label">Name</label>
            <input name="name" value="<?= htmlspecialchars($user['name']) ?>" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Username</label>
            <input name="username" value="<?= htmlspecialchars($user['username']) ?>" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">New Password (leave blank to keep current)</label>
            <input type="password" name="password" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label">Enabled Withdrawal Methods (Currencies)</label>
            <select name="currencies[]" class="form-select" multiple required>
                <?php foreach ($allCurrencies as $curr): 
                    $currCode = strtolower($curr['code']);
                ?>
                    <option value="<?= htmlspecialchars($currCode) ?>" <?= array_key_exists($currCode, $userCurrencies) ? 'selected' : '' ?>>
                        <?= htmlspecialchars(strtoupper($currCode) . ' - ' . $curr['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small class="text-muted">Hold Ctrl/Command to select multiple methods (bank/usdt/pkr etc.)</small>
        </div>

        <div class="mb-3">
            <label class="form-label">Default Currency</label>
            <select name="currency" class="form-select" required>
                <option value="">-- Select Default Currency --</option>
                <?php foreach ($allCurrencies as $curr): 
                    $currCode = strtolower($curr['code']);
                    if (!array_key_exists($currCode, $userCurrencies)) continue;
                ?>
                    <option value="<?= htmlspecialchars($currCode) ?>" <?= ($currCode === $defaultCurrency) ? 'selected' : '' ?>>
                        <?= htmlspecialchars(strtoupper($currCode) . ' - ' . $curr['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small class="text-muted">User's main balance currency. Must be one of the enabled methods.</small>
        </div>

        <?php if (!empty($userCurrencies)): ?>
            <h5 class="mt-4">Currency Conversion Rates</h5>
            <div class="border rounded p-3 mb-3 bg-light">
                <?php foreach ($userCurrencies as $code => $rates): ?>
                    <div class="mb-3 border-bottom pb-2">
                        <strong><?= htmlspecialchars(strtoupper($code)) ?>:</strong>
                        <div class="row g-2 mt-1">
                            <div class="col-md-6">
                                <label class="form-label">Pay-In Rate</label>
                                <input type="number" step="0.0001" name="payin_rates[<?= htmlspecialchars($code) ?>]" value="<?= htmlspecialchars($rates['payin_rate']) ?>" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Payout Rate</label>
                                <input type="number" step="0.0001" name="payout_rates[<?= htmlspecialchars($code) ?>]" value="<?= htmlspecialchars($rates['payout_rate']) ?>" class="form-control" required>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <button class="btn btn-primary"><i class="bi bi-check-circle"></i> Update User</button>
    </form>
</div>
</body>
</html>
