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

$pdo = getDatabaseConnection();
$regId = strtoupper(trim($_GET['regId'] ?? '')); // prefill only — lookup requires POST + email
$participant = null;
$error = null;

// Lookup requires Registration ID + the registered email address, so IDs
// alone can't be enumerated to harvest names/emails. No redirect: keeps
// personal data out of URLs and server logs.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $regId = strtoupper(trim($_POST['regId'] ?? ''));
    $email = trim($_POST['email'] ?? '');

    if (!$regId || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter your Registration ID and the email address you registered with.";
    } else {
        $stmt = $pdo->prepare("
            SELECT r.*, e.title as eventTitle, a.scannedAt, e.eventDate
            FROM registrations r
            LEFT JOIN events e ON r.eventId = e.id
            LEFT JOIN attendance a ON r.id = a.registrationId
            WHERE r.registrationId = ? AND LOWER(r.email) = LOWER(?)
        ");
        $stmt->execute([$regId, $email]);
        $participant = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$participant) {
            $error = "No registration found matching this ID and email combination.";
        } elseif (!$participant['scannedAt']) {
            $error = "You have not checked in at the venue. Certificates are only available for confirmed attendees.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Certificate - <?= 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/jspdf/2.5.1/jspdf.umd.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 flex flex-col">
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <main class="flex-grow flex items-center justify-center py-20 px-4 relative">
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-gradient-to-tr from-amber-500/20 to-purple-600/20 rounded-full blur-[140px] pointer-events-none"></div>

        <div class="max-w-xl w-full glass-panel p-8 md:p-12 rounded-3xl border border-amber-500/30 shadow-2xl relative z-10 text-center">
            
            <div class="w-16 h-16 rounded-2xl bg-amber-500/10 border border-amber-500/30 text-amber-400 flex items-center justify-center mx-auto mb-6">
                <i data-lucide="award" class="w-8 h-8"></i>
            </div>

            <h1 class="text-3xl font-heading-cyber font-extrabold text-slate-100 mb-2">Certificate Portal</h1>
            <p class="text-slate-400 text-sm mb-8">
                Enter your Registration ID to download your verified Supernova 2.0 Participation Certificate.
            </p>

            <?php if ($error): ?>
                <div class="mb-6 p-4 rounded-xl bg-red-500/10 border border-red-500/30 text-red-400 text-sm flex items-center justify-center gap-2">
                    <i data-lucide="alert-circle" class="w-5 h-5 shrink-0"></i>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>

            <?php if ($participant && $participant['scannedAt']): ?>
                <div class="p-6 rounded-2xl bg-slate-900 border border-emerald-500/30 mb-8 text-left">
                    <div class="flex items-center gap-3 mb-4">
                        <i data-lucide="check-circle-2" class="w-6 h-6 text-emerald-400"></i>
                        <h3 class="text-emerald-400 font-bold font-mono-cyber">CERTIFICATE READY</h3>
                    </div>
                    
                    <div class="space-y-2 text-sm font-mono-cyber text-slate-300">
                        <div class="flex justify-between border-b border-white/5 pb-2">
                            <span class="text-slate-500">Participant:</span>
                            <span class="font-bold text-white"><?= htmlspecialchars($participant['fullName']) ?></span>
                        </div>
                        <div class="flex justify-between border-b border-white/5 pb-2">
                            <span class="text-slate-500">Event:</span>
                            <span class="text-cyan-400"><?= htmlspecialchars($participant['eventTitle']) ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-slate-500">Reg ID:</span>
                            <span><?= htmlspecialchars($participant['registrationId']) ?></span>
                        </div>
                    </div>

                    <button onclick="downloadCertificate()" class="w-full mt-6 py-4 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 text-slate-950 font-extrabold text-sm transition-all shadow-glow flex items-center justify-center gap-2">
                        Download PDF Certificate <i data-lucide="download" class="w-4 h-4"></i>
                    </button>
                </div>

                <a href="index.php" class="text-slate-400 hover:text-white text-xs font-mono-cyber">Search Another ID</a>

                <script>
                    function downloadCertificate() {
                        const { jsPDF } = window.jspdf;
                        const doc = new jsPDF('landscape');
                        
                        // Add some styling for the certificate
                        doc.setFillColor(15, 23, 42); // slate-950
                        doc.rect(0, 0, 297, 210, 'F');
                        
                        // Border
                        doc.setDrawColor(6, 182, 212); // cyan-500
                        doc.setLineWidth(2);
                        doc.rect(10, 10, 277, 190, 'D');

                        // Title
                        doc.setTextColor(255, 255, 255);
                        doc.setFontSize(40);
                        doc.text('CERTIFICATE OF PARTICIPATION', 148, 50, { align: 'center' });

                        // Subtitle
                        doc.setFontSize(16);
                        doc.setTextColor(148, 163, 184); // slate-400
                        doc.text('THIS IS PROUDLY PRESENTED TO', 148, 80, { align: 'center' });

                        // Name
                        doc.setFontSize(36);
                        doc.setTextColor(251, 191, 36); // amber-400
                        doc.text('<?= addslashes(strtoupper($participant['fullName'])) ?>', 148, 100, { align: 'center' });

                        // Details
                        doc.setFontSize(14);
                        doc.setTextColor(148, 163, 184);
                        doc.text('For successfully participating in the event', 148, 120, { align: 'center' });
                        
                        doc.setFontSize(24);
                        doc.setTextColor(6, 182, 212);
                        doc.text('<?= addslashes(strtoupper($participant['eventTitle'])) ?>', 148, 135, { align: 'center' });

                        doc.setFontSize(14);
                        doc.setTextColor(148, 163, 184);
                        doc.text('held on <?= addslashes($participant['eventDate']) ?> as part of Supernova 2.0.', 148, 150, { align: 'center' });

                        // ID
                        doc.setFontSize(10);
                        doc.setTextColor(100, 116, 139);
                        doc.text('Certificate ID: <?= addslashes($participant['registrationId']) ?>', 148, 180, { align: 'center' });

                        doc.save('Supernova_Certificate_<?= addslashes($participant['registrationId']) ?>.pdf');
                    }
                </script>

            <?php else: ?>
                <form method="POST" class="space-y-4">
                    <div class="relative">
                        <i data-lucide="search" class="w-5 h-5 absolute left-4 top-1/2 -translate-y-1/2 text-slate-500"></i>
                        <input type="text" name="regId" required value="<?= htmlspecialchars($regId) ?>" placeholder="Enter Registration ID (e.g. SN-XYZ-1234)" class="w-full pl-12 pr-4 py-4 rounded-xl bg-slate-900 border border-white/10 text-slate-100 placeholder-slate-500 focus:outline-none focus:border-amber-400 text-sm font-mono-cyber uppercase" />
                    </div>

                    <div class="relative">
                        <i data-lucide="mail" class="w-5 h-5 absolute left-4 top-1/2 -translate-y-1/2 text-slate-500"></i>
                        <input type="email" name="email" required placeholder="Registered email address" class="w-full pl-12 pr-4 py-4 rounded-xl bg-slate-900 border border-white/10 text-slate-100 placeholder-slate-500 focus:outline-none focus:border-amber-400 text-sm font-mono-cyber" />
                    </div>

                    <button type="submit" class="w-full py-4 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 text-slate-950 font-extrabold text-sm transition-all shadow-glow flex items-center justify-center gap-2">
                        Verify & Download <i data-lucide="arrow-right" class="w-4 h-4"></i>
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </main>

    <?php include __DIR__ . '/../includes/footer.php'; ?>
    <script>lucide.createIcons();</script>
</body>
</html>
