<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/includes/db.php';

$new_currency = $_GET['currency'] ?? '';
$redirect_to = $_SERVER['HTTP_REFERER'] ?? 'index.php'; // Default redirect location

if (!empty($new_currency)) {
    // Validate that the selected currency exists and is active in our database
    $stmt = $conn->prepare("SELECT code FROM currencies WHERE code = ? AND is_active = 1");
    $stmt->bind_param("s", $new_currency);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        // If it's a valid currency, save it to the user's session
        $_SESSION['currency'] = $new_currency;
    }
    $stmt->close();
}

// Redirect the user back to the page they were on
header("Location: " . $redirect_to);
exit();
