<?php
// Filename: admin_qrcodes.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
// Allowed: Admin, Principal, Assistant, Timetable Coord, AND Class Teachers (Role 'teacher')
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'principal', 'assistant', 'assistant_hem', 'timetable_coord', 'teacher'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

// 2. FETCH CLASSES
$stmt = $pdo->query("SELECT * FROM classes ORDER BY form_level ASC, class_name ASC");
$all_classes = $stmt->fetchAll();

// 3. GROUP BY FORM
$grouped = [];
foreach ($all_classes as $c) {
    $label = ($c['form_level'] == 0) ? "Others" : "Form " . $c['form_level'];
    $grouped[$label][] = $c;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QR Codes Center</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; ... }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD (CONTROLS) */
        .floating-card {
            background: white; margin: -60px 20px 20px 20px;
            border-radius: 24px; padding: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        /* QR CARD DESIGN */
        .qr-card {
            background: white; border: 1px solid #f1f5f9; border-radius: 20px;
            padding: 25px 15px; text-align: center; height: 100%;
            box-shadow: 0 4px 10px rgba(0,0,0,0.02); transition: transform 0.2s;
            page-break-inside: avoid;
        }
        .qr-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.08); }

        .class-title { font-weight: 800; font-size: 1.2rem; color: var(--text-dark); text-transform: uppercase; letter-spacing: 0.5px; }
        .qr-box { margin: 15px auto; display: flex; justify-content: center; }
        .token-badge { background: #f1f5f9; color: var(--text-gray); font-family: monospace; padding: 4px 12px; border-radius: 8px; font-size: 0.8rem; letter-spacing: 1px; }

        /* TABS */
        .nav-pills { gap: 8px; overflow-x: auto; flex-wrap: nowrap; padding-bottom: 5px; }
        .nav-pills::-webkit-scrollbar { display: none; }
        .nav-link { 
            border-radius: 50px; color: var(--text-gray); font-weight: 700; 
            padding: 8px 20px; background: #f1f5f9; white-space: nowrap; font-size: 0.85rem;
        }
        .nav-link.active { background: #8B5CF6; color: white; box-shadow: 0 4px 10px rgba(139, 92, 246, 0.3); }

        /* BOTTOM NAV 
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; } */

        /* PRINT STYLES */
        @media print {
            body { background: white; padding: 0; }
            .no-print, .app-header, .bottom-nav, .floating-card { display: none !important; }
            .container { max-width: 100% !important; padding: 0 !important; }
            
            /* Force show all tabs content when printing */
            .tab-pane { display: block !important; opacity: 1 !important; visibility: visible !important; }
            .tab-content { display: block !important; }
            
            /* Print Grid */
            .row { display: flex; flex-wrap: wrap; }
            .col-md-6, .col-lg-4 { width: 50% !important; flex: 0 0 50%; max-width: 50%; padding: 10px; }
            
            .qr-card { box-shadow: none !important; border: 2px solid #000; break-inside: avoid; }
            
            /* Hide non-active tabs if you only want to print the active one? 
               Usually printing all is safer, or user selects specific tab then prints. 
               Current logic below prints *everything* unless we hide inactive. */
            .tab-pane:not(.active) { display: none !important; }
        }
    </style>
</head>
<body>

    <div class="app-header no-print">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">QR Codes</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Classroom Attendance Tokens</div>
    </div>

    <div class="floating-card no-print">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold text-dark m-0">Print Center</h6>
            <button onclick="window.print()" class="btn btn-primary btn-sm rounded-pill fw-bold px-3 shadow-sm">
                <i class="bi bi-printer-fill me-1"></i> Print View
            </button>
        </div>
        <p class="small text-muted mb-0">Select a tab below to filter classes. Click "Print View" to print the currently visible tab.</p>
    </div>

    <div class="container px-3 pb-4">
        
        <ul class="nav nav-pills mb-4 no-print" id="qrTabs" role="tablist">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tab-all">All Classes</button>
            </li>
            <?php foreach(array_keys($grouped) as $i => $formName): ?>
                <li class="nav-item">
                    <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-<?= md5($formName) ?>"><?= $formName ?></button>
                </li>
            <?php endforeach; ?>
        </ul>

        <div class="tab-content">
            
            <div class="tab-pane fade show active" id="tab-all">
                <div class="row g-3">
                    <?php 
                    foreach($all_classes as $c) {
                        renderQrItem($c, 'all'); 
                    }
                    ?>
                </div>
            </div>

            <?php foreach($grouped as $formName => $classes): ?>
                <div class="tab-pane fade" id="tab-<?= md5($formName) ?>">
                    <div class="alert alert-info no-print small mb-3">
                        <i class="bi bi-info-circle me-2"></i>Printing now will only print <strong><?= $formName ?></strong> cards.
                    </div>
                    <div class="row g-3">
                        <?php 
                        foreach($classes as $c) {
                            renderQrItem($c, md5($formName));
                        }
                        ?>
                    </div>
                </div>
            <?php endforeach; ?>

        </div>
    </div>

    <?php
    function renderQrItem($c, $suffix) {
        $uniqueId = "qr_" . $c['id'] . "_" . $suffix;
        ?>
        <div class="col-md-6 col-lg-4">
            <div class="qr-card">
                <div class="text-primary small fw-bold mb-1">SCAN ATTENDANCE</div>
                <div class="class-title"><?= htmlspecialchars($c['class_name']) ?></div>
                
                <div class="qr-box" id="<?= $uniqueId ?>"></div>
                
                <div class="token-badge">
                    TOKEN: <?= htmlspecialchars($c['qr_token']) ?>
                </div>
            </div>
            <script>
                // Generate QR immediately inline
                document.addEventListener('DOMContentLoaded', function() {
                    new QRCode(document.getElementById("<?= $uniqueId ?>"), {
                        text: "<?= htmlspecialchars($c['qr_token']) ?>",
                        width: 150,
                        height: 150,
                        colorDark : "#000000",
                        colorLight : "#ffffff",
                        correctLevel : QRCode.CorrectLevel.H
                    });
                });
            </script>
        </div>
        <?php
    }
    ?>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>