<?php
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';
require_once __DIR__ . '/../includes/database.php';

$pdo = getDatabaseConnection();
$stmt = $pdo->query("SELECT * FROM events WHERE status IN ('PUBLISHED', 'COMPLETED') ORDER BY eventDate, reportingTime");
$events = $stmt->fetchAll();

usort($events, function($a, $b) {
    $priority = [
        'SparkX - Startup Pitching' => 1,
        'Stellar - Hackthon' => 2,
        'Protonova - Project Competition' => 3
    ];
    $pa = $priority[$a['title']] ?? 99;
    $pb = $priority[$b['title']] ?? 99;
    
    if ($pa !== $pb) return $pa <=> $pb;
    
    return strtotime($a['eventDate'] . ' ' . $a['reportingTime']) <=> strtotime($b['eventDate'] . ' ' . $b['reportingTime']);
});

// Coordinators are fetched below in the loop or in a separate query, 
// let's fetch all coordinators mapping by eventId
$coordStmt = $pdo->query("SELECT * FROM coordinators");
$allCoords = $coordStmt->fetchAll();
$coordinatorsByEvent = [];
foreach ($allCoords as $c) {
    $coordinatorsByEvent[$c['eventId']][] = $c['name'];
}

function getCategoryTab($category) {
    $c = strtolower($category);
    if (
        strpos($c, 'coding') !== false || 
        strpos($c, 'program') !== false || 
        strpos($c, 'debug') !== false
    ) {
        return 'Coding';
    }
    if (strpos($c, 'workshop') !== false || strpos($c, 'training') !== false) return 'Workshop';
    if (strpos($c, 'startup') !== false || strpos($c, 'pitch') !== false || strpos($c, 'business') !== false) return 'Ideation';
    if (strpos($c, 'project') !== false || strpos($c, 'showcase') !== false || strpos($c, 'robot') !== false) return 'Showcase';
    if (strpos($c, 'gaming') !== false || strpos($c, 'sport') !== false) return 'Gaming';
    return 'Other';
}

$categories = ['All'];
foreach ($events as $evt) {
    $tab = getCategoryTab($evt['category']);
    if (!in_array($tab, $categories)) {
        $categories[] = $tab;
    }
}

function formatFee($fee) {
    return $fee == 0 ? 'Free' : '₹' . number_format($fee);
}

function formatPrize($prize) {
    if ($prize == 0) return 'Certificate';
    if ($prize >= 1000) return '₹' . floor($prize / 1000) . 'K';
    return '₹' . number_format($prize);
}
?>

