<?php
// Ensure this path jumps up from public/ to the root for config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/ad-display.php';

$settings_file = __DIR__ . '/../config/site-settings.json';
$site_name = 'tipspac';
if (file_exists($settings_file)) {
    $loaded = json_decode(file_get_contents($settings_file), true);
    if (!empty($loaded['site_name'])) $site_name = $loaded['site_name'];
}

// ==========================================
// DYNAMIC FRONTEND FILTERING & PAGINATION
// ==========================================
$searchTerm    = trim($_GET['q'] ?? '');
$filterCountry = trim($_GET['country'] ?? '');
$filterLeague  = trim($_GET['league'] ?? '');

// 🔁 CHANGED: limit to 10 matches per page
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$countSql = "
    SELECT COUNT(*) 
    FROM fixtures f
    JOIN teams ht ON f.home_team_id = ht.id
    JOIN teams at ON f.away_team_id = at.id
    WHERE f.match_date >= NOW()
";

$sql = "
    SELECT 
        f.*, 
        f.id AS fixture_id,
        ht.name AS home_team_name, ht.logo_url AS home_team_logo,
        at.name AS away_team_name, at.logo_url AS away_team_logo
    FROM fixtures f
    JOIN teams ht ON f.home_team_id = ht.id
    JOIN teams at ON f.away_team_id = at.id
    WHERE f.match_date >= NOW()
";

$params = [];

if (!empty($searchTerm)) {
    $condition = " AND (ht.name LIKE :search OR at.name LIKE :search OR f.league_name LIKE :search)";
    $sql .= $condition;
    $countSql .= $condition;
    $params['search'] = '%' . $searchTerm . '%';
}

if (!empty($filterCountry)) {
    $condition = " AND f.league_name LIKE :country";
    $sql .= $condition;
    $countSql .= $condition;
    $params['country'] = '%' . $filterCountry . '%';
}

if (!empty($filterLeague)) {
    $condition = " AND f.league_name LIKE :league";
    $sql .= $condition;
    $countSql .= $condition;
    $params['league'] = '%' . $filterLeague . '%';
}

$sql .= " ORDER BY f.match_date ASC LIMIT :limit OFFSET :offset";

$db_error = '';

try {
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total_records = $countStmt->fetchColumn();
    $total_pages = ceil($total_records / $limit);
    if ($total_pages < 1) $total_pages = 1;

    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $val) {
        $stmt->bindValue(':' . $key, $val);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
    $stmt->execute();
    $fixtures = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $fixtures = []; 
    $total_pages = 1;
    $db_error = $e->getMessage();
}
?>

<?php require_once __DIR__ . '/includes/header.php'; ?>

<div class="fixed inset-0 z-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
<div class="fixed inset-0 z-0 bg-gradient-to-t from-[#020617] via-[#020617]/85 to-transparent pointer-events-none"></div>
<canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-40"></canvas>

