<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';

// ==========================
// SAVE CURRENCY STATUS
// ==========================
$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (isset($_POST['update_currency'])) {

        foreach ($_POST['status'] as $code => $status) {

            $stmt = $conn->prepare("UPDATE currencies SET status = ? WHERE code = ?");
            $stmt->bind_param("ss", $status, $code);
            $stmt->execute();
        }

        $message = "Currencies updated successfully!";
    }
}

// ==========================
// LOAD CURRENCIES
// ==========================
$result = $conn->query("SELECT * FROM currencies ORDER BY code ASC");

ob_start();
?>

<div class="main-content">

    <h2 class="page-title">Manage Currencies</h2>

    <?php if ($message): ?>
        <div class="alert success"><?= $message ?></div>
    <?php endif; ?>

    <form method="POST" class="panel">

        <p><strong>Enable or disable supported currencies</strong></p>

        <table class="table">

            <thead>
                <tr>
                    <th>Currency</th>
                    <th>Code</th>
                    <th>Symbol</th>
                    <th>Status</th>
                </tr>
            </thead>

            <tbody>

                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>

                        <td><?= htmlspecialchars($row['name']) ?></td>
                        <td><?= $row['code'] ?></td>
                        <td><?= $row['symbol'] ?></td>

                        <td>
                            <select name="status[<?= $row['code'] ?>]">
                                <option value="active" <?= $row['status'] === 'active' ? 'selected' : '' ?>>
                                    Active
                                </option>
                                <option value="inactive" <?= $row['status'] === 'inactive' ? 'selected' : '' ?>>
                                    Inactive
                                </option>
                            </select>
                        </td>

                    </tr>
                <?php endwhile; ?>

            </tbody>

        </table>

        <br>

        <button type="submit" name="update_currency" class="btn">
            Save Changes
        </button>

    </form>

</div>

<?php
$content = ob_get_clean();
$page_title = "Currencies";
include '../components/admin_layout.php';
?>