<?php
// token_admin.php
$con = mysqli_connect('localhost', 'hmrsaasc_cert765', 'hmrsaasc_cert765', 'hmrsaasc_cert765');
if (!$con) {
    die("Database Connection Failed: " . mysqli_connect_error());
}

// Function to generate random token codes
function generateToken($length = 12) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $token .= $chars[random_int(0, strlen($chars) - 1)];
    }
    // Add dashes for readability, e.g. ABCD-EFGH-IJKL
    return strtoupper(chunk_split($token, 4, '-'));
}

// ✅ Handle token generation only when form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    $count = intval($_POST['count']);
    for ($i = 0; $i < $count; $i++) {
        $code = generateToken();
        $sql = "INSERT IGNORE INTO tokens (token_code) VALUES ('$code')";
        mysqli_query($con, $sql);
    }

    // ✅ Store success message in session
    session_start();
    $_SESSION['msg'] = "$count tokens generated successfully!";

    // ✅ Redirect to prevent resubmission on refresh
    header("Location: token_admin.php");
    exit();
}

// ✅ Fetch tokens for display
$result = mysqli_query($con, "SELECT * FROM tokens ORDER BY id DESC");

// ✅ Show session message if any
session_start();
$msg = '';
if (isset($_SESSION['msg'])) {
    $msg = $_SESSION['msg'];
    unset($_SESSION['msg']);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin - Token Generator</title>
    <style>
        body { font-family: Arial; margin: 30px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #004080; color: white; }
        button, input[type=submit] {
            background-color: #004080; color: white; border: none;
            padding: 8px 15px; border-radius: 5px; cursor: pointer;
        }
        input[type=number] { padding: 5px 10px; width: 100px; }
        .alert {
            background: #e7f3fe;
            color: #0c5460;
            border: 1px solid #b8daff;
            padding: 10px;
            border-radius: 5px;
            width: fit-content;
        }
    </style>
</head>
<body>

<h2>🎟 Token Generator Admin</h2>

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

<form method="POST">
    <label>Number of tokens to generate:</label>
    <input type="number" name="count" min="1" max="200" value="10" required>
    <input type="submit" name="generate" value="Generate Tokens">
</form>

<table>
    <tr>
        <th>ID</th>
        <th>Token Code</th>
        <th>Status</th>
        <th>Used By</th>
        <th>Used On</th>
        <th>Created On</th>
    </tr>
    <?php while ($row = mysqli_fetch_assoc($result)) { ?>
    <tr>
        <td><?= $row['id'] ?></td>
        <td><b><?= $row['token_code'] ?></b></td>
        <td><?= $row['status'] ?></td>
        <td><?= $row['used_by'] ?: '-' ?></td>
        <td><?= $row['used_on'] ?: '-' ?></td>
        <td><?= $row['created_on'] ?: '-' ?></td>
    </tr>
    <?php } ?>
</table>

</body>
</html>