<main class="relative z-10 flex-1 w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-8 pb-20">

    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-end justify-between mb-8 space-y-4 md:space-y-0">
        <div>
            <div class="inline-flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-emerald-400 mb-3">
                <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                <span>Live Feed Matrix</span>
            </div>
            <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">API Fixtures <span class="text-cyan-400">Terminal</span></h1>
            <p class="text-xs md:text-sm text-slate-400 mt-2 max-w-xl">Real-time global match coverage, leagues, tournaments, and live feeds.</p>
        </div>
        
        <div class="flex bg-slate-900/80 backdrop-blur border border-slate-800 rounded-xl p-1 shadow-lg">
            <button class="px-4 py-2 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Archive</button>
            <button class="px-4 py-2 text-xs font-bold text-white bg-slate-800 rounded-lg shadow uppercase tracking-wider border border-slate-700">Live Engine, <?php echo date('d M'); ?></button>
            <button class="px-4 py-2 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Upcoming</button>
        </div>
    </div>

    <!-- Ad Slot -->
    <div class="w-full mb-8 flex justify-center">
        <?php display_ad_slot($pdo, 'header'); ?>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        
        <!-- Sidebar -->
        <div class="col-span-1 space-y-6">
            <!-- Search Form -->
            <form action="predictions.php" method="GET" class="relative">
                <input type="text" name="q" value="<?php echo htmlspecialchars($searchTerm); ?>" placeholder="Search country, club or league..." class="w-full bg-slate-900/80 backdrop-blur border border-slate-800 rounded-xl py-3 pl-10 pr-4 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                <button type="submit" class="absolute left-4 top-3.5">
                    <svg class="w-4 h-4 text-slate-500 hover:text-cyan-400 transition" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                </button>
            </form>

            <!-- Filters -->
            <div class="bg-slate-900/60 backdrop-blur border border-slate-800 rounded-2xl p-5">
                <h3 class="text-xs font-black text-slate-300 uppercase tracking-widest mb-4 border-b border-slate-800 pb-2">Filter Fixtures</h3>
                <form action="predictions.php" method="GET" class="space-y-4">
                    <?php if(!empty($searchTerm)): ?>
                        <input type="hidden" name="q" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    <?php endif; ?>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Country</label>
                        <select name="country" class="w-full bg-slate-800/60 border border-slate-700 rounded-lg py-2 px-3 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                            <option value="">All Countries</option>
                            <option value="England" <?php if($filterCountry == 'England') echo 'selected'; ?>>England</option>
                            <option value="Spain" <?php if($filterCountry == 'Spain') echo 'selected'; ?>>Spain</option>
                            <option value="Italy" <?php if($filterCountry == 'Italy') echo 'selected'; ?>>Italy</option>
                            <option value="Germany" <?php if($filterCountry == 'Germany') echo 'selected'; ?>>Germany</option>
                            <option value="France" <?php if($filterCountry == 'France') echo 'selected'; ?>>France</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">League / Tournament</label>
                        <select name="league" class="w-full bg-slate-800/60 border border-slate-700 rounded-lg py-2 px-3 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                            <option value="">All Leagues</option>
                            <option value="Premier League" <?php if($filterLeague == 'Premier League') echo 'selected'; ?>>Premier League</option>
                            <option value="La Liga" <?php if($filterLeague == 'La Liga') echo 'selected'; ?>>La Liga</option>
                            <option value="Serie A" <?php if($filterLeague == 'Serie A') echo 'selected'; ?>>Serie A</option>
                            <option value="Bundesliga" <?php if($filterLeague == 'Bundesliga') echo 'selected'; ?>>Bundesliga</option>
                            <option value="Ligue 1" <?php if($filterLeague == 'Ligue 1') echo 'selected'; ?>>Ligue 1</option>
                            <option value="Champions League" <?php if($filterLeague == 'Champions League') echo 'selected'; ?>>Champions League</option>
                        </select>
                    </div>

                    <div class="flex space-x-2 pt-2">
                        <button type="submit" class="flex-1 bg-cyan-600 hover:bg-cyan-500 text-white text-[10px] font-bold uppercase tracking-widest py-2 rounded-lg transition shadow-lg shadow-cyan-900/30">Apply Filters</button>
                        <a href="predictions.php" class="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white text-[10px] font-bold uppercase tracking-widest py-2 rounded-lg text-center transition">Reset</a>
                    </div>
                </form>
            </div>
            
            <!-- Ad Slot -->
            <div class="bg-slate-900/60 backdrop-blur border border-slate-800 rounded-2xl p-4 text-center">
                <span class="text-[9px] text-slate-500 uppercase tracking-widest">Sponsored</span>
                <div class="mt-2 h-48 bg-slate-800 rounded-xl flex items-center justify-center">
                    <span class="text-xs text-slate-600 font-bold">300x250 Ad Slot</span>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-span-1 lg:col-span-3 flex flex-col space-y-6">
            
            <!-- Stats -->
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 bg-slate-900/80 backdrop-blur border border-slate-800 rounded-2xl p-4">
                <div class="text-center border-r border-slate-800 md:border-r md:last:border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Live Data Source</span>
                    <span class="block text-xl font-black text-white mt-1 uppercase"><?php echo defined('DATA_SOURCE') ? DATA_SOURCE : 'API'; ?></span>
                </div>
                <div class="text-center border-r border-slate-800 md:border-r md:last:border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Available Matches</span>
                    <span class="block text-xl font-black text-emerald-400 mt-1"><?php echo isset($total_records) ? number_format($total_records) : 0; ?></span>
                </div>
                <div class="text-center border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Showing Page</span>
                    <span class="block text-xl font-black text-cyan-400 mt-1"><?php echo $page; ?> of <?php echo $total_pages; ?></span>
                </div>
            </div>

            <!-- Fixtures Table -->
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl overflow-hidden shadow-2xl divide-y divide-slate-800/40">
                
                <!-- Desktop Header -->
                <div class="hidden lg:grid grid-cols-12 gap-4 p-4.5 border-b border-slate-800 bg-slate-950/40 text-[8px] font-black tracking-[0.2em] uppercase text-slate-500">
                    <div class="col-span-3 pl-2">Kick-off (UTC)</div>
                    <div class="col-span-4">Fixture & Tournament Details</div>
                    <div class="col-span-2 text-center">Result</div>
                    <div class="col-span-3 text-right pr-4">Global Bookmaker Odds (1X2)</div>
                </div>

                <?php if (!empty($db_error)): ?>
                    <div class="p-12 text-center flex flex-col items-center space-y-3">
                        <span class="text-2xl">⚠️</span>
                        <div class="text-sm text-rose-500 font-bold tracking-widest uppercase">DATABASE SYNC ERROR</div>
                        <div class="text-[10px] text-slate-400 font-mono bg-slate-950 p-3 rounded-lg border border-slate-800 max-w-lg overflow-x-auto"><?php echo htmlspecialchars($db_error); ?></div>
                    </div>
                <?php elseif (empty($fixtures)): ?>
                    <div class="p-12 text-center text-sm text-slate-500 font-bold tracking-widest uppercase">
                        🤖 NO MATCHES FOUND MATCHING SEARCH FILTERS
                    </div>
                <?php else: ?>
                    <?php foreach ($fixtures as $fix): 
                        // Determine match status
                        $status = $fix['match_status'] ?? 'NS';
                        $is_finished = in_array($status, ['FT', 'AET', 'PEN']);
                        $home_goals = $fix['home_goals'];
                        $away_goals = $fix['away_goals'];
                        $winner = $fix['winner'] ?? null;

                        // Odds
                        $h_odds = isset($fix['home_odds']) ? (float)$fix['home_odds'] : 0;
                        $d_odds = isset($fix['draw_odds']) ? (float)$fix['draw_odds'] : 0;
                        $a_odds = isset($fix['away_odds']) ? (float)$fix['away_odds'] : 0;
                        $has_odds = ($h_odds > 0 || $d_odds > 0 || $a_odds > 0);
                    ?>
                        <div class="flex flex-col lg:grid lg:grid-cols-12 gap-3 p-4 md:p-5 hover:bg-slate-800/30 transition-colors items-start lg:items-center">
                            
                            <!-- Time & Status -->
                            <div class="col-span-3 w-full lg:w-auto flex flex-row lg:flex-col justify-between items-center lg:items-start pl-0 lg:pl-2 border-b lg:border-b-0 border-slate-800/40 pb-3 lg:pb-0 mb-2 lg:mb-0">
                                <span class="text-xs font-mono text-cyan-400 font-bold bg-cyan-500/10 px-2 py-0.5 rounded">
                                    <?php echo date("d M H:i", strtotime($fix['match_date'])); ?>
                                </span>
                                <span class="text-[9px] text-slate-400 font-bold uppercase lg:mt-2 truncate max-w-[120px] tracking-wider">
                                    <?php echo htmlspecialchars($fix['match_status'] ?? 'Pending'); ?>
                                </span>
                            </div>
                            
                            <!-- Fixture Details -->
                            <div class="col-span-4 w-full lg:w-auto flex flex-col justify-center space-y-2 border-b lg:border-b-0 border-slate-800/40 pb-3 lg:pb-0 mb-2 lg:mb-0">
                                <div class="text-[8px] font-black uppercase tracking-[0.15em] text-emerald-400 truncate">
                                    <?php echo htmlspecialchars($fix['league_name'] ?? 'Unknown'); ?>
                                </div>
                                <div class="flex flex-col space-y-1">
                                    <div class="flex items-center space-x-2">
                                        <?php if(!empty($fix['home_team_logo'])): ?>
                                            <img src="<?php echo htmlspecialchars($fix['home_team_logo']); ?>" class="w-4 h-4 object-contain" alt="logo">
                                        <?php endif; ?>
                                        <span class="font-bold text-xs text-white truncate"><?php echo htmlspecialchars($fix['home_team_name'] ?? 'TBD'); ?></span>
                                    </div>
                                    <div class="flex items-center space-x-2">
                                        <?php if(!empty($fix['away_team_logo'])): ?>
                                            <img src="<?php echo htmlspecialchars($fix['away_team_logo']); ?>" class="w-4 h-4 object-contain" alt="logo">
                                        <?php endif; ?>
                                        <span class="font-bold text-xs text-slate-400 truncate"><?php echo htmlspecialchars($fix['away_team_name'] ?? 'TBD'); ?></span>
                                    </div>
                                </div>
                            </div>

                            <!-- Result -->
                            <div class="col-span-2 w-full lg:w-auto text-center">
                                <?php if ($is_finished && $home_goals !== null && $away_goals !== null): ?>
                                    <div class="flex items-center justify-center space-x-2">
                                        <span class="text-lg font-black text-white"><?php echo $home_goals; ?></span>
                                        <span class="text-xs font-bold text-slate-500">–</span>
                                        <span class="text-lg font-black text-white"><?php echo $away_goals; ?></span>
                                    </div>
                                    <?php if ($winner): ?>
                                        <div class="text-[8px] font-bold uppercase tracking-widest mt-0.5">
                                            <?php if ($winner === '1'): ?>
                                                <span class="text-emerald-400">🏆 Home</span>
                                            <?php elseif ($winner === 'X'): ?>
                                                <span class="text-yellow-400">🤝 Draw</span>
                                            <?php elseif ($winner === '2'): ?>
                                                <span class="text-rose-400">🏆 Away</span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-xs text-slate-500 font-bold uppercase tracking-wider">–</span>
                                <?php endif; ?>
                            </div>

                            <!-- Odds -->
                            <div class="col-span-3 w-full lg:w-auto flex justify-between lg:justify-end items-center lg:pr-2">
                                <span class="lg:hidden text-[9px] font-bold text-slate-500 uppercase tracking-widest">Market Odds:</span>
                                
                                <?php if($has_odds): ?>
                                    <div class="flex space-x-2 w-full lg:w-auto justify-end">
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-cyan-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">1</span>
                                            <span class="font-mono text-xs font-black text-cyan-400"><?php echo number_format($h_odds, 2); ?></span>
                                        </div>
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-slate-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">X</span>
                                            <span class="font-mono text-xs font-black text-slate-300"><?php echo number_format($d_odds, 2); ?></span>
                                        </div>
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-amber-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">2</span>
                                            <span class="font-mono text-xs font-black text-amber-400"><?php echo number_format($a_odds, 2); ?></span>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <span class="bg-slate-800/60 text-slate-500 border border-slate-700/60 px-4 py-2 rounded-xl text-[9px] font-black tracking-widest uppercase flex items-center space-x-2">
                                        <svg class="animate-spin h-3 w-3 text-slate-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                                        <span>Odds Awaiting Sync</span>
                                    </span>
                                <?php endif; ?>
                            </div>

                        </div>

                    <?php endforeach; ?>
                <?php endif; ?>

            </div>

            <!-- Ad Slot -->
            <div class="w-full flex justify-center py-4">
                <?php display_ad_slot($pdo, 'in_content'); ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="flex justify-center pt-2">
                    <div class="flex items-center space-x-1 bg-slate-900/60 border border-slate-800 p-1 rounded-xl text-xs overflow-x-auto max-w-full">
                        
                        <?php if ($page > 1): ?>
                            <a href="predictions.php?page=<?php echo $page - 1 . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">Prev</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-slate-600 cursor-not-allowed rounded-lg">Prev</span>
                        <?php endif; ?>

                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        if($start > 1) {
                            echo '<a href="predictions.php?page=1'.(!empty($searchTerm) ? '&q='.urlencode($searchTerm) : '').'" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">1</a>';
                            if($start > 2) echo '<span class="px-2 text-slate-600">...</span>';
                        }

                        for ($i = $start; $i <= $end; $i++): 
                        ?>
                            <a href="predictions.php?page=<?php echo $i . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 rounded-lg font-bold transition <?php echo $i == $page ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30' : 'text-slate-400 hover:text-white'; ?>"><?php echo $i; ?></a>
                        <?php endfor; ?>

                        <?php 
                        if($end < $total_pages) {
                            if($end < $total_pages - 1) echo '<span class="px-2 text-slate-600">...</span>';
                            echo '<a href="predictions.php?page='.$total_pages.(!empty($searchTerm) ? '&q='.urlencode($searchTerm) : '').'" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">'.$total_pages.'</a>';
                        }
                        ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="predictions.php?page=<?php echo $page + 1 . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">Next</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-slate-600 cursor-not-allowed rounded-lg">Next</span>
                        <?php endif; ?>

                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

