<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/database.php';

requireRole(['ADMIN', 'ORGANIZER']);

$pdo = getDatabaseConnection();

$stmt = $pdo->query("SELECT id, title, eventDate, venue FROM events ORDER BY createdAt DESC");
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);

$selectedEventId = $_GET['eventId'] ?? ($events[0]['id'] ?? '');

$attendanceStats = [
    'presentCount' => 0,
    'totalRegistrations' => 0,
    'attendances' => []
];

if ($selectedEventId) {
    // Total Regs
    $regStmt = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE eventId = ?");
    $regStmt->execute([$selectedEventId]);
    $attendanceStats['totalRegistrations'] = $regStmt->fetchColumn();

    // All Registrations with Attendance Status
    $attStmt = $pdo->prepare("
        SELECT r.registrationId, r.fullName, r.email, a.scannedAt 
        FROM registrations r
        LEFT JOIN attendance a ON r.id = a.registrationId
        WHERE r.eventId = ?
        ORDER BY a.scannedAt DESC, r.createdAt DESC
    ");
    $attStmt->execute([$selectedEventId]);
    $attendances = $attStmt->fetchAll(PDO::FETCH_ASSOC);
    $attendanceStats['presentCount'] = count(array_filter($attendances, fn($a) => $a['scannedAt'] !== null));
    $attendanceStats['attendances'] = $attendances;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Dashboard - <?= APP_NAME ?></title>
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/style.css">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<body class="bg-slate-950 text-slate-200 antialiased selection:bg-cyan-500/30 selection:text-cyan-200 min-h-screen">
    <div class="min-h-screen bg-cyber-grid py-10 px-4 sm:px-6 lg:px-8 font-tech">
        <div class="max-w-7xl mx-auto">
            <div class="flex flex-wrap items-center justify-between gap-4 mb-8 border-b border-cyan-500/20 pb-6">
                <div>
                    <div class="flex items-center gap-2 text-cyan-400 text-xs font-mono-cyber uppercase mb-1">
                        <i data-lucide="shield-check" class="w-4 h-4 text-cyan-400"></i> SUPERNOVA 2.0 • ORGANIZER DESK
                    </div>
                    <h1 class="text-3xl sm:text-4xl font-heading-cyber font-extrabold text-slate-100">
                        ATTENDANCE DESK
                    </h1>
                </div>

                <div class="flex items-center gap-4">
                    <form method="GET" class="flex gap-2">
                        <select name="eventId" onchange="this.form.submit()" class="px-4 py-2.5 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-100 focus:outline-none focus:border-cyan-400 text-xs font-mono-cyber font-bold">
                            <?php foreach ($events as $evt): ?>
                                <option value="<?= htmlspecialchars($evt['id']) ?>" <?= $selectedEventId === $evt['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($evt['title']) ?> (<?= htmlspecialchars($evt['eventDate']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <a href="javascript:history.back()" class="px-4 py-2.5 rounded-xl glass-panel text-slate-300 hover:text-cyan-400 border border-cyan-500/20 text-xs font-mono-cyber font-semibold flex items-center gap-1.5">
                            <i data-lucide="arrow-left" class="w-4 h-4 text-cyan-400"></i> BACK
                        </a>
                        <a href="<?= APP_URL ?>/admin/dashboard.php" class="px-4 py-2.5 rounded-xl glass-panel text-purple-400 hover:text-white border border-purple-500/20 text-xs font-mono-cyber font-semibold flex items-center gap-1.5">
                            <i data-lucide="shield-check" class="w-4 h-4 text-purple-400"></i> ADMIN DASHBOARD
                        </a>
                    </form>
                </div>
            </div>

            <?php
                $selectedEvt = array_filter($events, fn($e) => $e['id'] === $selectedEventId);
                $selectedEvt = array_shift($selectedEvt);
                $venueUrl = APP_URL . "/attendance/venue-scan.php?eventId=" . urlencode($selectedEventId) . "&title=" . urlencode($selectedEvt['title'] ?? '');
            ?>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-8 mb-10">
                <!-- QR Code Card -->
                <div class="glass-panel p-6 rounded-3xl border border-cyan-500/30 text-center flex flex-col items-center justify-center shadow-glow-cyan">
                    <span class="text-[10px] text-cyan-400 font-mono-cyber uppercase tracking-widest block mb-1">
                        [LIVE VENUE SCREEN]
                    </span>
                    <h3 class="text-sm font-bold text-slate-200 uppercase tracking-wider mb-4 font-mono-cyber">
                        <?= htmlspecialchars($selectedEvt['title'] ?? 'EVENT') ?> ATTENDANCE QR
                    </h3>

                    <div class="bg-slate-950 p-4 rounded-2xl border border-cyan-500/40 mb-4 shadow-glow-cyan relative group">
                        <div id="qrcode" class="w-48 h-48 mx-auto rounded-xl overflow-hidden bg-white p-2"></div>
                    </div>

                    <p class="text-xs text-slate-400 mb-4 font-tech">
                        Participants scan with their mobile phone at the venue to mark check-in & receive their PDF certificate.
                    </p>

                    <div class="flex flex-col sm:flex-row items-center gap-2 w-full">
                        <button onclick="document.getElementById('projector-modal').classList.remove('hidden')" class="w-full py-2.5 rounded-xl bg-gradient-to-r from-cyan-500 to-purple-600 text-slate-950 font-mono-cyber font-bold text-xs transition-all shadow-glow-cyan flex items-center justify-center gap-2">
                            <i data-lucide="maximize-2" class="w-4 h-4"></i> PROJECT FULLSCREEN
                        </button>
                        <button onclick="copyUrl()" class="w-full py-2.5 rounded-xl glass-panel border border-cyan-500/20 text-cyan-400 text-xs font-mono-cyber hover:text-white transition-colors flex items-center justify-center gap-1.5" id="copy-btn">
                            <i data-lucide="copy" class="w-3.5 h-3.5"></i> COPY SCAN URL
                        </button>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div class="md:col-span-2 space-y-6">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <div class="glass-panel p-6 rounded-2xl border border-emerald-500/30 shadow-glow-cyan">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs text-emerald-400 font-mono-cyber uppercase">Present Attendees</span>
                                <div class="p-2 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">
                                    <i data-lucide="check-circle-2" class="w-5 h-5"></i>
                                </div>
                            </div>
                            <span class="text-4xl font-mono-cyber font-extrabold text-emerald-400">
                                <?= $attendanceStats['presentCount'] ?>
                            </span>
                            <span class="text-xs text-slate-400 block mt-1 font-tech">Checked-in at venue</span>
                        </div>

                        <div class="glass-panel p-6 rounded-2xl border border-cyan-500/30">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs text-cyan-400 font-mono-cyber uppercase">Total Registrations</span>
                                <div class="p-2 rounded-lg bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                                    <i data-lucide="users" class="w-5 h-5"></i>
                                </div>
                            </div>
                            <span class="text-4xl font-mono-cyber font-extrabold text-cyan-400">
                                <?= $attendanceStats['totalRegistrations'] ?>
                            </span>
                            <span class="text-xs text-slate-400 block mt-1 font-tech">Registered participants</span>
                        </div>
                    </div>

                    <!-- Present Attendees Table -->
                    <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                        <h3 class="text-base font-bold text-slate-200 mb-4 font-mono-cyber uppercase text-cyan-400 flex items-center gap-2">
                            <i data-lucide="sparkles" class="w-4 h-4 text-amber-400"></i> LIVE VENUE CHECK-IN LEDGER
                        </h3>
                        <div class="overflow-x-auto">
                            <table class="w-full text-left text-xs text-slate-300">
                                <thead class="bg-slate-900/90 text-cyan-400 uppercase text-[10px] font-mono-cyber font-bold">
                                    <tr>
                                        <th class="p-3 rounded-l-lg">REG ID</th>
                                        <th class="p-3">PARTICIPANT NAME</th>
                                        <th class="p-3">EMAIL</th>
                                        <th class="p-3 rounded-r-lg">CHECK-IN TIME</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-white/5 font-tech">
                                    <?php if (count($attendanceStats['attendances']) === 0): ?>
                                    <tr>
                                        <td colSpan="4" class="text-center py-6 text-slate-500 font-mono-cyber">
                                            No registrations found for this event session.
                                        </td>
                                    </tr>
                                    <?php else: ?>
                                        <?php foreach ($attendanceStats['attendances'] as $att): ?>
                                        <tr class="hover:bg-cyan-500/5 transition-colors">
                                            <td class="p-3 font-mono-cyber font-bold text-cyan-400"><?= htmlspecialchars($att['registrationId']) ?></td>
                                            <td class="p-3 font-semibold text-slate-200"><?= htmlspecialchars($att['fullName']) ?></td>
                                            <td class="p-3 text-slate-400 font-mono-cyber"><?= htmlspecialchars($att['email']) ?></td>
                                            <td class="p-3 text-slate-400 font-mono-cyber">
                                                <?php if ($att['scannedAt']): ?>
                                                    <span class="text-emerald-400 font-bold flex items-center gap-1"><i data-lucide="check-circle-2" class="w-3.5 h-3.5"></i> <?= htmlspecialchars($att['scannedAt']) ?></span>
                                                <?php else: ?>
                                                    <span class="text-slate-500 font-medium flex items-center gap-1"><i data-lucide="x-circle" class="w-3.5 h-3.5"></i> Pending</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Fullscreen Auditorium QR Projector Modal -->
        <div id="projector-modal" class="fixed inset-0 z-50 bg-slate-950/95 backdrop-blur-2xl flex-col items-center justify-center p-6 text-center hidden">
            <button onclick="document.getElementById('projector-modal').classList.add('hidden')" class="absolute top-6 right-6 p-3 rounded-full bg-slate-900 border border-cyan-500/40 text-cyan-400 hover:text-white">
                <i data-lucide="x" class="w-8 h-8"></i>
            </button>

            <span class="text-cyan-400 text-xs font-mono-cyber uppercase tracking-widest mb-2 block">
                [SUPERNOVA 2.0 • VENUE STAGE DISPLAY]
            </span>
            <h1 class="text-4xl sm:text-6xl font-heading-cyber font-black text-white mb-2">
                <?= strtoupper(htmlspecialchars($selectedEvt['title'] ?? 'SUPERNOVA EVENT')) ?>
            </h1>
            <p class="text-slate-300 text-sm font-tech mb-8">
                SCAN THIS QR CODE ON YOUR PHONE CAMERA TO MARK ATTENDANCE & RECEIVE CERTIFICATE
            </p>

            <div class="bg-slate-900 p-6 sm:p-8 rounded-3xl border-2 border-cyan-400 shadow-glow-cyan mb-8 inline-block">
                <div id="qrcode-fullscreen" class="mx-auto rounded-2xl overflow-hidden bg-white p-4"></div>
            </div>

            <div class="px-6 py-2 rounded-full bg-cyan-500/10 border border-cyan-500/30 text-cyan-400 text-sm font-mono-cyber font-bold">
                VENUE: <?= htmlspecialchars($selectedEvt['venue'] ?? '') ?> • DATE: <?= htmlspecialchars($selectedEvt['eventDate'] ?? '') ?>
            </div>
        </div>
    </div>
    
    <script>
        lucide.createIcons();
        
        const venueUrl = <?= json_encode($venueUrl) ?>;
        
        if (venueUrl) {
            new QRCode(document.getElementById("qrcode"), {
                text: venueUrl,
                width: 176,
                height: 176,
                colorDark : "#0f172a",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H
            });
            
            new QRCode(document.getElementById("qrcode-fullscreen"), {
                text: venueUrl,
                width: 320,
                height: 320,
                colorDark : "#0f172a",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H
            });
        }
        
        function copyUrl() {
            navigator.clipboard.writeText(venueUrl);
            const btn = document.getElementById('copy-btn');
            btn.innerHTML = '<i data-lucide="check" class="w-3.5 h-3.5"></i> COPIED!';
            lucide.createIcons();
            setTimeout(() => {
                btn.innerHTML = '<i data-lucide="copy" class="w-3.5 h-3.5"></i> COPY SCAN URL';
                lucide.createIcons();
            }, 2000);
        }
    </script>
</body>
</html>
