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

// Check admin login
if (!isset($_SESSION['SESS_ADMINLOGGEDIN']) || $_SESSION['SESS_ADMINLOGGEDIN'] == FALSE) {
    header("Location: " . $config_basedir . "../admin/adminlogin.php");
    exit();
}

require_once("header.php");

// ================= DELETE CURRENCY =================
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);
    $stmt = $pdo->prepare("DELETE FROM currencies WHERE id = ?");
    $stmt->execute([$id]);
    $cur_success = "<div class='alert alert-danger'>Currency deleted successfully.</div>";
}

// ================= ADD CURRENCY =================
if (isset($_POST['add_cur'])) {
    $stmt = $pdo->prepare("INSERT INTO currencies (cur_name, cur_shot_name, cur_symbol, cur_rate, date) 
                           VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['cur_name'],
        strtoupper($_POST['cur_shot_name']),
        $_POST['cur_symbol'],
        $_POST['cur_rate'],
        date("Y-m-d H:i:s")
    ]);
    $cur_success = "<div class='alert alert-success'>Currency added successfully.</div>";
}

// ================= EDIT CURRENCY =================
if (isset($_POST['edit_currency'])) {
    $stmt = $pdo->prepare("UPDATE currencies 
                           SET cur_name = ?, cur_shot_name = ?, cur_symbol = ?, cur_rate = ?, date = ? 
                           WHERE id = ?");
    $stmt->execute([
        $_POST['cur_name'],
        strtoupper($_POST['cur_shot_name']),
        $_POST['cur_symbol'],
        $_POST['cur_rate'],
        date("Y-m-d H:i:s"),
        $_POST['id']
    ]);
    $cur_success = "<div class='alert alert-success'>Currency updated successfully.</div>";
}

// ================= AUTO UPDATE CURRENCIES =================
if (isset($_POST['update_all'])) {
    $apiUrl = "https://open.er-api.com/v6/latest/USD"; // Free, no key needed

    $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'];

        // Fetch currencies from DB
        $stmt = $pdo->query("SELECT id, cur_shot_name FROM currencies");
        $currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $updated = 0;
        foreach ($currencies as $cur) {
            $code = strtoupper(trim($cur['cur_shot_name'])); // Must match API code
            if (array_key_exists($code, $rates)) {
                $rate = $rates[$code];
                $upd = $pdo->prepare("UPDATE currencies SET cur_rate = ?, date = ? WHERE id = ?");
                $upd->execute([$rate, date("Y-m-d H:i:s"), $cur['id']]);
                $updated++;
            }
        }

        if ($updated > 0) {
            $cur_success = "<div class='alert alert-success'>✅ $updated currencies updated successfully to latest USD rates.</div>";
        } else {
            $cur_success = "<div class='alert alert-warning'>⚠️ No currencies were updated. Please make sure <b>cur_shot_name</b> in DB matches ISO codes like EUR, GBP, NGN, CNY.</div>";
        }
    } else {
        $cur_success = "<div class='alert alert-danger'>❌ Failed to fetch currency rates.<br><pre>" . htmlspecialchars($response) . "</pre></div>";
    }
}

?>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <div class="mt-2 mb-4">
                <h1 class="title1 text-dark">Manage Site Currencies</h1>
            </div>

            <?php if (isset($cur_success)) echo $cur_success; ?>

            <!-- AUTO UPDATE BUTTON -->
            <form method="post" class="mb-3">
                <button type="submit" name="update_all" class="btn btn-primary">Update All Currencies (Live Rates)</button>
            </form>

            <!-- LIST CURRENCIES -->
            <?php
            $stmt = $pdo->query("SELECT * FROM currencies ORDER BY id ASC");
            $currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if ($currencies) {
                foreach ($currencies as $row) {
                    ?>
                    <form method="POST" class="border p-3 mb-3 bg-white">
                        <input type="hidden" name="id" value="<?= $row['id'] ?>">
                        <div class="form-group">
                            <label>USA (Dollar) VS <?= $row['cur_name'] ?> (<?= $row['cur_symbol'] ?>)</label>
                            <input type="text" class="form-control" name="cur_name" value="<?= htmlspecialchars($row['cur_name']) ?>" required>
                            <input type="text" class="form-control" name="cur_shot_name" value="<?= htmlspecialchars($row['cur_shot_name']) ?>" required>
                            <input type="text" class="form-control" name="cur_symbol" value="<?= htmlspecialchars($row['cur_symbol']) ?>" required>
                            <input type="text" class="form-control" name="cur_rate" value="<?= htmlspecialchars($row['cur_rate']) ?>" required>
                        </div>
                        <div class="button-group">
                            <a href="currency.php?del=<?= $row['id'] ?>" class="btn btn-danger">Delete</a>
                            <button type="submit" class="btn btn-success" name="edit_currency">Update</button>
                        </div>
                    </form>
                    <?php
                }
            } else {
                echo "<p>No currencies found.</p>";
            }
            ?>

            <hr>

            <!-- ADD NEW CURRENCY -->
            <!--<center><h3>Add New Currency</h3></center>-->
            <!--<form method="POST" class="border p-3 bg-white">-->
            <!--    <div class="form-group">-->
            <!--        <label>CURRENCY NAME</label>-->
            <!--        <input type="text" class="form-control" name="cur_name" required>-->
            <!--    </div>-->
            <!--    <div class="form-group">-->
            <!--        <label>CURRENCY SHORT NAME</label>-->
            <!--        <input type="text" class="form-control" name="cur_shot_name" required>-->
            <!--    </div>-->
            <!--    <div class="form-group">-->
            <!--        <label>CURRENCY SYMBOL</label>-->
            <!--        <input type="text" class="form-control" name="cur_symbol" required>-->
            <!--    </div>-->
            <!--    <div class="form-group">-->
            <!--        <label>USD RATE</label>-->
            <!--        <input type="text" class="form-control" name="cur_rate" required>-->
            <!--    </div>-->
            <!--    <button type="submit" class="btn btn-success btn-block" name="add_cur">Add Currency</button>-->
            <!--</form>-->

        </div>
    </div>
</div>

<?php require("footer.php"); ?>