<script>
    // Neural Canvas Background (unchanged)
    const canvas = document.getElementById("neuralCanvas");
    if(canvas) {
        const ctx = canvas.getContext("2d");
        let width, height;
        let particles = [];
        let mouse = { x: null, y: null, radius: 150 };
        window.addEventListener('mousemove', function(e) {
            mouse.x = e.x;
            mouse.y = e.y;
        });

        function initCanvas() {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
            particles = [];
            let particleCount = (width * height) / 12000;
            for (let i = 0; i < particleCount; i++) {
                particles.push({
                    x: Math.random() * width,
                    y: Math.random() * height,
                    vx: (Math.random() - 0.5) * 1.5,
                    vy: (Math.random() - 0.5) * 1.5,
                    radius: Math.random() * 1.5 + 0.5
                });
            }
        }

        function animateCanvas() {
            ctx.clearRect(0, 0, width, height);
            for (let i = 0; i < particles.length; i++) {
                let p = particles[i];
                p.x += p.vx;
                p.y += p.vy;
                if (p.x < 0 || p.x > width) p.vx *= -1;
                if (p.y < 0 || p.y > height) p.vy *= -1;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                ctx.fillStyle = "rgba(16, 185, 129, 0.35)";
                ctx.fill();
                for (let j = i + 1; j < particles.length; j++) {
                    let p2 = particles[j];
                    let dist = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2));
                    if (dist < 100) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(p2.x, p2.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${1 - dist/100})`;
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                }
                if (mouse.x && mouse.y) {
                    let mouseDist = Math.sqrt(Math.pow(p.x - mouse.x, 2) + Math.pow(p.y - mouse.y, 2));
                    if (mouseDist < mouse.radius) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(mouse.x, mouse.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${0.8 - mouseDist/mouse.radius})`;
                        ctx.lineWidth = 1;
                        ctx.stroke();
                    }
                }
            }
            requestAnimationFrame(animateCanvas);
        }

        window.addEventListener("resize", initCanvas);
        initCanvas();
        animateCanvas();
    }
