<?php
session_start();
require_once("../config.php");

// Only allow admins
if (!isset($_SESSION['SESS_ADMINLOGGEDIN']) || $_SESSION['SESS_ADMINLOGGEDIN'] !== true) {
    header("Location: adminlogin.php");
    exit;
}

// Currency ISO codes + symbols
$currencySymbols = [
    "USD" => "$", "EUR" => "€", "GBP" => "£", "NGN" => "₦", "CNY" => "¥",
    "JPY" => "¥", "AUD" => "A$", "CAD" => "C$", "CHF" => "CHF", "INR" => "₹",
    "ZAR" => "R", "BRL" => "R$", "RUB" => "₽", "SEK" => "kr", "NOK" => "kr",
    "KRW" => "₩", "MXN" => "$", "TRY" => "₺", "AED" => "د.إ", "SAR" => "﷼"
];

// Currency ISO codes + full names
$currencyNames = [
    "USD" => "US Dollar", "EUR" => "Euro", "GBP" => "British Pound", "NGN" => "Nigerian Naira",
    "CNY" => "Chinese Yuan", "JPY" => "Japanese Yen", "AUD" => "Australian Dollar",
    "CAD" => "Canadian Dollar", "CHF" => "Swiss Franc", "INR" => "Indian Rupee",
    "ZAR" => "South African Rand", "BRL" => "Brazilian Real", "RUB" => "Russian Ruble",
    "SEK" => "Swedish Krona", "NOK" => "Norwegian Krone", "KRW" => "South Korean Won",
    "MXN" => "Mexican Peso", "TRY" => "Turkish Lira", "AED" => "UAE Dirham", "SAR" => "Saudi Riyal"
];

// Handle button press
if (isset($_POST['generate_all'])) {
    $apiUrl = "https://open.er-api.com/v6/latest/USD";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);

    if ($data && isset($data['rates'])) {
        $rates = $data['rates'];
        $inserted = 0;

        foreach ($rates as $code => $rate) {
            $name = $currencyNames[$code] ?? $code;
            $symbol = $currencySymbols[$code] ?? $code;

            // Check if already exists
            $check = $pdo->prepare("SELECT id FROM currencies WHERE cur_shot_name = ?");
            $check->execute([$code]);

            if ($check->rowCount() > 0) {
                // Update if exists
                $stmt = $pdo->prepare("UPDATE currencies 
                    SET cur_name=?, cur_symbol=?, cur_rate=?, date=? 
                    WHERE cur_shot_name=?");
                $stmt->execute([$name, $symbol, $rate, date("Y-m-d H:i:s"), $code]);
            } else {
                // Insert new
                $stmt = $pdo->prepare("INSERT INTO currencies 
                    (cur_name, cur_shot_name, cur_symbol, cur_rate, date) 
                    VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $code, $symbol, $rate, date("Y-m-d H:i:s")]);
            }
            $inserted++;
        }

        $msg = "<div style='color:green;font-weight:bold'>✅ $inserted currencies generated/updated successfully.</div>";
    } else {
        $msg = "<div style='color:red'>❌ Failed to fetch currency data. Response:<br><pre>" . htmlspecialchars($response) . "</pre></div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Generate All Currencies</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f9f9f9; padding: 20px; }
        .container { background: #fff; padding: 20px; border-radius: 8px; max-width: 600px; margin: auto; box-shadow: 0 2px 6px rgba(0,0,0,0.2); }
        button { padding: 12px 20px; font-size: 16px; background: green; color: white; border: none; border-radius: 6px; cursor: pointer; }
        button:hover { background: darkgreen; }
    </style>
</head>
<body>
<div class="container">
    <h2>🌍 Generate All Currencies (vs USD)</h2>
    <p>Click the button below to fetch all currencies live and insert/update into the database.</p>
    <form method="post">
        <button type="submit" name="generate_all">Generate All Currencies</button>
    </form>
    <br>
    <?php if (isset($msg)) echo $msg; ?>
</div>
</body>
</html>
