<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }
require_once '../config.php';
require_once '../includes/canteen_helpers.php';
canteen_require_active();
canteen_require_role(['admin']);

$conn = getDBConnection();

// ── AJAX: run the generation ──────────────────────────────────────────────────
if (isset($_GET['run']) && $_GET['run'] === '1') {
    header('Content-Type: application/json');

    $stmt = $conn->prepare(
        "SELECT id FROM students WHERE identity_qr_token IS NULL AND status = 'active' ORDER BY id"
    );
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $generated = 0;
    $skipped   = 0;
    $errors    = 0;

    foreach ($rows as $row) {
        $student_id = (int) $row['id'];
        $token      = canteen_generate_identity_token($student_id);
        $now        = date('Y-m-d H:i:s');

        $upd = $conn->prepare(
            "UPDATE students
             SET identity_qr_token = ?, identity_qr_generated_at = ?
             WHERE id = ? AND identity_qr_token IS NULL"
        );
        $upd->bind_param('ssi', $token, $now, $student_id);
        $upd->execute();

        if ($upd->affected_rows === 1) {
            $generated++;
        } elseif ($upd->affected_rows === 0) {
            // Another process already set the token (race condition) — safe
            $skipped++;
        } else {
            $errors++;
        }
        $upd->close();
    }

    // Count remaining NULLs as final check
    $check = $conn->query("SELECT COUNT(*) AS cnt FROM students WHERE identity_qr_token IS NULL");
    $remaining = (int) $check->fetch_assoc()['cnt'];

    echo json_encode([
        'success'   => true,
        'generated' => $generated,
        'skipped'   => $skipped,
        'errors'    => $errors,
        'remaining' => $remaining,
    ]);
    exit;
}

// ── Stats for the page load ───────────────────────────────────────────────────
$total_res   = $conn->query("SELECT COUNT(*) AS cnt FROM students WHERE status = 'active'");
$total       = (int) $total_res->fetch_assoc()['cnt'];

$missing_res = $conn->query("SELECT COUNT(*) AS cnt FROM students WHERE identity_qr_token IS NULL AND status = 'active'");
$missing     = (int) $missing_res->fetch_assoc()['cnt'];

$done = $total - $missing;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Identity QR Tokens — EduTrack Canteen</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('canteen/generate_identity_qrs.php'); ?>
    </nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right">
                <div class="dropdown">
                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                    </ul>
                </div>
            </div>
        </header>
        <main class="content">
            <div class="content-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h2><i class="fas fa-qrcode me-2"></i>Generate Student Identity QR Tokens</h2>
                        <p class="text-muted mb-0">Permanent QR codes for the fee desk. Run once — safe to re-run (skips existing tokens).</p>
                    </div>
                    <a href="settings.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i>Back to Settings
                    </a>
                </div>
            </div>

            <!-- Status card -->
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="card text-center">
                        <div class="card-body py-3">
                            <div class="fs-2 fw-bold text-primary"><?php echo $total; ?></div>
                            <div class="text-muted small">Active Students</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-center">
                        <div class="card-body py-3">
                            <div class="fs-2 fw-bold text-success" id="stat-done"><?php echo $done; ?></div>
                            <div class="text-muted small">Have QR Token</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-center border-<?php echo $missing > 0 ? 'warning' : 'success'; ?>">
                        <div class="card-body py-3">
                            <div class="fs-2 fw-bold <?php echo $missing > 0 ? 'text-warning' : 'text-success'; ?>" id="stat-missing"><?php echo $missing; ?></div>
                            <div class="text-muted small">Missing QR Token</div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if ($missing === 0): ?>
            <div class="alert alert-success d-flex align-items-center gap-3">
                <i class="fas fa-check-circle fa-2x"></i>
                <div>
                    <strong>All students have identity QR tokens.</strong><br>
                    <span class="text-muted small">You can print student ID cards from the Settings → Student ID Cards tab.</span>
                </div>
            </div>
            <?php else: ?>
            <!-- Progress (hidden until run starts) -->
            <div id="progress-wrap" class="mb-4" style="display:none;">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="fw-semibold">Generating tokens…</span>
                            <span id="progress-label">0 / <?php echo $missing; ?></span>
                        </div>
                        <div class="progress" style="height:10px;">
                            <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated bg-primary"
                                 style="width:0%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div id="result-wrap" class="mb-4" style="display:none;"></div>

            <button id="btn-run" class="btn btn-primary btn-lg">
                <i class="fas fa-play me-2"></i>Generate <?php echo $missing; ?> Missing QR Token<?php echo $missing === 1 ? '' : 's'; ?>
            </button>
            <p class="text-muted small mt-2">
                <i class="fas fa-info-circle me-1"></i>
                This is idempotent — existing tokens are never overwritten. Runs in a single AJAX request.
            </p>
            <?php endif; ?>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
(function () {
    const btn = document.getElementById('btn-run');
    if (!btn) return;

    btn.addEventListener('click', function () {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Running…';
        document.getElementById('progress-wrap').style.display = 'block';

        fetch('generate_identity_qrs.php?run=1', { method: 'GET', credentials: 'same-origin' })
            .then(r => r.json())
            .then(data => {
                // Animate progress to 100 %
                const bar   = document.getElementById('progress-bar');
                const label = document.getElementById('progress-label');
                const total = <?php echo $missing; ?>;
                bar.style.width   = '100%';
                bar.classList.remove('progress-bar-animated');
                bar.classList.add('bg-success');
                label.textContent = total + ' / ' + total;

                // Show result
                const rw = document.getElementById('result-wrap');
                rw.style.display = 'block';
                if (data.success && data.remaining === 0) {
                    rw.innerHTML = `<div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        <strong>Done!</strong> ${data.generated} token(s) generated.
                        ${data.errors > 0 ? `<span class="text-danger ms-2">${data.errors} error(s) — check server logs.</span>` : ''}
                        <a href="settings.php" class="btn btn-sm btn-success ms-3">Continue to Settings</a>
                    </div>`;
                    document.getElementById('stat-done').textContent  = parseInt(document.getElementById('stat-done').textContent) + data.generated;
                    document.getElementById('stat-missing').textContent = '0';
                } else {
                    rw.innerHTML = `<div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Generated ${data.generated}. <strong>${data.remaining} still missing</strong> — re-run to retry.
                        ${data.errors > 0 ? `${data.errors} error(s) logged.` : ''}
                    </div>`;
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-redo me-2"></i>Re-run for Remaining ' + data.remaining;
                }
            })
            .catch(() => {
                document.getElementById('result-wrap').style.display = 'block';
                document.getElementById('result-wrap').innerHTML = `<div class="alert alert-danger">
                    <i class="fas fa-times-circle me-2"></i>Network error — please try again.
                </div>`;
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-play me-2"></i>Retry';
            });
    });
})();
</script>
</body>
</html>