</script><?php
// Ensure this path jumps up from public/ to the root for config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/ad-display.php';

$settings_file = __DIR__ . '/../config/site-settings.json';
$site_name = 'tipspac';
if (file_exists($settings_file)) {
    $loaded = json_decode(file_get_contents($settings_file), true);
    if (!empty($loaded['site_name'])) $site_name = $loaded['site_name'];
}

// ==========================================
// DYNAMIC FRONTEND FILTERING & PAGINATION
// ==========================================
$searchTerm    = trim($_GET['q'] ?? '');
$filterCountry = trim($_GET['country'] ?? '');
$filterLeague  = trim($_GET['league'] ?? '');

// 🔁 CHANGED: limit to 10 matches per page
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$countSql = "
    SELECT COUNT(*) 
    FROM fixtures f
    JOIN teams ht ON f.home_team_id = ht.id
    JOIN teams at ON f.away_team_id = at.id
    WHERE f.match_date >= NOW()
";

$sql = "
    SELECT 
        f.*, 
        f.id AS fixture_id,
        ht.name AS home_team_name, ht.logo_url AS home_team_logo,
        at.name AS away_team_name, at.logo_url AS away_team_logo
    FROM fixtures f
    JOIN teams ht ON f.home_team_id = ht.id
    JOIN teams at ON f.away_team_id = at.id
    WHERE f.match_date >= NOW()
