<?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 selected currencies
$userCurrencies = [];
$stmt = $pdo->prepare("SELECT currency_code FROM user_currencies WHERE user_id = ?");
$stmt->execute([$id]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $userCurrencies[] = $row['currency_code'];
}

// Load user's currency rates
$userRates = [];
$stmt = $pdo->prepare("SELECT currency_code, payin_rate, payout_rate FROM user_currency_rates WHERE user_id = ?");
$stmt->execute([$id]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $userRates[$row['currency_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;

    $selectedCurrencies = $_POST['currencies'] ?? [];
    $ratesPayin = $_POST['payin_rates'] ?? [];
    $ratesPayout = $_POST['payout_rates'] ?? [];
    $defaultCurrency = $_POST['currency'] ?? '';

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

    // Update user
    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]);
    }

    // Update user_currencies
    $pdo->prepare("DELETE FROM user_currencies WHERE user_id = ?")->execute([$id]);
    $insertUC = $pdo->prepare("INSERT INTO user_currencies (user_id, currency_code) VALUES (?, ?)");
    foreach ($selectedCurrencies as $currency) {
        $insertUC->execute([$id, $currency]);
    }

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

    header("Location: user_edit.php?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 Currencies (Hold Ctrl/Command to select multiple)</label>
            <select name="currencies[]" class="form-select" multiple required>
                <?php foreach ($allCurrencies as $curr): ?>
                    <option value="<?= $curr['code'] ?>" <?= in_array($curr['code'], $userCurrencies) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($curr['code'] . ' - ' . $curr['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </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): ?>
                    <?php if (!in_array($curr['code'], $userCurrencies)) continue; ?>
                    <option value="<?= $curr['code'] ?>" <?= ($curr['code'] === $defaultCurrency) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($curr['code'] . ' - ' . $curr['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small class="text-muted">User's main/default currency. Must be one of their enabled currencies.</small>
        </div>

        <?php if (!empty($allCurrencies)): ?>
            <h5 class="mt-4">Currency Conversion Rates</h5>
            <div class="border rounded p-3 mb-3 bg-light">
                <?php foreach ($allCurrencies as $curr):
                    $code = $curr['code'];
                    if (!in_array($code, $userCurrencies)) continue;
                    $payinVal = isset($userRates[$code]['payin_rate']) ? $userRates[$code]['payin_rate'] : 1.0;
                    $payoutVal = isset($userRates[$code]['payout_rate']) ? $userRates[$code]['payout_rate'] : 1.0;
                ?>
                    <div class="mb-3 border-bottom pb-2">
                        <strong><?= htmlspecialchars($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[<?= $code ?>]" value="<?= $payinVal ?>" 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[<?= $code ?>]" value="<?= $payoutVal ?>" 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>
