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

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

// CSRF: validate every state-changing POST on this page
require_csrf();

$pdo = getDatabaseConnection();

// Handle Event Proposal Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'propose_event') {
    $title = $_POST['title'] ?? '';
    $category = $_POST['category'] ?? '';
    $description = $_POST['description'] ?? '';
    $rulesText = $_POST['rules'] ?? '';
    $venue = $_POST['venue'] ?? '';
    $eventDate = $_POST['eventDate'] ?? '';
    $reportingTime = $_POST['reportingTime'] ?? '';
    $registrationFee = (float)($_POST['registrationFee'] ?? 0);
    $prizePool = (float)($_POST['prizePool'] ?? 0);
    $coordName = $_POST['coordinatorName'] ?? '';
    $coordPhone = $_POST['coordinatorPhone'] ?? '';

    $rulesArray = array_filter(array_map('trim', explode("\n", $rulesText)));
    $rulesJson = json_encode(array_values($rulesArray));

    // Generate slug from title
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));

    $stmt = $pdo->prepare("INSERT INTO events (id, title, slug, category, description, rules, venue, eventDate, reportingTime, registrationFee, prizePool, status) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING_APPROVAL')");
    $stmt->execute([$title, $slug, $category, $description, $rulesJson, $venue, $eventDate, $reportingTime, $registrationFee, $prizePool]);
    
    // Fetch inserted event id
    $stmt2 = $pdo->prepare("SELECT id FROM events WHERE slug = ? ORDER BY createdAt DESC LIMIT 1");
    $stmt2->execute([$slug]);
    $newEvent = $stmt2->fetch();

    if ($newEvent && $coordName) {
        $stmt3 = $pdo->prepare("INSERT INTO coordinators (id, eventId, name, phone) VALUES (UUID(), ?, ?, ?)");
        $stmt3->execute([$newEvent['id'], $coordName, $coordPhone]);
    }
    
    header("Location: dashboard.php?msg=proposed");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_event') {
    $eventId = $_POST['event_id'] ?? '';
    $stmt = $pdo->prepare("DELETE FROM events WHERE id = ?");
    $stmt->execute([$eventId]);
    header("Location: dashboard.php");
    exit;
}

// Handle File Upload Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_resource') {
    if (isset($_FILES['resource_file'])) {
        $file = $_FILES['resource_file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            // Sanitize filename
            $filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($file['name']));

            // Extension allowlist — never accept executable/script types.
            // Checked against the FULL name so double extensions (x.php.jpg is
            // fine, x.jpg.php is not) can't smuggle code onto the server.
            $allowedExts = ['pdf','png','jpg','jpeg','gif','webp','xls','xlsx','csv','doc','docx','ppt','pptx','txt','zip'];
            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if (!in_array($ext, $allowedExts, true)) {
                header("Location: dashboard.php?tab=files&msg=upload_failed");
                exit;
            }

            // Move uploaded file to our uploads folder
            if (move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
                header("Location: dashboard.php?tab=files&msg=file_uploaded");
                exit;
            }
        }
    }
    header("Location: dashboard.php?tab=files&msg=upload_failed");
    exit;
}

// Handle File Delete Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_resource') {
    $filename = $_POST['filename'] ?? '';
    // Prevent directory traversal
    if ($filename && preg_match('/^[a-zA-Z0-9._-]+$/', $filename)) {
        // 1. Delete associated registrations from DB (cascades to payments & attendance)
        $delRegs = $pdo->prepare("DELETE FROM registrations WHERE importSource = ?");
        $delRegs->execute([$filename]);

        // 2. Delete the physical file from disk
        $filePath = __DIR__ . '/../uploads/' . $filename;
        if (file_exists($filePath)) {
            unlink($filePath);
            $redirectTab = str_starts_with($filename, 'import_') ? 'analytics' : 'files';
            header("Location: dashboard.php?tab=" . $redirectTab . "&msg=file_deleted");
            exit;
        }
    }
    header("Location: dashboard.php?tab=files&msg=delete_failed");
    exit;
}

// Fetch Files inside uploads directory
$uploadDir = __DIR__ . '/../uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}
$files = [];
if ($handle = opendir($uploadDir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $filePath = $uploadDir . $entry;
            if (is_file($filePath)) {
                $files[] = [
                    'name' => $entry,
                    'size' => filesize($filePath),
                    'mtime' => filemtime($filePath),
                    'ext' => strtolower(pathinfo($entry, PATHINFO_EXTENSION))
                ];
            }
        }
    }
    closedir($handle);
}
// Sort files by modified time descending
usort($files, fn($a, $b) => $b['mtime'] <=> $a['mtime']);

// Fetch Events
$eventStmt = $pdo->query("SELECT * FROM events ORDER BY createdAt DESC");
$events = $eventStmt->fetchAll();

// Fetch Registrations for Analytics
// Requires joining registrations, events, payments, and attendance
$regQuery = "
    SELECT r.id, r.registrationId, r.fullName, r.email, r.mobileNumber, r.college, r.city, r.createdAt,
           e.title as eventTitle,
           p.status as paymentStatus, p.amount as paymentAmount, p.razorpayPaymentId,
           a.id as attendanceId
    FROM registrations r
    LEFT JOIN events e ON r.eventId = e.id
    LEFT JOIN payments p ON p.registrationId = r.id
    LEFT JOIN attendance a ON a.registrationId = r.id
    ORDER BY r.createdAt DESC
";
$regStmt = $pdo->query($regQuery);
$registrations = $regStmt->fetchAll(PDO::FETCH_ASSOC);