";

$params = [];

if (!empty($searchTerm)) {
    $condition = " AND (ht.name LIKE :search OR at.name LIKE :search OR f.league_name LIKE :search)";
    $sql .= $condition;
    $countSql .= $condition;
    $params['search'] = '%' . $searchTerm . '%';
}

if (!empty($filterCountry)) {
    $condition = " AND f.league_name LIKE :country";
    $sql .= $condition;
    $countSql .= $condition;
    $params['country'] = '%' . $filterCountry . '%';
}

if (!empty($filterLeague)) {
    $condition = " AND f.league_name LIKE :league";
    $sql .= $condition;
    $countSql .= $condition;
    $params['league'] = '%' . $filterLeague . '%';
}

$sql .= " ORDER BY f.match_date ASC LIMIT :limit OFFSET :offset";

$db_error = '';

try {
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total_records = $countStmt->fetchColumn();
    $total_pages = ceil($total_records / $limit);
    if ($total_pages < 1) $total_pages = 1;

    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $val) {
        $stmt->bindValue(':' . $key, $val);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
    $stmt->execute();
    $fixtures = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $fixtures = []; 
    $total_pages = 1;
    $db_error = $e->getMessage();
}
?>

<?php require_once __DIR__ . '/includes/header.php'; ?>

<div class="fixed inset-0 z-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
<div class="fixed inset-0 z-0 bg-gradient-to-t from-[#020617] via-[#020617]/85 to-transparent pointer-events-none"></div>
<canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-40"></canvas>

