<?php
require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/session.php";
require_once __DIR__ . "/../includes/auth_check.php";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$user_id = $_SESSION['user_id'];
$conn = db();

// Top 10 currencies (your multi-currency system)
$currencies = ['USD', 'EUR', 'GBP', 'JPY', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD'];

// Handle POST submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected_currency = $_POST['currency'] ?? '';

    if (!in_array($selected_currency, $currencies)) {
        $error = "Invalid currency selection.";
    } else {
        $stmt = $conn->prepare("UPDATE users SET currency=? WHERE id=?");
        $stmt->bind_param("si", $selected_currency, $user_id);
        $stmt->execute();

        // Redirect to dashboard after successful selection
        header("Location: /user/dashboard.php");
        exit;
    }
}

// Fetch current currency (if already selected)
$stmt = $conn->prepare("SELECT currency FROM users WHERE id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$current_currency = $stmt->get_result()->fetch_assoc()['currency'] ?? '';

?>

<?php include __DIR__ . "/../components/layout.php"; ?>

<div class="select-currency-container">

    <h2>Select Your Account Currency</h2>

    <?php if (!empty($error)): ?>
        <p style="color:red;"><?php echo htmlspecialchars($error); ?></p>
    <?php endif; ?>

    <form method="POST">

        <label for="currency">Choose Currency:</label>
        <select name="currency" id="currency" required>
            <option value="">-- Select --</option>
            <?php foreach ($currencies as $cur): ?>
                <option value="<?php echo $cur; ?>" <?php echo ($cur === $current_currency) ? 'selected' : ''; ?>>
                    <?php echo $cur; ?>
                </option>
            <?php endforeach; ?>
        </select>

        <br><br>
        <button type="submit" class="btn">Save Currency</button>
    </form>

</div>