function formatFee($fee) { return $fee == 0 ? 'Free' : '₹' . number_format($fee); }
function formatPrize($prize) { return '₹' . number_format($prize); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Organizer 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://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.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">
            <!-- Header -->
            <div class="flex flex-wrap items-center justify-between gap-4 mb-6 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 CONTROL PANEL
                    </div>
                    <h1 class="text-3xl sm:text-4xl font-heading-cyber font-extrabold text-slate-100">
                        ORGANIZER DASHBOARD
                    </h1>
                </div>

                <div class="flex items-center gap-3">
                    <a href="javascript:history.back()" class="px-4 py-2.5 rounded-xl glass-panel text-slate-300 hover:text-cyan-400 text-xs font-mono-cyber font-semibold flex items-center gap-1.5 border border-cyan-500/20">
                        <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 text-xs font-mono-cyber font-semibold flex items-center gap-1.5 border border-purple-500/20">
                        <i data-lucide="shield-check" class="w-4 h-4 text-purple-400"></i> ADMIN DASHBOARD
                    </a>
                    <a href="<?= APP_URL ?>/attendance/dashboard.php" class="px-4 py-2.5 rounded-xl glass-panel text-slate-300 hover:text-cyan-400 text-xs font-mono-cyber font-semibold flex items-center gap-1.5 border border-cyan-500/20">
                        <i data-lucide="ticket" class="w-4 h-4 text-cyan-400"></i> ATTENDANCE DESK
                    </a>
                    <a href="<?= APP_URL ?>/admin/logout.php" class="px-4 py-2.5 rounded-xl glass-panel text-slate-400 hover:text-red-400 text-xs font-mono-cyber font-semibold border border-white/10">
                        SIGN OUT
                    </a>
                </div>
            </div>

            <?php $activeTab = $_GET['tab'] ?? 'events'; ?>
            <!-- Tabs -->
            <div class="flex items-center gap-2 mb-8">
                <button id="tab-events" class="px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 <?= $activeTab === 'events' ? 'bg-cyan-500 text-slate-950 shadow-glow-cyan' : 'glass-panel text-slate-400 border border-white/5 hover:text-white' ?> tab-btn">
                    <i data-lucide="calendar" class="w-4 h-4"></i> EVENT PROPOSALS
                </button>
                <button id="tab-analytics" class="px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 <?= $activeTab === 'analytics' ? 'bg-purple-500 text-white shadow-glow-purple' : 'glass-panel text-slate-400 border border-white/5 hover:text-white' ?> tab-btn">
                    <i data-lucide="bar-chart-3" class="w-4 h-4"></i> REGISTRATION ANALYTICS
                </button>
                <button id="tab-files" class="px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 <?= $activeTab === 'files' ? 'bg-pink-500 text-white shadow-glow-pink' : 'glass-panel text-slate-400 border border-white/5 hover:text-white' ?> tab-btn">
                    <i data-lucide="folder-open" class="w-4 h-4"></i> FILE MANAGER
                </button>
            </div>

            <?php if (isset($_GET['msg']) && $_GET['msg'] === 'proposed'): ?>
            <div class="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm font-tech flex items-center gap-3">
                <i data-lucide="check-circle-2" class="w-5 h-5 shrink-0"></i>
                <span>Event proposed successfully! Status set to PENDING APPROVAL by Admin.</span>
            </div>
            <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'file_uploaded'): ?>
            <div class="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm font-tech flex items-center gap-3">
                <i data-lucide="check-circle-2" class="w-5 h-5 shrink-0"></i>
                <span>Resource file uploaded successfully!</span>
            </div>
            <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'upload_failed'): ?>
            <div class="mb-6 p-4 rounded-2xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm font-tech flex items-center gap-3">
                <i data-lucide="alert-triangle" class="w-5 h-5 shrink-0"></i>
                <span>Failed to upload the resource file. Please make sure it is a valid file.</span>
            </div>
            <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'file_deleted'): ?>
            <div class="mb-6 p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm font-tech flex items-center gap-3">
                <i data-lucide="check-circle-2" class="w-5 h-5 shrink-0"></i>
                <span>File deleted successfully from the server!</span>
            </div>
            <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'delete_failed'): ?>
            <div class="mb-6 p-4 rounded-2xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm font-tech flex items-center gap-3">
                <i data-lucide="alert-triangle" class="w-5 h-5 shrink-0"></i>
                <span>Failed to delete the file.</span>
            </div>
            <?php endif; ?>

            <!-- EVENTS TAB -->
            <div id="content-events" class="tab-content <?= $activeTab === 'events' ? '' : 'hidden' ?>">
                <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-heading-cyber font-bold text-slate-100">ALL MANAGED EVENTS (<?= count($events) ?>)</h3>
                        <div class="flex gap-2">
                            <a href="dashboard.php" class="p-2.5 rounded-xl glass-panel text-cyan-400 hover:text-white border border-cyan-500/20">
                                <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                            </a>
                            <button id="btn-propose" class="px-4 py-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 text-slate-950 font-mono-cyber font-bold text-xs flex items-center gap-2 shadow-glow-cyan hover:scale-105">
                                <i data-lucide="plus" class="w-4 h-4"></i> PROPOSE NEW
                            </button>
                        </div>
                    </div>

                    <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 tracking-wider">
                                <tr>
                                    <th class="p-4 rounded-l-xl">EVENT TITLE</th>
                                    <th class="p-4">CATEGORY</th>
                                    <th class="p-4">DATE & VENUE</th>
                                    <th class="p-4">REGISTRATION FEE</th>
                                    <th class="p-4">APPROVAL STATUS</th>
                                    <th class="p-4 rounded-r-xl text-right">ACTIONS</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-white/5 font-tech">
                                <?php foreach ($events as $evt): ?>
                                <tr class="hover:bg-cyan-500/5 transition-colors">
                                    <td class="p-4 font-bold text-slate-100 text-sm"><?= htmlspecialchars($evt['title']) ?></td>
                                    <td class="p-4 text-purple-400 font-semibold"><?= htmlspecialchars($evt['category']) ?></td>
                                    <td class="p-4 text-slate-300">
                                        <div><?= htmlspecialchars($evt['eventDate']) ?></div>
                                        <div class="text-[10px] text-cyan-400 font-mono-cyber"><?= htmlspecialchars($evt['venue']) ?></div>
                                    </td>
                                    <td class="p-4 font-mono-cyber font-semibold">
                                        <div class="text-cyan-400"><?= formatFee($evt['registrationFee']) ?></div>
                                    </td>
                                    <td class="p-4">
                                        <span class="px-3 py-1 rounded-full text-[10px] font-mono-cyber font-bold uppercase inline-flex items-center gap-1 <?= 
                                            $evt['status'] === 'PUBLISHED' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 
                                            ($evt['status'] === 'PENDING_APPROVAL' ? 'bg-amber-500/10 text-amber-400 border border-amber-500/30' : 'bg-slate-800 text-slate-400 border border-slate-700') 
                                        ?>">
                                            <?= $evt['status'] === 'PUBLISHED' ? '<i data-lucide="check-circle-2" class="w-3 h-3"></i>' : '<i data-lucide="clock" class="w-3 h-3"></i>' ?>
                                            <?= $evt['status'] === 'PENDING_APPROVAL' ? 'PENDING ADMIN APPROVAL' : htmlspecialchars($evt['status']) ?>
                                        </span>
                                    </td>
                                    <td class="p-4 text-right space-x-2 flex justify-end gap-1">
                                        <a href="<?= APP_URL ?>/events/details.php?slug=<?= htmlspecialchars($evt['slug']) ?>" target="_blank" class="inline-block p-2 rounded-lg bg-slate-800 text-slate-300 hover:text-cyan-400 border border-white/10" title="View Public Page">
                                            <i data-lucide="eye" class="w-3.5 h-3.5"></i>
                                        </a>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Permanently delete proposal?');">
                                            <input type="hidden" name="action" value="delete_event"><?= csrf_field() ?>
                                            <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                            <button type="submit" class="p-2 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white transition-colors border border-red-500/20" title="Delete Proposal">
                                                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- ANALYTICS TAB -->
            <div id="content-analytics" class="tab-content <?= $activeTab === 'analytics' ? '' : 'hidden' ?> space-y-6">
                <!-- KPI Cards -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div id="card-kpi-total" class="glass-panel p-5 rounded-2xl border border-cyan-500/60 shadow-[0_0_15px_rgba(6,182,212,0.2)] relative overflow-hidden cursor-pointer hover:scale-[1.02] transition-all duration-300">
                        <div class="absolute top-0 right-0 p-4 opacity-20"><i data-lucide="users" class="w-12 h-12 text-cyan-400"></i></div>
                        <p class="text-xs font-mono-cyber text-slate-400 mb-1">TOTAL REGISTRATIONS</p>
                        <h3 id="kpi-total" class="text-3xl font-heading-cyber font-bold text-white">0</h3>
                    </div>
                    <div id="card-kpi-paid" class="glass-panel p-5 rounded-2xl border border-white/10 relative overflow-hidden cursor-pointer hover:border-white/30 hover:scale-[1.02] transition-all duration-300">
                        <div class="absolute top-0 right-0 p-4 opacity-20"><i data-lucide="check-circle-2" class="w-12 h-12 text-emerald-400"></i></div>
                        <p class="text-xs font-mono-cyber text-slate-400 mb-1">SUCCESSFUL PAYMENTS</p>
                        <h3 id="kpi-paid" class="text-3xl font-heading-cyber font-bold text-emerald-400">0</h3>
                    </div>
                    <div id="card-kpi-attended" class="glass-panel p-5 rounded-2xl border border-white/10 relative overflow-hidden cursor-pointer hover:border-white/30 hover:scale-[1.02] transition-all duration-300">
                        <div class="absolute top-0 right-0 p-4 opacity-20"><i data-lucide="user-check" class="w-12 h-12 text-purple-400"></i></div>
                        <p class="text-xs font-mono-cyber text-slate-400 mb-1">ATTENDANCE CHECK-INS</p>
                        <h3 id="kpi-attended" class="text-3xl font-heading-cyber font-bold text-purple-400">0</h3>
                    </div>
                    <div id="card-kpi-revenue" class="glass-panel p-5 rounded-2xl border border-white/10 relative overflow-hidden cursor-pointer hover:border-white/30 hover:scale-[1.02] transition-all duration-300">
                        <div class="absolute top-0 right-0 p-4 opacity-20"><i data-lucide="indian-rupee" class="w-12 h-12 text-amber-400"></i></div>
                        <p class="text-xs font-mono-cyber text-slate-400 mb-1">TOTAL REVENUE</p>
                        <h3 id="kpi-revenue" class="text-3xl font-heading-cyber font-bold text-amber-400">₹0</h3>
                    </div>
                </div>

                <!-- Controls -->
                <div class="glass-panel p-4 rounded-2xl border border-cyan-500/20 flex flex-wrap gap-4 items-center justify-between">
                    <div class="flex flex-wrap gap-3 flex-1">
                        <div class="relative flex-1 min-w-[200px] max-w-sm">
                            <i data-lucide="search" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
                            <input type="text" id="filter-search" placeholder="Search name, email, or Reg ID..." class="w-full bg-slate-900 border border-white/10 rounded-xl py-2 pl-9 pr-4 text-sm text-slate-200 outline-none focus:border-cyan-400 transition-colors" />
                        </div>
                        <select id="filter-event" class="bg-slate-900 border border-white/10 rounded-xl py-2 px-4 text-sm text-slate-200 outline-none focus:border-cyan-400">
                            <option value="ALL">All Events</option>
                        </select>
                        <select id="filter-payment" class="bg-slate-900 border border-white/10 rounded-xl py-2 px-4 text-sm text-slate-200 outline-none focus:border-cyan-400">
                            <option value="ALL">All Payments</option>
                            <option value="SUCCESSFUL">Successful</option>
                            <option value="PENDING">Pending</option>
                        </select>
                    </div>

                    <div class="flex gap-2">
                        <button id="btn-csv" class="p-2 rounded-xl bg-slate-800 text-slate-300 hover:text-white border border-white/10 flex items-center gap-2 text-xs font-bold" title="Export CSV">
                            <i data-lucide="file-text" class="w-4 h-4"></i> CSV
                        </button>
                        <button id="btn-excel" class="p-2 rounded-xl bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500 hover:text-white border border-emerald-500/20 flex items-center gap-2 text-xs font-bold" title="Export Excel">
                            <i data-lucide="file-spreadsheet" class="w-4 h-4"></i> EXCEL
                        </button>
                        <button id="btn-pdf" class="p-2 rounded-xl bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white border border-red-500/20 flex items-center gap-2 text-xs font-bold" title="Export PDF">
                            <i data-lucide="download" class="w-4 h-4"></i> PDF
                        </button>
                        <button id="btn-import-xls" class="p-2 rounded-xl bg-purple-500/10 text-purple-400 hover:bg-purple-500 hover:text-white border border-purple-500/20 flex items-center gap-2 text-xs font-bold" title="Import Attendance Sheet">
                            <i data-lucide="upload" class="w-4 h-4"></i> IMPORT XLS
                        </button>
                        <input type="file" id="import-file-input" accept=".xls,.xlsx,.csv" class="hidden" />
                    </div>
                </div>

                <!-- Data Table -->
                <div class="glass-panel rounded-3xl border border-cyan-500/20 shadow-glow-cyan overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-xs text-slate-300" id="analytics-table">
                            <thead class="bg-slate-900/90 text-cyan-400 uppercase text-[10px] font-mono-cyber font-bold tracking-wider">
                                <tr>
                                    <th class="p-4">PARTICIPANT INFO</th>
                                    <th class="p-4">COLLEGE / CITY</th>
                                    <th class="p-4">EVENT</th>
                                    <th class="p-4">PAYMENT</th>
                                    <th class="p-4">ATTENDANCE</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-white/5 font-tech" id="analytics-tbody">
                                <!-- JS will populate this -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- FILE MANAGER TAB -->
            <div id="content-files" class="tab-content <?= $activeTab === 'files' ? '' : 'hidden' ?> space-y-6">
                <!-- Upload Form Panel -->
                <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                    <h3 class="text-xl font-heading-cyber font-bold text-slate-100 mb-4">UPLOAD RESOURCE FILE</h3>
                    <form action="dashboard.php" method="POST" enctype="multipart/form-data" class="flex flex-col sm:flex-row items-center gap-4">
                        <input type="hidden" name="action" value="upload_resource" /><?= csrf_field() ?>
                        <div class="w-full sm:flex-1 relative">
                            <input type="file" name="resource_file" required class="w-full px-4 py-3 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-200 focus:outline-none focus:border-cyan-400 text-xs font-mono-cyber font-bold" />
                        </div>
                        <button type="submit" class="w-full sm:w-auto px-6 py-3 rounded-xl bg-gradient-to-r from-pink-500 to-purple-600 text-white font-mono-cyber font-bold text-xs flex items-center justify-center gap-2 shadow-glow-pink hover:scale-105 transition-transform duration-300">
                            <i data-lucide="upload-cloud" class="w-4 h-4"></i> UPLOAD TO SERVER
                        </button>
                    </form>
                </div>

                <!-- Files Table List -->
                <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                    <h3 class="text-xl font-heading-cyber font-bold text-slate-100 mb-6">STORED SERVER RESOURCES</h3>
                    <?php if (empty($files)): ?>
                        <div class="text-center py-12 text-slate-400 font-tech">
                            <i data-lucide="folder-archive" class="w-12 h-12 text-slate-500 mx-auto mb-4 opacity-50"></i>
                            <p>No uploaded resource files found in the server repository.</p>
                        </div>
                    <?php else: ?>
                        <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 tracking-wider">
                                    <tr>
                                        <th class="p-4">FILE DETAILS</th>
                                        <th class="p-4">EXTENSION</th>
                                        <th class="p-4">FILE SIZE</th>
                                        <th class="p-4">DATE MODIFIED</th>
                                        <th class="p-4 text-right">ACTIONS</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-white/5 font-tech">
                                    <?php foreach ($files as $file): 
                                        $fileIcon = 'file';
                                        $iconColor = 'text-slate-400';
                                        if (in_array($file['ext'], ['xls', 'xlsx', 'csv'])) {
                                            $fileIcon = 'file-spreadsheet';
                                            $iconColor = 'text-emerald-400';
                                        } elseif (in_array($file['ext'], ['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg'])) {
                                            $fileIcon = 'file-image';
                                            $iconColor = 'text-blue-400';
                                        } elseif ($file['ext'] === 'pdf') {
                                            $fileIcon = 'file-text';
                                            $iconColor = 'text-rose-400';
                                        }
                                    ?>
                                        <tr class="hover:bg-cyan-500/5 transition-colors">
                                            <td class="p-4">
                                                <div class="flex items-center gap-3">
                                                    <i data-lucide="<?= $fileIcon ?>" class="w-6 h-6 <?= $iconColor ?> shrink-0"></i>
                                                    <div>
                                                        <a href="<?= APP_URL ?>/uploads/<?= rawurlencode($file['name']) ?>" target="_blank" class="font-bold text-slate-100 hover:text-cyan-400 transition-colors text-sm break-all">
                                                            <?= htmlspecialchars($file['name']) ?>
                                                        </a>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="p-4">
                                                <span class="px-2 py-0.5 rounded bg-slate-900 border border-white/10 uppercase font-mono-cyber text-[10px] text-slate-400 font-bold"><?= htmlspecialchars($file['ext']) ?></span>
                                            </td>
                                            <td class="p-4 text-slate-400 font-mono-cyber">
                                                <?= number_format($file['size'] / 1024, 1) ?> KB
                                            </td>
                                            <td class="p-4 text-slate-400">
                                                <?= date('d M Y, H:i A', $file['mtime']) ?>
                                            </td>
                                            <td class="p-4 text-right">
                                                <form action="dashboard.php" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete this file? This action cannot be undone.');" class="inline">
                                                    <input type="hidden" name="action" value="delete_resource" /><?= csrf_field() ?>
                                                    <input type="hidden" name="filename" value="<?= htmlspecialchars($file['name']) ?>" />
                                                    <button type="submit" class="p-2 rounded-xl bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white border border-red-500/20 text-xs font-bold transition-all inline-flex items-center gap-1">
                                                        <i data-lucide="trash-2" class="w-3.5 h-3.5"></i> DELETE
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Import Modal -->
            <div id="modal-import" class="fixed inset-0 z-50 hidden items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md">
                <div class="glass-panel max-w-lg w-full max-h-[90vh] overflow-y-auto p-6 sm:p-8 rounded-3xl border border-purple-400/50 shadow-2xl">
                    <div class="flex items-center justify-between border-b border-purple-500/20 pb-4 mb-6">
                        <h3 class="text-xl font-heading-cyber font-bold text-white flex items-center gap-2">
                            <i data-lucide="upload" class="w-5 h-5 text-purple-400"></i> IMPORT ATTENDANCE SHEET
                        </h3>
                        <button id="btn-close-import" class="text-slate-400 hover:text-white font-bold text-lg">✕</button>
                    </div>

                    <div class="space-y-4">
                        <!-- Info Banner -->
                        <div id="import-info-banner" class="p-3 rounded-xl bg-purple-500/10 border border-purple-500/30 text-purple-300 text-xs font-tech leading-relaxed">
                            <strong>Supported formats:</strong> XLS, XLSX, CSV<br>
                            Automatically maps: Registration ID, Name, Email, Mobile, College, Event, Payment, Attendance Check-in
                        </div>

                        <!-- Drop Zone -->
                        <div id="import-dropzone" class="border-2 border-dashed border-purple-500/40 rounded-2xl p-8 text-center cursor-pointer hover:border-purple-400 hover:bg-purple-500/5 transition-all group">
                            <i data-lucide="file-spreadsheet" class="w-12 h-12 text-purple-400 mx-auto mb-3 group-hover:scale-110 transition-transform"></i>
                            <p class="text-slate-300 font-tech text-sm">Drop your XLS / XLSX / CSV file here</p>
                            <p class="text-slate-500 text-xs mt-1">or click to browse</p>
                            <p id="import-filename" class="text-cyan-400 text-xs font-mono-cyber mt-2 hidden"></p>
                        </div>

                        <!-- Progress -->
                        <div id="import-progress" class="hidden">
                            <div class="flex items-center gap-3 p-4 rounded-xl bg-slate-800 border border-white/10">
                                <div class="w-5 h-5 border-2 border-purple-400 border-t-transparent rounded-full animate-spin shrink-0"></div>
                                <span class="text-slate-300 text-sm font-tech">Processing file... please wait</span>
                            </div>
                        </div>

                        <!-- Results -->
                        <div id="import-results" class="hidden"></div>

                        <!-- Actions -->
                        <div class="flex items-center justify-end gap-3 pt-2">
                            <button id="btn-cancel-import" class="px-5 py-2.5 rounded-xl border border-white/10 text-slate-400 hover:text-white text-xs font-mono-cyber font-bold">CANCEL</button>
                            <button id="btn-do-import" disabled class="px-6 py-2.5 rounded-xl bg-gradient-to-r from-purple-500 to-cyan-600 text-white font-mono-cyber font-bold text-sm shadow-glow-cyan hover:scale-105 transition-all disabled:opacity-40 disabled:cursor-not-allowed disabled:scale-100">
                                <i data-lucide="upload" class="w-4 h-4 inline-block mr-1"></i> START IMPORT
                            </button>
                        </div>

                        <!-- Imported Sheets List -->
                        <div class="border-t border-purple-500/20 pt-4 mt-4">
                            <h4 class="text-xs font-mono-cyber font-bold text-purple-400 mb-3 uppercase tracking-wider">Recently Imported Sheets</h4>
                            <?php 
                            $importedSheets = array_filter($files, fn($f) => str_starts_with($f['name'], 'import_'));
                            if (empty($importedSheets)): 
                            ?>
                                <p class="text-[10px] text-slate-500 font-tech">No imported sheets found.</p>
                            <?php else: ?>
                                <div class="space-y-2 max-h-40 overflow-y-auto pr-1">
                                    <?php foreach ($importedSheets as $sheet): 
                                        $cleanName = preg_replace('/^import_\d{8}_\d{6}_/', '', $sheet['name']);
                                    ?>
                                        <div class="flex items-center justify-between p-2.5 rounded-xl bg-slate-900/80 border border-purple-500/10 text-xs font-tech">
                                            <div class="min-w-0 flex-1 pr-2">
                                                <div class="font-bold text-slate-200 truncate" title="<?= htmlspecialchars($sheet['name']) ?>"><?= htmlspecialchars($cleanName) ?></div>
                                                <div class="text-[9px] text-slate-500 font-mono-cyber"><?= date('d M Y, H:i', $sheet['mtime']) ?> • <?= number_format($sheet['size']/1024, 1) ?> KB</div>
                                            </div>
                                            <form action="dashboard.php" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete this import sheet and all associated student registrations? This action cannot be undone.');" class="shrink-0">
                                                <input type="hidden" name="action" value="delete_resource" /><?= csrf_field() ?>
                                                <input type="hidden" name="filename" value="<?= htmlspecialchars($sheet['name']) ?>" />
                                                <button type="submit" class="p-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white border border-red-500/20 transition-all" title="Delete sheet & all imported students">
                                                    <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                                                </button>
                                            </form>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Propose Modal -->
            <div id="modal-propose" class="fixed inset-0 z-50 hidden items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md">
                <div class="glass-panel max-w-2xl w-full p-6 sm:p-8 rounded-3xl border border-cyan-400/50 shadow-glow-cyan max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between border-b border-cyan-500/20 pb-4 mb-6">
                        <h3 class="text-2xl font-heading-cyber font-bold text-white flex items-center gap-2">
                            <i data-lucide="file-plus" class="w-6 h-6 text-cyan-400"></i> PROPOSE NEW EVENT TEMPLATE
                        </h3>
                        <button id="btn-close-modal" class="text-slate-400 hover:text-white font-bold text-lg">✕</button>
                    </div>

                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="action" value="propose_event"><?= csrf_field() ?>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Event Title *</label>
                                <input type="text" name="title" required placeholder="e.g. RoboWars" oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>
                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Category *</label>
                                <?php
                                $stmtCat = $pdo->query("SELECT DISTINCT category FROM events");
                                $dbCategories = $stmtCat->fetchAll(PDO::FETCH_COLUMN);
                                $defaultCategories = [
                                    'Coding & Algorithm', 'UI/UX & Creative Design', 'Hands-on Training',
                                    'Ideation & Pitching', 'Speed Coding & Debugging', 'Business & Entrepreneurship',
                                    'Project Showcase', 'Robotics & AI'
                                ];
                                $allCategories = array_unique(array_merge($defaultCategories, $dbCategories));
                                sort($allCategories);
                                ?>
                                <select name="category" id="category-select" onchange="toggleNewCategoryInput(this)" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none mb-2">
                                    <?php foreach ($allCategories as $cat): ?>
                                        <option value="<?= htmlspecialchars($cat) ?>"><?= htmlspecialchars($cat) ?></option>
                                    <?php endforeach; ?>
                                    <option value="NEW_CATEGORY_OPTION" class="font-bold text-cyan-400">+ Add New Category...</option>
                                </select>
                                <input type="text" name="new_category" id="new-category-input" placeholder="Enter new category name..." class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none hidden" />
                                <script>
                                function toggleNewCategoryInput(select) {
                                    const input = document.getElementById('new-category-input');
                                    if (select.value === 'NEW_CATEGORY_OPTION') {
                                        input.classList.remove('hidden');
                                        input.required = true;
                                        select.name = 'old_category';
                                        input.name = 'category';
                                    } else {
                                        input.classList.add('hidden');
                                        input.required = false;
                                        select.name = 'category';
                                        input.name = 'new_category';
                                    }
                                }
                                </script>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Event Description *</label>
                            <textarea name="description" required rows="3" placeholder="Comprehensive description of the competition..." oninput="this.value = this.value.replace(/[^a-zA-Z0-9\s]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none"></textarea>
                        </div>

                        <div>
                            <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Rules & Eligibility (1 per line)</label>
                            <textarea name="rules" rows="3" placeholder="Rule 1 Individual or team participation&#10;Rule 2 Duration 2 hours" oninput="this.value = this.value.replace(/[^a-zA-Z0-9\s]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none"></textarea>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Venue Location *</label>
                                <input type="text" name="venue" required oninput="this.value = this.value.replace(/[^a-zA-Z\s]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>

                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Event Date & Time *</label>
                                <div class="grid grid-cols-2 gap-2">
                                    <input type="text" name="eventDate" required placeholder="Date" class="bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-xs text-slate-100 focus:border-cyan-400 outline-none" />
                                    <input type="text" name="reportingTime" required placeholder="Time" class="bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-xs text-slate-100 focus:border-cyan-400 outline-none" />
                                </div>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Registration Fee (₹)</label>
                                <input type="number" name="registrationFee" required min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>

                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Prize Pool (₹)</label>
                                <input type="number" name="prizePool" required min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Lead Student Coordinator</label>
                                <input type="text" name="coordinatorName" placeholder="e.g. Diya Chuphal" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>

                            <div>
                                <label class="block text-xs font-mono-cyber uppercase text-cyan-400 mb-1">Coordinator Mobile Phone</label>
                                <input type="text" name="coordinatorPhone" placeholder="+91 9876543210" class="w-full bg-slate-900 border border-cyan-500/30 rounded-xl p-3 text-sm text-slate-100 focus:border-cyan-400 outline-none" />
                            </div>
                        </div>

                        <div class="pt-4 flex items-center justify-end gap-3">
                            <button type="button" id="btn-cancel-modal" class="px-5 py-2.5 rounded-xl border border-white/10 text-slate-400 hover:text-white text-xs font-mono-cyber font-bold">CANCEL</button>
                            <button type="submit" class="px-6 py-2.5 rounded-xl bg-gradient-to-r from-cyan-500 to-purple-600 text-slate-950 font-mono-cyber font-bold text-sm shadow-glow-cyan hover:scale-105 transition-all">
                                SUBMIT FOR ADMIN APPROVAL
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        lucide.createIcons();

        // Data from PHP
        const registrations = <?= json_encode($registrations) ?>;

        // Tabs Logic
        const tabEventsBtn = document.getElementById('tab-events');
        const tabAnalyticsBtn = document.getElementById('tab-analytics');
        const tabFilesBtn = document.getElementById('tab-files');
        
        const contentEvents = document.getElementById('content-events');
        const contentAnalytics = document.getElementById('content-analytics');
        const contentFiles = document.getElementById('content-files');

        function clearAllTabs() {
            tabEventsBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 glass-panel text-slate-400 border border-white/5 hover:text-white tab-btn';
            tabAnalyticsBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 glass-panel text-slate-400 border border-white/5 hover:text-white tab-btn';
            tabFilesBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 glass-panel text-slate-400 border border-white/5 hover:text-white tab-btn';
            
            contentEvents.classList.add('hidden');
            contentAnalytics.classList.add('hidden');
            contentFiles.classList.add('hidden');
        }

        tabEventsBtn.addEventListener('click', () => {
            clearAllTabs();
            tabEventsBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 bg-cyan-500 text-slate-950 shadow-glow-cyan tab-btn';
            contentEvents.classList.remove('hidden');
        });

        tabAnalyticsBtn.addEventListener('click', () => {
            clearAllTabs();
            tabAnalyticsBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 bg-purple-500 text-white shadow-glow-purple tab-btn';
            contentAnalytics.classList.remove('hidden');
            renderAnalytics();
        });

        tabFilesBtn.addEventListener('click', () => {
            clearAllTabs();
            tabFilesBtn.className = 'px-6 py-3 rounded-xl font-mono-cyber text-sm font-bold transition-all flex items-center gap-2 bg-pink-500 text-white shadow-glow-pink tab-btn';
            contentFiles.classList.remove('hidden');
        });

        // Modal Logic
        const modal = document.getElementById('modal-propose');
        document.getElementById('btn-propose').addEventListener('click', () => modal.classList.replace('hidden', 'flex'));
        document.getElementById('btn-close-modal').addEventListener('click', () => modal.classList.replace('flex', 'hidden'));
        document.getElementById('btn-cancel-modal').addEventListener('click', () => modal.classList.replace('flex', 'hidden'));

        // Analytics Logic
        const tbody = document.getElementById('analytics-tbody');
        const searchInput = document.getElementById('filter-search');
        const eventSelect = document.getElementById('filter-event');
        const paymentSelect = document.getElementById('filter-payment');

        // KPI Card Elements
        const cardTotal = document.getElementById('card-kpi-total');
        const cardPaid = document.getElementById('card-kpi-paid');
        const cardAttended = document.getElementById('card-kpi-attended');
        const cardRevenue = document.getElementById('card-kpi-revenue');

        let activeKpiFilter = 'all'; // can be 'all', 'paid', 'attended'

        // Populate Event Select Options dynamically
        const uniqueEvents = [...new Set(registrations.map(r => r.eventTitle))].filter(Boolean);
        uniqueEvents.forEach(evt => {
            const opt = document.createElement('option');
            opt.value = evt;
            opt.textContent = evt;
            eventSelect.appendChild(opt);
        });

        function updateKpiCardStyles() {
            // Reset all card styles
            [cardTotal, cardPaid, cardAttended, cardRevenue].forEach(c => {
                c.className = 'glass-panel p-5 rounded-2xl border border-white/10 relative overflow-hidden cursor-pointer hover:border-white/30 hover:scale-[1.02] transition-all duration-300';
            });

            // Highlight active cards with specific cyberpunk glows
            if (activeKpiFilter === 'all') {
                cardTotal.className = 'glass-panel p-5 rounded-2xl border border-cyan-500/60 shadow-[0_0_15px_rgba(6,182,212,0.2)] relative overflow-hidden cursor-pointer hover:scale-[1.02] transition-all duration-300';
            } else if (activeKpiFilter === 'paid') {
                cardPaid.className = 'glass-panel p-5 rounded-2xl border border-emerald-500/60 shadow-[0_0_15px_rgba(16,185,129,0.2)] relative overflow-hidden cursor-pointer hover:scale-[1.02] transition-all duration-300';
                cardRevenue.className = 'glass-panel p-5 rounded-2xl border border-amber-500/60 shadow-[0_0_15px_rgba(245,158,11,0.2)] relative overflow-hidden cursor-pointer hover:scale-[1.02] transition-all duration-300';
            } else if (activeKpiFilter === 'attended') {
                cardAttended.className = 'glass-panel p-5 rounded-2xl border border-purple-500/60 shadow-[0_0_15px_rgba(139,92,246,0.2)] relative overflow-hidden cursor-pointer hover:scale-[1.02] transition-all duration-300';
            }
        }

        function getFilteredRegistrations() {
            const query = searchInput.value.toLowerCase();
            const eventVal = eventSelect.value;
            const payVal = paymentSelect.value;

            return registrations.filter(r => {
                const searchMatch = (r.fullName || '').toLowerCase().includes(query) || (r.email || '').toLowerCase().includes(query) || (r.registrationId || '').toLowerCase().includes(query);
                const eventMatch = eventVal === 'ALL' || r.eventTitle === eventVal;
                
                let payMatch = payVal === 'ALL' || r.paymentStatus === payVal;
                if (activeKpiFilter === 'paid') {
                    payMatch = r.paymentStatus === 'SUCCESSFUL';
                }
                
                let attendMatch = true;
                if (activeKpiFilter === 'attended') {
                    attendMatch = r.attendanceId !== null && r.attendanceId !== undefined;
                }

                return searchMatch && eventMatch && payMatch && attendMatch;
            });
        }

        function renderAnalytics() {
            const query = searchInput.value.toLowerCase();
            const eventVal = eventSelect.value;

            // Base filtered list for KPI calculations (only event and search)
            const kpiFiltered = registrations.filter(r => {
                const searchMatch = (r.fullName || '').toLowerCase().includes(query) || (r.email || '').toLowerCase().includes(query) || (r.registrationId || '').toLowerCase().includes(query);
                const eventMatch = eventVal === 'ALL' || r.eventTitle === eventVal;
                return searchMatch && eventMatch;
            });

            // Calculate KPI values
            const total = kpiFiltered.length;
            const paid = kpiFiltered.filter(r => r.paymentStatus === 'SUCCESSFUL').length;
            const attended = kpiFiltered.filter(r => r.attendanceId).length;
            const revenue = kpiFiltered.filter(r => r.paymentStatus === 'SUCCESSFUL').reduce((sum, r) => sum + parseFloat(r.paymentAmount || 0), 0);

            document.getElementById('kpi-total').textContent = total;
            document.getElementById('kpi-paid').textContent = paid;
            document.getElementById('kpi-attended').textContent = attended;
            document.getElementById('kpi-revenue').textContent = '₹' + revenue.toLocaleString();

            updateKpiCardStyles();

            // Filtered list for the actual table
            const filtered = getFilteredRegistrations();

            // Table rendering
            tbody.innerHTML = '';
            if (filtered.length === 0) {
                tbody.innerHTML = '<tr><td colSpan="5" class="p-8 text-center text-slate-400">No registrations found for your criteria.</td></tr>';
                return;
            }

            filtered.forEach(reg => {
                const payStyle = reg.paymentStatus === 'SUCCESSFUL' ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border-amber-500/20';
                const payStatus = reg.paymentStatus || 'PENDING';
                const attendHTML = reg.attendanceId 
                    ? '<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> Checked In</span>'
                    : '<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>';

                const row = document.createElement('tr');
                row.className = 'hover:bg-cyan-500/5 transition-colors';
                row.innerHTML = `
                    <td class="p-4">
                        <div class="font-bold text-slate-100 text-sm">${reg.fullName}</div>
                        <div class="text-slate-400">${reg.email}</div>
                        <div class="text-[10px] text-cyan-500 font-mono-cyber mt-1">${reg.registrationId}</div>
                    </td>
                    <td class="p-4">
                        <div class="font-semibold text-slate-200">${reg.college}</div>
                        <div class="text-slate-400">${reg.city}</div>
                    </td>
                    <td class="p-4 font-semibold text-purple-400">${reg.eventTitle || 'Unknown Event'}</td>
                    <td class="p-4">
                        <span class="px-2.5 py-1 rounded-md text-[10px] font-bold border ${payStyle}">${payStatus}</span>
                        <div class="text-[10px] text-slate-400 mt-1">₹${reg.paymentAmount || 0}</div>
                    </td>
                    <td class="p-4">${attendHTML}</td>
                `;
                tbody.appendChild(row);
            });
            lucide.createIcons();
        }

        // Attach KPI Card Click Listeners
        cardTotal.addEventListener('click', () => {
            activeKpiFilter = 'all';
            paymentSelect.value = 'ALL';
            renderAnalytics();
        });

        cardPaid.addEventListener('click', () => {
            activeKpiFilter = 'paid';
            paymentSelect.value = 'SUCCESSFUL';
            renderAnalytics();
        });

        cardRevenue.addEventListener('click', () => {
            activeKpiFilter = 'paid';
            paymentSelect.value = 'SUCCESSFUL';
            renderAnalytics();
        });

        cardAttended.addEventListener('click', () => {
            activeKpiFilter = 'attended';
            paymentSelect.value = 'ALL';
            renderAnalytics();
        });

        searchInput.addEventListener('input', renderAnalytics);
        eventSelect.addEventListener('change', renderAnalytics);
        
        paymentSelect.addEventListener('change', () => {
            if (paymentSelect.value === 'SUCCESSFUL') {
                activeKpiFilter = 'paid';
            } else {
                activeKpiFilter = 'all';
            }
            renderAnalytics();
        });

        // Exports
        function getExportData() {
            const data = getFilteredRegistrations();
            return data.map(r => ({
                'Registration ID': r.registrationId,
                'Full Name': r.fullName,
                'Email': r.email,
                'Mobile': r.mobileNumber,
                'College': r.college,
                'City': r.city,
                'Event': r.eventTitle || 'N/A',
                'Payment Status': r.paymentStatus || 'N/A',
                'Amount': r.paymentAmount || 0,
                'Transaction ID': r.razorpayPaymentId || 'N/A',
                'Attendance': r.attendanceId ? 'Present' : 'Absent',
                'Registered At': r.createdAt
            }));
        }

        document.getElementById('btn-csv').addEventListener('click', () => {
            const data = getExportData();
            if(!data.length) return alert('No data');
            const headers = Object.keys(data[0]);
            const csv = [headers.join(','), ...data.map(row => headers.map(h => `"${String(row[h]).replace(/"/g, '""')}"`).join(','))].join('\n');
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'registrations.csv';
            a.click();
        });

        document.getElementById('btn-excel').addEventListener('click', () => {
            const data = getExportData();
            if(!data.length) return alert('No data');
            const ws = XLSX.utils.json_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Registrations");
            XLSX.writeFile(wb, "registrations.xlsx");
        });

        document.getElementById('btn-pdf').addEventListener('click', () => {
            const data = getExportData();
            if(!data.length) return alert('No data');
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF('landscape');
            doc.text('Supernova 2.0 Registrations', 14, 15);
            const head = [['Reg ID', 'Name', 'College', 'Event', 'Payment', 'Attendance']];
            const body = data.map(r => [r['Registration ID'], r['Full Name'], r['College'], r['Event'], r['Payment Status'], r['Attendance']]);
            doc.autoTable({ head, body, startY: 20, styles: { fontSize: 8 }, headStyles: { fillColor: [6, 182, 212] } });
            doc.save('registrations.pdf');
        });

        // ─── Import XLS Modal ────────────────────────────────────────────
        const importModal     = document.getElementById('modal-import');
        const importFileInput = document.getElementById('import-file-input');
        const importDropzone  = document.getElementById('import-dropzone');
        const importFilename  = document.getElementById('import-filename');
        const importProgress  = document.getElementById('import-progress');
        const importResults   = document.getElementById('import-results');
        const doImportBtn     = document.getElementById('btn-do-import');

        let selectedImportFile = null;

        function resetImportModal() {
            selectedImportFile = null;
            importFilename.classList.add('hidden');
            importProgress.classList.add('hidden');
            importResults.classList.add('hidden');
            importResults.innerHTML = '';
            doImportBtn.disabled = true;
            importFileInput.value = '';
            const banner = document.getElementById('import-info-banner');
            if (banner) banner.classList.remove('hidden');
            if (importDropzone) importDropzone.classList.remove('hidden');
        }

        function setImportFile(file) {
            if (!file) return;
            const allowed = ['xls', 'xlsx', 'csv'];
            const ext = file.name.split('.').pop().toLowerCase();
            if (!allowed.includes(ext)) {
                alert('Invalid file type. Only .xls, .xlsx, or .csv files are supported.');
                return;
            }
            selectedImportFile = file;
            importFilename.textContent = '📎 ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)';
            importFilename.classList.remove('hidden');
            doImportBtn.disabled = false;
            importResults.classList.add('hidden');
            importResults.innerHTML = '';
        }

        // Open modal
        document.getElementById('btn-import-xls').addEventListener('click', () => {
            importModal.classList.replace('hidden', 'flex');
            resetImportModal();
            lucide.createIcons();
        });

        // Close modal
        ['btn-close-import', 'btn-cancel-import'].forEach(id => {
            document.getElementById(id).addEventListener('click', () => {
                importModal.classList.replace('flex', 'hidden');
                resetImportModal();
            });
        });

        // Browse via click
        importDropzone.addEventListener('click', () => importFileInput.click());
        importFileInput.addEventListener('change', e => setImportFile(e.target.files[0]));

        // Drag and drop
        importDropzone.addEventListener('dragover', e => { e.preventDefault(); importDropzone.classList.add('border-purple-400', 'bg-purple-500/10'); });
        importDropzone.addEventListener('dragleave', () => { importDropzone.classList.remove('border-purple-400', 'bg-purple-500/10'); });
        importDropzone.addEventListener('drop', e => {
            e.preventDefault();
            importDropzone.classList.remove('border-purple-400', 'bg-purple-500/10');
            setImportFile(e.dataTransfer.files[0]);
        });

        // Do import
        doImportBtn.addEventListener('click', async () => {
            if (!selectedImportFile) return;

            importProgress.classList.remove('hidden');
            importResults.classList.add('hidden');
            importResults.innerHTML = '';
            doImportBtn.disabled = true;

            const banner = document.getElementById('import-info-banner');
            if (banner) banner.classList.add('hidden');
            if (importDropzone) importDropzone.classList.add('hidden');

            const formData = new FormData();
            formData.append('file', selectedImportFile);

            try {
                const res = await fetch('<?= APP_URL ?>/organizer/import_attendance.php', {
                    method: 'POST',
                    headers: { 'X-CSRF-Token': '<?= csrf_token() ?>' },
                    body: formData,
                });
                const responseData = await res.json();
                importProgress.classList.add('hidden');

                if (responseData.error) {
                    importResults.innerHTML = `<div class="p-4 rounded-xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm font-tech">⚠️ ${responseData.error}</div>`;
                } else {
                    const s = responseData.stats;
                    const previewRows = (s.preview || []).map(p =>
                        `<tr class="border-t border-white/5 text-xs">
                            <td class="py-1.5 pr-3 text-slate-200">${p.name}</td>
                            <td class="py-1.5 pr-3 text-cyan-400 font-mono-cyber">${p.regId}</td>
                            <td class="py-1.5 pr-3 text-purple-400 truncate max-w-[120px]">${p.event}</td>
                            <td class="py-1.5 pr-3">
                                <span class="${p.status === 'imported' ? 'text-emerald-400' : 'text-slate-400'} font-bold">${p.status === 'imported' ? '✓ New' : '~ Exists'}</span>
                            </td>
                        </tr>`
                    ).join('');

                    importResults.innerHTML = `
                        <div class="p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-sm font-tech mb-3">
                            ✅ ${responseData.message}
                        </div>
                        <div style="display: flex; gap: 8px; margin-bottom: 16px;">
                            <div style="flex: 1;" class="p-3 rounded-xl bg-slate-800 border border-white/10 text-center">
                                <div class="text-2xl font-bold text-cyan-400">${s.total_rows}</div>
                                <div class="text-[10px] text-slate-400 uppercase mt-1">Total Rows</div>
                            </div>
                            <div style="flex: 1;" class="p-3 rounded-xl bg-slate-800 border border-white/10 text-center">
                                <div class="text-2xl font-bold text-emerald-400">${s.imported}</div>
                                <div class="text-[10px] text-slate-400 uppercase mt-1">Imported</div>
                            </div>
                            <div style="flex: 1;" class="p-3 rounded-xl bg-slate-800 border border-white/10 text-center">
                                <div class="text-2xl font-bold text-slate-400">${s.already_exists}</div>
                                <div class="text-[10px] text-slate-400 uppercase mt-1">Existed</div>
                            </div>
                        </div>
                        ${previewRows ? `<div style="max-height: 220px; overflow-y: auto;" class="overflow-x-auto rounded-xl border border-white/10 mb-3"><table class="w-full text-left font-tech">
                            <thead class="bg-slate-900 text-[10px] text-cyan-400 uppercase font-mono-cyber sticky top-0 z-10"><tr>
                                <th class="p-2 bg-slate-900">Name</th><th class="p-2 bg-slate-900">Reg ID</th><th class="p-2 bg-slate-900">Event</th><th class="p-2 bg-slate-900">Status</th>
                            </tr></thead>
                            <tbody class="text-slate-300">${previewRows}</tbody>
                        </table></div>` : ''}
                        ${s.errors && s.errors.length ? `<div class="p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-tech max-h-32 overflow-y-auto">${s.errors.map(e => `<div>${e}</div>`).join('')}</div>` : ''}
                    `;
                }

                importResults.classList.remove('hidden');
                doImportBtn.disabled = false;

                // Reload after short delay so new data shows up in analytics
                if (responseData.success && responseData.stats && responseData.stats.imported > 0) {
                    setTimeout(() => window.location.reload(), 3500);
                }

            } catch (err) {
                importProgress.classList.add('hidden');
                importResults.innerHTML = `<div class="p-4 rounded-xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm font-tech">❌ Network error: ${err.message}</div>`;
                importResults.classList.remove('hidden');
                doImportBtn.disabled = false;
            }
        });
    </script>
</body>
</html>