<main class="relative z-10 flex-1 w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-8 pb-20">

    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-end justify-between mb-8 space-y-4 md:space-y-0">
        <div>
            <div class="inline-flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-emerald-400 mb-3">
                <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                <span>Live Feed Matrix</span>
            </div>
            <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">API Fixtures <span class="text-cyan-400">Terminal</span></h1>
            <p class="text-xs md:text-sm text-slate-400 mt-2 max-w-xl">Real-time global match coverage, leagues, tournaments, and live feeds.</p>
        </div>
        
        <div class="flex bg-slate-900/80 backdrop-blur border border-slate-800 rounded-xl p-1 shadow-lg">
            <button class="px-4 py-2 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Archive</button>
            <button class="px-4 py-2 text-xs font-bold text-white bg-slate-800 rounded-lg shadow uppercase tracking-wider border border-slate-700">Live Engine, <?php echo date('d M'); ?></button>
            <button class="px-4 py-2 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Upcoming</button>
        </div>
    </div>

    <!-- Ad Slot -->
    <div class="w-full mb-8 flex justify-center">
        <?php display_ad_slot($pdo, 'header'); ?>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        
        <!-- Sidebar -->
        <div class="col-span-1 space-y-6">
            <!-- Search Form -->
            <form action="predictions.php" method="GET" class="relative">
                <input type="text" name="q" value="<?php echo htmlspecialchars($searchTerm); ?>" placeholder="Search country, club or league..." class="w-full bg-slate-900/80 backdrop-blur border border-slate-800 rounded-xl py-3 pl-10 pr-4 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                <button type="submit" class="absolute left-4 top-3.5">
                    <svg class="w-4 h-4 text-slate-500 hover:text-cyan-400 transition" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                </button>
            </form>

            <!-- Filters -->
            <div class="bg-slate-900/60 backdrop-blur border border-slate-800 rounded-2xl p-5">
                <h3 class="text-xs font-black text-slate-300 uppercase tracking-widest mb-4 border-b border-slate-800 pb-2">Filter Fixtures</h3>
                <form action="predictions.php" method="GET" class="space-y-4">
                    <?php if(!empty($searchTerm)): ?>
                        <input type="hidden" name="q" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    <?php endif; ?>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Country</label>
                        <select name="country" class="w-full bg-slate-800/60 border border-slate-700 rounded-lg py-2 px-3 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                            <option value="">All Countries</option>
                            <option value="England" <?php if($filterCountry == 'England') echo 'selected'; ?>>England</option>
                            <option value="Spain" <?php if($filterCountry == 'Spain') echo 'selected'; ?>>Spain</option>
                            <option value="Italy" <?php if($filterCountry == 'Italy') echo 'selected'; ?>>Italy</option>
                            <option value="Germany" <?php if($filterCountry == 'Germany') echo 'selected'; ?>>Germany</option>
                            <option value="France" <?php if($filterCountry == 'France') echo 'selected'; ?>>France</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">League / Tournament</label>
                        <select name="league" class="w-full bg-slate-800/60 border border-slate-700 rounded-lg py-2 px-3 text-xs text-white focus:outline-none focus:border-cyan-500 transition-colors">
                            <option value="">All Leagues</option>
                            <option value="Premier League" <?php if($filterLeague == 'Premier League') echo 'selected'; ?>>Premier League</option>
                            <option value="La Liga" <?php if($filterLeague == 'La Liga') echo 'selected'; ?>>La Liga</option>
                            <option value="Serie A" <?php if($filterLeague == 'Serie A') echo 'selected'; ?>>Serie A</option>
                            <option value="Bundesliga" <?php if($filterLeague == 'Bundesliga') echo 'selected'; ?>>Bundesliga</option>
                            <option value="Ligue 1" <?php if($filterLeague == 'Ligue 1') echo 'selected'; ?>>Ligue 1</option>
                            <option value="Champions League" <?php if($filterLeague == 'Champions League') echo 'selected'; ?>>Champions League</option>
                        </select>
                    </div>

                    <div class="flex space-x-2 pt-2">
                        <button type="submit" class="flex-1 bg-cyan-600 hover:bg-cyan-500 text-white text-[10px] font-bold uppercase tracking-widest py-2 rounded-lg transition shadow-lg shadow-cyan-900/30">Apply Filters</button>
                        <a href="predictions.php" class="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white text-[10px] font-bold uppercase tracking-widest py-2 rounded-lg text-center transition">Reset</a>
                    </div>
                </form>
            </div>
            
            <!-- Ad Slot -->
            <div class="bg-slate-900/60 backdrop-blur border border-slate-800 rounded-2xl p-4 text-center">
                <span class="text-[9px] text-slate-500 uppercase tracking-widest">Sponsored</span>
                <div class="mt-2 h-48 bg-slate-800 rounded-xl flex items-center justify-center">
                    <span class="text-xs text-slate-600 font-bold">300x250 Ad Slot</span>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-span-1 lg:col-span-3 flex flex-col space-y-6">
            
            <!-- Stats -->
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 bg-slate-900/80 backdrop-blur border border-slate-800 rounded-2xl p-4">
                <div class="text-center border-r border-slate-800 md:border-r md:last:border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Live Data Source</span>
                    <span class="block text-xl font-black text-white mt-1 uppercase"><?php echo defined('DATA_SOURCE') ? DATA_SOURCE : 'API'; ?></span>
                </div>
                <div class="text-center border-r border-slate-800 md:border-r md:last:border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Available Matches</span>
                    <span class="block text-xl font-black text-emerald-400 mt-1"><?php echo isset($total_records) ? number_format($total_records) : 0; ?></span>
                </div>
                <div class="text-center border-r-0 px-2">
                    <span class="block text-[10px] text-slate-500 uppercase tracking-widest font-bold">Showing Page</span>
                    <span class="block text-xl font-black text-cyan-400 mt-1"><?php echo $page; ?> of <?php echo $total_pages; ?></span>
                </div>
            </div>

            <!-- Fixtures Table -->
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl overflow-hidden shadow-2xl divide-y divide-slate-800/40">
                
                <!-- Desktop Header -->
                <div class="hidden lg:grid grid-cols-12 gap-4 p-4.5 border-b border-slate-800 bg-slate-950/40 text-[8px] font-black tracking-[0.2em] uppercase text-slate-500">
                    <div class="col-span-3 pl-2">Kick-off (UTC)</div>
                    <div class="col-span-4">Fixture & Tournament Details</div>
                    <div class="col-span-2 text-center">Result</div>
                    <div class="col-span-3 text-right pr-4">Global Bookmaker Odds (1X2)</div>
                </div>

                <?php if (!empty($db_error)): ?>
                    <div class="p-12 text-center flex flex-col items-center space-y-3">
                        <span class="text-2xl">⚠️</span>
                        <div class="text-sm text-rose-500 font-bold tracking-widest uppercase">DATABASE SYNC ERROR</div>
                        <div class="text-[10px] text-slate-400 font-mono bg-slate-950 p-3 rounded-lg border border-slate-800 max-w-lg overflow-x-auto"><?php echo htmlspecialchars($db_error); ?></div>
                    </div>
                <?php elseif (empty($fixtures)): ?>
                    <div class="p-12 text-center text-sm text-slate-500 font-bold tracking-widest uppercase">
                        🤖 NO MATCHES FOUND MATCHING SEARCH FILTERS
                    </div>
                <?php else: ?>
                    <?php foreach ($fixtures as $fix): 
                        // Determine match status
                        $status = $fix['match_status'] ?? 'NS';
                        $is_finished = in_array($status, ['FT', 'AET', 'PEN']);
                        $home_goals = $fix['home_goals'];
                        $away_goals = $fix['away_goals'];
                        $winner = $fix['winner'] ?? null;

                        // Odds
                        $h_odds = isset($fix['home_odds']) ? (float)$fix['home_odds'] : 0;
                        $d_odds = isset($fix['draw_odds']) ? (float)$fix['draw_odds'] : 0;
                        $a_odds = isset($fix['away_odds']) ? (float)$fix['away_odds'] : 0;
                        $has_odds = ($h_odds > 0 || $d_odds > 0 || $a_odds > 0);
                    ?>
                        <div class="flex flex-col lg:grid lg:grid-cols-12 gap-3 p-4 md:p-5 hover:bg-slate-800/30 transition-colors items-start lg:items-center">
                            
                            <!-- Time & Status -->
                            <div class="col-span-3 w-full lg:w-auto flex flex-row lg:flex-col justify-between items-center lg:items-start pl-0 lg:pl-2 border-b lg:border-b-0 border-slate-800/40 pb-3 lg:pb-0 mb-2 lg:mb-0">
                                <span class="text-xs font-mono text-cyan-400 font-bold bg-cyan-500/10 px-2 py-0.5 rounded">
                                    <?php echo date("d M H:i", strtotime($fix['match_date'])); ?>
                                </span>
                                <span class="text-[9px] text-slate-400 font-bold uppercase lg:mt-2 truncate max-w-[120px] tracking-wider">
                                    <?php echo htmlspecialchars($fix['match_status'] ?? 'Pending'); ?>
                                </span>
                            </div>
                            
                            <!-- Fixture Details -->
                            <div class="col-span-4 w-full lg:w-auto flex flex-col justify-center space-y-2 border-b lg:border-b-0 border-slate-800/40 pb-3 lg:pb-0 mb-2 lg:mb-0">
                                <div class="text-[8px] font-black uppercase tracking-[0.15em] text-emerald-400 truncate">
                                    <?php echo htmlspecialchars($fix['league_name'] ?? 'Unknown'); ?>
                                </div>
                                <div class="flex flex-col space-y-1">
                                    <div class="flex items-center space-x-2">
                                        <?php if(!empty($fix['home_team_logo'])): ?>
                                            <img src="<?php echo htmlspecialchars($fix['home_team_logo']); ?>" class="w-4 h-4 object-contain" alt="logo">
                                        <?php endif; ?>
                                        <span class="font-bold text-xs text-white truncate"><?php echo htmlspecialchars($fix['home_team_name'] ?? 'TBD'); ?></span>
                                    </div>
                                    <div class="flex items-center space-x-2">
                                        <?php if(!empty($fix['away_team_logo'])): ?>
                                            <img src="<?php echo htmlspecialchars($fix['away_team_logo']); ?>" class="w-4 h-4 object-contain" alt="logo">
                                        <?php endif; ?>
                                        <span class="font-bold text-xs text-slate-400 truncate"><?php echo htmlspecialchars($fix['away_team_name'] ?? 'TBD'); ?></span>
                                    </div>
                                </div>
                            </div>

                            <!-- Result -->
                            <div class="col-span-2 w-full lg:w-auto text-center">
                                <?php if ($is_finished && $home_goals !== null && $away_goals !== null): ?>
                                    <div class="flex items-center justify-center space-x-2">
                                        <span class="text-lg font-black text-white"><?php echo $home_goals; ?></span>
                                        <span class="text-xs font-bold text-slate-500">–</span>
                                        <span class="text-lg font-black text-white"><?php echo $away_goals; ?></span>
                                    </div>
                                    <?php if ($winner): ?>
                                        <div class="text-[8px] font-bold uppercase tracking-widest mt-0.5">
                                            <?php if ($winner === '1'): ?>
                                                <span class="text-emerald-400">🏆 Home</span>
                                            <?php elseif ($winner === 'X'): ?>
                                                <span class="text-yellow-400">🤝 Draw</span>
                                            <?php elseif ($winner === '2'): ?>
                                                <span class="text-rose-400">🏆 Away</span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-xs text-slate-500 font-bold uppercase tracking-wider">–</span>
                                <?php endif; ?>
                            </div>

                            <!-- Odds -->
                            <div class="col-span-3 w-full lg:w-auto flex justify-between lg:justify-end items-center lg:pr-2">
                                <span class="lg:hidden text-[9px] font-bold text-slate-500 uppercase tracking-widest">Market Odds:</span>
                                
                                <?php if($has_odds): ?>
                                    <div class="flex space-x-2 w-full lg:w-auto justify-end">
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-cyan-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">1</span>
                                            <span class="font-mono text-xs font-black text-cyan-400"><?php echo number_format($h_odds, 2); ?></span>
                                        </div>
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-slate-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">X</span>
                                            <span class="font-mono text-xs font-black text-slate-300"><?php echo number_format($d_odds, 2); ?></span>
                                        </div>
                                        <div class="bg-slate-900/80 border border-slate-700/50 hover:border-amber-500/50 transition-colors rounded-xl px-3 py-1.5 flex flex-col items-center flex-1 lg:flex-none cursor-pointer">
                                            <span class="text-[8px] text-slate-500 font-bold uppercase tracking-widest mb-0.5">2</span>
                                            <span class="font-mono text-xs font-black text-amber-400"><?php echo number_format($a_odds, 2); ?></span>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <span class="bg-slate-800/60 text-slate-500 border border-slate-700/60 px-4 py-2 rounded-xl text-[9px] font-black tracking-widest uppercase flex items-center space-x-2">
                                        <svg class="animate-spin h-3 w-3 text-slate-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                                        <span>Odds Awaiting Sync</span>
                                    </span>
                                <?php endif; ?>
                            </div>

                        </div>

                    <?php endforeach; ?>
                <?php endif; ?>

            </div>

            <!-- Ad Slot -->
            <div class="w-full flex justify-center py-4">
                <?php display_ad_slot($pdo, 'in_content'); ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="flex justify-center pt-2">
                    <div class="flex items-center space-x-1 bg-slate-900/60 border border-slate-800 p-1 rounded-xl text-xs overflow-x-auto max-w-full">
                        
                        <?php if ($page > 1): ?>
                            <a href="predictions.php?page=<?php echo $page - 1 . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">Prev</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-slate-600 cursor-not-allowed rounded-lg">Prev</span>
                        <?php endif; ?>

                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        if($start > 1) {
                            echo '<a href="predictions.php?page=1'.(!empty($searchTerm) ? '&q='.urlencode($searchTerm) : '').'" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">1</a>';
                            if($start > 2) echo '<span class="px-2 text-slate-600">...</span>';
                        }

                        for ($i = $start; $i <= $end; $i++): 
                        ?>
                            <a href="predictions.php?page=<?php echo $i . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 rounded-lg font-bold transition <?php echo $i == $page ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30' : 'text-slate-400 hover:text-white'; ?>"><?php echo $i; ?></a>
                        <?php endfor; ?>

                        <?php 
                        if($end < $total_pages) {
                            if($end < $total_pages - 1) echo '<span class="px-2 text-slate-600">...</span>';
                            echo '<a href="predictions.php?page='.$total_pages.(!empty($searchTerm) ? '&q='.urlencode($searchTerm) : '').'" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">'.$total_pages.'</a>';
                        }
                        ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="predictions.php?page=<?php echo $page + 1 . (!empty($searchTerm) ? '&q=' . urlencode($searchTerm) : '') . (!empty($filterCountry) ? '&country=' . urlencode($filterCountry) : '') . (!empty($filterLeague) ? '&league=' . urlencode($filterLeague) : ''); ?>" class="px-3 py-1.5 text-slate-400 hover:text-white transition rounded-lg">Next</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-slate-600 cursor-not-allowed rounded-lg">Next</span>
                        <?php endif; ?>

                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