<div class="min-h-screen bg-transparent text-slate-100 pb-12 px-4 sm:px-6 lg:px-8 relative pt-36 md:pt-48">
    <!-- Glow ambient background -->
    <div class="absolute top-10 left-1/2 -translate-x-1/2 w-[700px] h-[350px] bg-gradient-to-r from-purple-900/30 via-cyan-600/20 to-blue-900/30 rounded-full blur-[140px] pointer-events-none"></div>

    <div class="max-w-7xl mx-auto relative z-10">
        <a href="<?= APP_URL ?>/" class="inline-flex items-center gap-2 px-4 py-2 bg-slate-900/30 border border-cyan-500/30 hover:border-cyan-400/60 text-xs font-mono-cyber text-cyan-400 mb-8 transition-all duration-300 backdrop-blur-md group w-fit shadow-[0_0_20px_rgba(6,182,212,0.15)]">
            <i data-lucide="arrow-left" class="w-4 h-4 transition-transform group-hover:-translate-x-1"></i>
            <span>BACK TO HOME</span>
        </a>

        <div class="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-6">
            <div>
                <h1 class="text-4xl md:text-5xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-purple-300 via-cyan-300 to-white font-heading-cyber">
                    Official Events Catalog
                </h1>
                <p class="text-slate-400 mt-2 text-lg font-tech">
                    Explore technical challenges, hackathons, workshops, and flagship competitions.
                </p>
            </div>

            <div class="w-full md:w-72 relative">
                <i data-lucide="search" class="w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                <input
                    type="text"
                    id="search-input"
                    placeholder="Search event name..."
                    class="w-full pl-10 pr-4 py-2.5 rounded-xl bg-slate-900/90 border border-white/10 text-slate-100 placeholder-slate-500 focus:outline-none focus:border-cyan-400 focus:ring-1 focus:ring-cyan-400 text-sm font-tech"
                />
            </div>
        </div>

        <!-- Category Pills -->
        <div class="mb-8">
            <p class="text-xs font-mono-cyber text-slate-500 uppercase tracking-widest mb-3">Filter by category</p>
            <div class="flex flex-wrap gap-2 border-b border-white/10 pb-6" id="category-filters">
                <?php foreach ($categories as $cat): ?>
                    <button
                        data-category="<?= htmlspecialchars($cat) ?>"
                        class="cat-filter-btn px-4 py-2 rounded-xl text-sm font-medium transition-all font-tech <?= $cat === 'All' ? 'bg-cyan-500 text-slate-950 font-bold shadow-glow-cyan' : 'border border-white/20 bg-slate-800/30 text-slate-200 hover:border-cyan-500/60 hover:text-cyan-300 hover:bg-slate-700/40' ?>"
                    >
                        <?= htmlspecialchars($cat) ?>
                    </button>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Events Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="events-grid">
            <?php if (count($events) === 0): ?>
                <div class="col-span-3 text-center py-20 glass-panel rounded-2xl border border-white/10">
                    <p class="text-slate-400 text-lg font-tech">No events found.</p>
                </div>
            <?php else: ?>
                <?php foreach ($events as $evt): ?>
                    <div class="event-card glass-card bg-slate-950/20 p-6 rounded-2xl border border-white/10 flex flex-col justify-between group hover:border-cyan-400/50" data-title="<?= strtolower(htmlspecialchars($evt['title'])) ?>" data-desc="<?= strtolower(htmlspecialchars($evt['description'])) ?>" data-category="<?= htmlspecialchars(getCategoryTab($evt['category'])) ?>">
                        <div>
                            <div class="flex items-center justify-between gap-2 mb-3">
                                <div class="flex items-center gap-3">
                                    <?php 
                                        $expectedLogo = '/assets/img/events/' . $evt['title'] . '.png';
                                        $hasLogo = !empty($evt['bannerUrl']) || file_exists(__DIR__ . '/..' . $expectedLogo);
                                        $logoSrc = !empty($evt['bannerUrl']) ? APP_URL . $evt['bannerUrl'] : APP_URL . $expectedLogo;
                                    ?>
                                    <?php if ($hasLogo): ?>
                                        <div class="w-12 h-12 rounded-xl bg-black border border-cyan-500/30 p-1 shrink-0 group-hover:scale-110 transition-transform overflow-hidden shadow-glow-cyan flex items-center justify-center">
                                            <img src="<?= htmlspecialchars($logoSrc) ?>" alt="<?= htmlspecialchars($evt['title']) ?>" class="w-full h-full object-contain invert">
                                        </div>
                                    <?php endif; ?>
                                    <span class="px-2.5 py-1 rounded-md bg-purple-500/10 border border-purple-500/30 text-purple-300 text-xs font-semibold font-mono-cyber">
                                        <?= htmlspecialchars($evt['category']) ?>
                                    </span>
                                </div>
                            </div>

                            <h3 class="text-2xl font-bold text-slate-100 group-hover:text-cyan-400 transition-colors mb-2 font-heading-cyber">
                                <?= htmlspecialchars($evt['title']) ?>
                            </h3>
                            <p class="text-slate-400 text-sm line-clamp-3 mb-6 font-tech leading-relaxed">
                                <?= htmlspecialchars($evt['description']) ?>
                            </p>
                        </div>

                        <div>
                            <div class="space-y-2 text-xs text-slate-300 border-t border-white/5 pt-4 mb-6 font-mono-cyber">
                                <div class="flex items-start gap-2">
                                    <i data-lucide="calendar" class="w-4 h-4 text-cyan-400 shrink-0 mt-0.5"></i>
                                    <span class="leading-relaxed"><?= htmlspecialchars($evt['eventDate']) ?> • <?= htmlspecialchars($evt['reportingTime']) ?></span>
                                </div>
                                <div class="flex items-start gap-2">
                                    <i data-lucide="map-pin" class="w-4 h-4 text-cyan-400 shrink-0 mt-0.5"></i>
                                    <span class="leading-relaxed"><?= htmlspecialchars($evt['venue']) ?></span>
                                </div>
                                <?php if (isset($coordinatorsByEvent[$evt['id']])): ?>
                                    <div class="flex items-start gap-2">
                                        <i data-lucide="users" class="w-4 h-4 text-cyan-400 shrink-0 mt-0.5"></i>
                                        <span class="leading-relaxed">Coord: <?= htmlspecialchars(implode(', ', $coordinatorsByEvent[$evt['id']])) ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="flex items-end justify-between border-t border-white/10 pt-4">
                                <div>
                                    <span class="text-[10px] text-slate-400 uppercase font-semibold block font-mono-cyber mb-1">Entry Fee</span>
                                    <span class="text-lg font-bold text-cyan-400 font-mono-cyber leading-none block">
                                        <?= formatFee($evt['registrationFee']) ?>
                                    </span>
                                </div>
                                <a href="<?= APP_URL ?>/events/details.php?slug=<?= htmlspecialchars($evt['slug']) ?>" class="px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-cyan-500 hover:text-slate-950 text-slate-200 font-semibold text-xs transition-all flex items-center gap-1.5 font-mono-cyber">
                                    Event Details <i data-lucide="arrow-right" class="w-3.5 h-3.5"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="<?= APP_URL ?>/assets/js/events.js"></script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
