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

$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 (GET)
// ===========================
$selected_user = intval($_GET['user_id'] ?? 0);
$token_count = 1;

// ===========================
// GENERATE TOKENS (POST)
// ===========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_tokens'])) {

    $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).";
    }
}

// ===========================
// FETCH EXISTING TOKENS
// ===========================
if ($selected_user > 0) {

    $stmt = $conn->prepare("
        SELECT token_number, token_value, reason, used
        FROM user_tokens
        WHERE user_id = ?
        ORDER BY token_number ASC
    ");

    $stmt->bind_param("i", $selected_user);
    $stmt->execute();

    $res = $stmt->get_result();

    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; ?>

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

        <label>Select 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>

    </form>

    <!-- ===========================
         GENERATE TOKENS FORM
    ============================ -->
    <?php if($selected_user): ?>

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

        <input type="hidden"
               name="user_id"
               value="<?= $selected_user ?>">

        <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>

        <div id="token_reasons" style="margin-top:15px;">

            <?php for($i=1;$i<=$token_count;$i++): ?>

                <label>
                    Reason for Token #<?= $i ?>:
                </label>

                <input type="text"
                       name="reason_<?= $i ?>"
                       placeholder="Enter reason"
                       required
                       value="<?= htmlspecialchars($_POST["reason_$i"] ?? '') ?>">

            <?php endfor; ?>

        </div>

        <button type="submit"
                name="generate_tokens"
                style="margin-top:15px;">

            Generate Tokens

        </button>

    </form>

    <?php endif; ?>

    <!-- ===========================
         EXISTING TOKENS
    ============================ -->
    <?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}"
                   placeholder="Enter reason"
                   required>
        `;
    }
}
</script>

<?php
$content = ob_get_clean();

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