<script>
    // Neural Canvas Background (unchanged)
    const canvas = document.getElementById("neuralCanvas");
    if(canvas) {
        const ctx = canvas.getContext("2d");
        let width, height;
        let particles = [];
        let mouse = { x: null, y: null, radius: 150 };
        window.addEventListener('mousemove', function(e) {
            mouse.x = e.x;
            mouse.y = e.y;
        });

        function initCanvas() {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
            particles = [];
            let particleCount = (width * height) / 12000;
            for (let i = 0; i < particleCount; i++) {
                particles.push({
                    x: Math.random() * width,
                    y: Math.random() * height,
                    vx: (Math.random() - 0.5) * 1.5,
                    vy: (Math.random() - 0.5) * 1.5,
                    radius: Math.random() * 1.5 + 0.5
                });
            }
        }

        function animateCanvas() {
            ctx.clearRect(0, 0, width, height);
            for (let i = 0; i < particles.length; i++) {
                let p = particles[i];
                p.x += p.vx;
                p.y += p.vy;
                if (p.x < 0 || p.x > width) p.vx *= -1;
                if (p.y < 0 || p.y > height) p.vy *= -1;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                ctx.fillStyle = "rgba(16, 185, 129, 0.35)";
                ctx.fill();
                for (let j = i + 1; j < particles.length; j++) {
                    let p2 = particles[j];
                    let dist = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2));
                    if (dist < 100) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(p2.x, p2.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${1 - dist/100})`;
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                }
                if (mouse.x && mouse.y) {
                    let mouseDist = Math.sqrt(Math.pow(p.x - mouse.x, 2) + Math.pow(p.y - mouse.y, 2));
                    if (mouseDist < mouse.radius) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(mouse.x, mouse.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${0.8 - mouseDist/mouse.radius})`;
                        ctx.lineWidth = 1;
                        ctx.stroke();
                    }
                }
            }
            requestAnimationFrame(animateCanvas);
        }

        window.addEventListener("resize", initCanvas);
        initCanvas();
        animateCanvas();
    }
</script>