<?php
require_once '../includes/adminsession.php';
require_once '../includes/db.php';
require_once '../includes/admin_functions.php'; // ✅ admin layout

$conn = db();
if (!$conn) die("Database connection failed.");

// Fetch all users
$users = $conn->query("
    SELECT id, CONCAT(first_name, ' ', last_name) AS full_name, email 
    FROM users 
    ORDER BY first_name, last_name ASC
");

if (!$users) die("Query failed: " . $conn->error);

$success = '';
$error = '';
$existing_tokens = [];
$selected_user = 0;
$token_count = 1;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected_user = intval($_POST['user_id'] ?? 0);
    $token_count = intval($_POST['token_count'] ?? 1);

    if ($selected_user <= 0 || $token_count < 1 || $token_count > 6) {
        $error = "Invalid user or token count.";
    } else {
        $stmt = $conn->prepare("
            INSERT INTO user_tokens (user_id, token_number, token_value, reason)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE token_value = VALUES(token_value), reason = VALUES(reason), used = 0
        ");

        for ($i = 1; $i <= $token_count; $i++) {
            $reason_field = trim($_POST["reason_$i"] ?? '');
            if (!$reason_field) $reason_field = "No reason provided";
            $token_value = strtoupper(bin2hex(random_bytes(3)));

            $stmt->bind_param("isss", $selected_user, $i, $token_value, $reason_field);
            $stmt->execute();
        }

        $success = "Successfully generated $token_count token(s) with unique reasons.";
    }
}

// Fetch existing tokens
if ($selected_user) {
    $res = $conn->query("
        SELECT token_number, token_value, reason, used 
        FROM user_tokens 
        WHERE user_id = $selected_user 
        ORDER BY token_number ASC
    ");
    if ($res && $res->num_rows > 0) {
        $existing_tokens = $res->fetch_all(MYSQLI_ASSOC);
    }
}

// ===========================
// CAPTURE UI
// ===========================
ob_start();
?>

<div style="max-width:800px;margin:auto;">

    <h2>🔐 Generate Tokens for User</h2>

    <?php if($success): ?>
        <div style="color:green; margin-bottom:10px;"><?= $success ?></div>
    <?php endif; ?>

    <?php if($error): ?>
        <div style="color:red; margin-bottom:10px;"><?= $error ?></div>
    <?php endif; ?>

    <form method="POST" style="background:#fff;padding:20px;border-radius:10px;box-shadow:0 2px 8px rgba(0,0,0,0.08);">

        <label>User:</label>
        <select name="user_id" required onchange="this.form.submit()">
            <option value="">-- Select User --</option>
            <?php while($u = $users->fetch_assoc()): ?>
                <option value="<?= $u['id'] ?>" <?= ($selected_user == $u['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($u['full_name']) ?> (<?= htmlspecialchars($u['email']) ?>)
                </option>
            <?php endwhile; ?>
        </select>

       <p> <label>Number of Tokens (1-6):</label>
        <select name="token_count" onchange="showReasons(this.value)">
            <?php for($i=1;$i<=6;$i++): ?>
                <option value="<?= $i ?>" <?= ($token_count == $i ? 'selected' : '') ?>><?= $i ?></option>
            <?php endfor; ?>
        </select>
</p>
        <div id="token_reasons">
            <?php for($i=1;$i<=$token_count;$i++): ?>
                <label>Reason for Token #<?= $i ?>:</label>
                <input type="text" name="reason_<?= $i ?>" required
                    value="<?= $_POST["reason_$i"] ?? '' ?>">
            <?php endfor; ?>
        </div>

        <button type="submit" style="margin-top:10px;">Generate Tokens</button>
    </form>

    <?php if(!empty($existing_tokens)): ?>
        <h3 style="margin-top:30px;">📋 Existing Tokens</h3>

        <table style="width:100%;border-collapse:collapse;">
            <tr style="background:#1a73e8;color:white;">
                <th style="padding:10px;">#</th>
                <th>Token</th>
                <th>Reason</th>
                <th>Status</th>
            </tr>

            <?php foreach($existing_tokens as $t): ?>
                <tr style="background:#fff;">
                    <td style="padding:10px;"><?= $t['token_number'] ?></td>
                    <td><?= htmlspecialchars($t['token_value']) ?></td>
                    <td><?= htmlspecialchars($t['reason']) ?></td>
                    <td><?= $t['used'] ? 'Used' : 'Unused' ?></td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php endif; ?>

</div>

<script>
function showReasons(count) {
    const container = document.getElementById('token_reasons');
    container.innerHTML = '';

    for (let i = 1; i <= count; i++) {
        container.innerHTML += `
            <label>Reason for Token #${i}:</label>
            <input type="text" name="reason_${i}" required>
        `;
    }
}
</script>

<?php
$content = ob_get_clean();

// ===========================
// RENDER ADMIN LAYOUT
// ===========================
renderAdminLayout("Generate Tokens", $content, $conn);