<?php
// Initialize session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ---------------------------------------------------------
// AUTHENTICATION CHECK
// ---------------------------------------------------------
// If the user isn't logged in, kick them back to the login terminal
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login-register.php");
    exit;
}

// Ensure this path jumps up from public/user/ to the root for config
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../includes/ad-display.php';

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

// Check user tier from live session
$is_vip = isset($_SESSION['user_tier']) && $_SESSION['user_tier'] === 'VIP';

// ---------------------------------------------------------
// DATA FETCHING ENGINE (JOINING PREDICTIONS, FIXTURES, AND TEAMS)
// ---------------------------------------------------------
$today = date('Y-m-d');
try {
    // The JOIN query connects our 3 hybrid tables to assemble the full match context
    $stmt = $pdo->prepare("
        SELECT 
            p.id,
            p.prediction_pick AS ai_pick,
            p.confidence,
            p.is_vip,
            f.league_name AS league,
            DATE_FORMAT(f.match_date, '%H:%i') AS match_time,
            t_home.name AS home_team,
            t_away.name AS away_team
        FROM predictions p
        JOIN fixtures f ON p.fixture_id = f.id
        JOIN teams t_home ON f.home_team_id = t_home.id
        JOIN teams t_away ON f.away_team_id = t_away.id
        WHERE DATE(f.match_date) = ?
        ORDER BY f.match_date ASC
    ");
    $stmt->execute([$today]);
    $predictions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $predictions = []; 
}

// Fallback array if database is empty for testing UI visual states
// (Updated to match the new boolean 'is_vip' logic instead of string 'access_tier')
if (empty($predictions)) {
    $predictions = [
        ['id' => 1, 'match_time' => '14:00', 'league' => 'Premier League', 'home_team' => 'Arsenal', 'away_team' => 'Chelsea', 'ai_pick' => 'Over 2.5', 'confidence' => 89, 'is_vip' => 0],
        ['id' => 2, 'match_time' => '18:30', 'league' => 'La Liga', 'home_team' => 'Real Madrid', 'away_team' => 'Sevilla', 'ai_pick' => 'Home Win', 'confidence' => 92, 'is_vip' => 0],
        ['id' => 3, 'match_time' => '21:00', 'league' => 'Champions League', 'home_team' => 'AC Milan', 'away_team' => 'Paris SG', 'ai_pick' => 'BTTS - Yes', 'confidence' => 85, 'is_vip' => 1],
    ];
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Predictions Terminal - <?php echo htmlspecialchars($site_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #020617; }
        ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: #334155; }
        .hide-scroll::-webkit-scrollbar { display: none; }
        .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body class="bg-[#020617] text-slate-300 font-sans antialiased min-h-screen relative overflow-x-hidden">

    <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]/90 to-[#020617]/80 pointer-events-none"></div>
    <canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-30"></canvas>

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

    <div class="relative z-10 flex flex-col min-h-screen md:pl-64 transition-all duration-300">
        
        <header class="md:hidden w-full border-b border-slate-800/60 bg-slate-950/80 backdrop-blur-md h-16 flex items-center justify-between px-4 sticky top-0 z-30">
            <div class="text-white font-black tracking-tighter text-lg flex items-center space-x-2">
                <span class="w-2 h-2 rounded-full bg-indigo-500 animate-pulse"></span>
                <span>Pred <span class="text-indigo-400">Pro</span></span>
            </div>
            <button onclick="toggleSidebar()" class="text-slate-300 hover:text-white p-2 focus:outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
            </button>
        </header>

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

            <div class="flex flex-col md:flex-row md:items-end justify-between mb-2 space-y-4 md:space-y-0 border-b border-slate-800/60 pb-6">
                <div>
                    <div class="inline-flex items-center space-x-2 bg-indigo-500/10 border border-indigo-500/20 px-3 py-1 rounded-full text-[9px] font-bold tracking-widest uppercase text-indigo-400 mb-2">
                        <span class="w-1.5 h-1.5 rounded-full bg-indigo-400 animate-pulse"></span>
                        <span>Autonomous AI Engine</span>
                    </div>
                    <h1 class="text-3xl md:text-4xl font-black text-white tracking-tight">AI Predictions <span class="text-cyan-400">Terminal</span></h1>
                    <p class="text-xs text-slate-400 mt-1 max-w-xl">Real-time match analysis, Poisson distribution modeling, and probability ratings calculated via machine learning nodes.</p>
                </div>
                
                <div class="flex bg-slate-950/60 border border-slate-800 rounded-xl p-1 shadow-lg w-max self-start md:self-end">
                    <button class="px-4 py-2 text-[9px] font-bold text-slate-400 hover:text-white transition rounded-lg uppercase tracking-wider">Yesterday</button>
                    <button class="px-4 py-2 text-[9px] font-bold text-white bg-indigo-600 rounded-lg shadow uppercase tracking-wider border border-indigo-500/30">Today, <?php echo date('d M'); ?></button>
                    <button class="px-4 py-2 text-[9px] font-bold text-slate-400 hover:text-white transition rounded-lg uppercase tracking-wider">Tomorrow</button>
                </div>
            </div>

            <div class="w-full flex justify-center py-2">
                <?php display_ad_slot($pdo, 'header'); ?>
            </div>

            <div class="grid grid-cols-3 gap-4 bg-slate-900/60 backdrop-blur border border-slate-800 rounded-2xl p-4 shadow-xl">
                <div class="text-center border-r border-slate-800">
                    <span class="block text-[8px] text-slate-500 uppercase tracking-[0.2em] font-bold">Algorithms Deployed</span>
                    <span class="block text-xl font-black text-white mt-1 font-mono">162+</span>
                </div>
                <div class="text-center border-r border-slate-800">
                    <span class="block text-[8px] text-slate-500 uppercase tracking-[0.2em] font-bold">Verified Success Rate</span>
                    <span class="block text-xl font-black text-emerald-400 mt-1 font-mono">79%</span>
                </div>
                <div class="text-center">
                    <span class="block text-[8px] text-slate-500 uppercase tracking-[0.2em] font-bold">Compute Status</span>
                    <span class="block text-xl font-black text-cyan-400 mt-1 tracking-widest">ONLINE</span>
                </div>
            </div>

            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-2xl overflow-hidden shadow-2xl">
                
                <div class="hidden md:grid grid-cols-12 gap-4 p-4 border-b border-slate-800 bg-slate-950/50 text-[9px] font-black tracking-[0.2em] uppercase text-slate-500 items-center">
                    <div class="col-span-2 pl-2">Kick-off</div>
                    <div class="col-span-4">Match Fixture</div>
                    <div class="col-span-2 text-center">Calculated AI Pick</div>
                    <div class="col-span-3 text-center">Confidence Level</div>
                    <div class="col-span-1 text-right pr-2">Analytics</div>
                </div>
                
                <?php if (empty($predictions)): ?>
                    <div class="p-12 text-center text-xs font-bold text-slate-600 tracking-[0.2em] uppercase">🤖 PARSING LIVE DATA FEEDS...</div>
                <?php else: ?>
                    <?php foreach ($predictions as $pred): ?>
                        
                        <?php 
                        // Check boolean is_vip column against user session tier
                        if ($pred['is_vip'] == 1 && !$is_vip): 
                        ?>
                            <div class="grid grid-cols-1 md:grid-cols-12 gap-4 p-4 md:p-5 border-b border-slate-800/50 items-center hover:bg-slate-800/40 transition-colors opacity-80 relative overflow-hidden">
                                <div class="md:col-span-2 flex md:flex-col items-center md:items-start justify-between md:justify-center pl-2">
                                    <span class="text-xs font-mono text-indigo-400 font-bold bg-indigo-500/10 px-2 py-0.5 rounded"><?php echo htmlspecialchars($pred['match_time']); ?></span>
                                    <span class="text-[8px] text-slate-500 font-bold uppercase mt-1 truncate max-w-[120px]"><?php echo htmlspecialchars($pred['league']); ?></span>
                                </div>
                                
                                <div class="md:col-span-4 flex flex-col justify-center space-y-1 my-2 md:my-0">
                                    <div class="font-bold text-sm text-white"><?php echo htmlspecialchars($pred['home_team']); ?></div>
                                    <div class="font-bold text-sm text-slate-400"><?php echo htmlspecialchars($pred['away_team']); ?></div>
                                </div>
                                
                                <div class="md:col-span-6 flex items-center justify-center bg-amber-500/5 border border-amber-500/20 rounded-xl py-3 mt-2 md:mt-0 backdrop-blur-sm relative overflow-hidden">
                                    <div class="absolute inset-0 bg-gradient-to-r from-amber-500/10 to-orange-500/10 opacity-50"></div>
                                    <div class="relative flex items-center space-x-2">
                                        <span class="text-amber-500 text-lg">👑</span>
                                        <span class="text-[9px] font-black tracking-[0.1em] text-amber-500 uppercase">VIP Tier Locked</span>
                                        <a href="billing.php" class="ml-4 bg-amber-500 text-slate-950 px-3 py-1 rounded text-[8px] font-black tracking-widest uppercase hover:bg-amber-400 transition">Unlock</a>
                                    </div>
                                </div>
                            </div>
                        
                        <?php else: ?>
                            <div class="grid grid-cols-1 md:grid-cols-12 gap-4 p-4 md:p-5 border-b border-slate-800/50 items-center hover:bg-slate-800/40 transition-colors">
                                <div class="md:col-span-2 flex md:flex-col items-center md:items-start justify-between md:justify-center pl-2">
                                    <span class="text-xs font-mono text-indigo-400 font-bold bg-indigo-500/10 px-2 py-0.5 rounded"><?php echo htmlspecialchars($pred['match_time']); ?></span>
                                    <span class="text-[8px] text-slate-500 font-bold uppercase mt-1 truncate max-w-[120px]"><?php echo htmlspecialchars($pred['league']); ?></span>
                                </div>
                                
                                <div class="md:col-span-4 flex flex-col justify-center space-y-1 my-2 md:my-0">
                                    <div class="font-bold text-sm text-white"><?php echo htmlspecialchars($pred['home_team']); ?></div>
                                    <div class="font-bold text-sm text-slate-400"><?php echo htmlspecialchars($pred['away_team']); ?></div>
                                </div>
                                
                                <div class="md:col-span-2 flex justify-start md:justify-center">
                                    <span class="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-3 py-1.5 rounded-lg text-[10px] font-black tracking-wider shadow-[0_0_10px_rgba(16,185,129,0.1)]">
                                        <?php echo htmlspecialchars($pred['ai_pick']); ?>
                                    </span>
                                </div>

                                <div class="md:col-span-3 flex flex-col justify-center mt-2 md:mt-0 px-2">
                                    <div class="flex justify-between text-[8px] font-black tracking-[0.1em] uppercase mb-1">
                                        <span class="text-slate-400">Compute Accuracy</span>
                                        <span class="text-emerald-400"><?php echo htmlspecialchars($pred['confidence']); ?>%</span>
                                    </div>
                                    <div class="w-full bg-slate-950 border border-slate-800 rounded-full h-1.5 overflow-hidden">
                                        <div class="bg-gradient-to-r from-emerald-500 to-indigo-400 h-1.5 rounded-full" style="width: <?php echo htmlspecialchars($pred['confidence']); ?>%"></div>
                                    </div>
                                </div>

                                <div class="md:col-span-1 flex justify-end pr-2 mt-2 md:mt-0">
                                    <a href="match-center.php?id=<?php echo $pred['id']; ?>" class="bg-slate-800 hover:bg-slate-700 border border-slate-700 text-slate-300 px-3 py-2 rounded-xl text-[8px] tracking-[0.15em] uppercase font-bold transition">Analyze</a>
                                </div>
                            </div>
                        <?php endif; ?>

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

            </div>

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

            <div class="flex justify-center pt-4">
                <div class="flex items-center space-x-2 bg-slate-900/60 border border-slate-800 p-1 rounded-xl">
                    <button class="px-3 py-1.5 text-[10px] uppercase tracking-widest text-slate-500 hover:text-white transition font-bold">Prev</button>
                    <button class="bg-indigo-600/30 text-indigo-400 border border-indigo-500/30 px-3 py-1.5 rounded-lg text-[10px] font-black uppercase tracking-widest">1</button>
                    <button class="px-3 py-1.5 text-[10px] uppercase tracking-widest text-slate-400 hover:text-white transition font-bold">2</button>
                    <button class="px-3 py-1.5 text-[10px] uppercase tracking-widest text-slate-500 hover:text-white transition font-bold">3</button>
                    <span class="text-slate-600">...</span>
                    <button class="px-3 py-1.5 text-[10px] uppercase tracking-widest text-slate-500 hover:text-white transition font-bold">Next</button>
                </div>
            </div>

        </main>
    </div>

    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        }

        const canvas = document.getElementById("neuralCanvas");
        if(canvas) {
            const ctx = canvas.getContext("2d");
            let width, height;
            let particles = [];
            
            function initCanvas() {
                width = canvas.width = window.innerWidth;
                height = canvas.height = window.innerHeight;
                particles = [];
                for (let i = 0; i < (width * height) / 15000; 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(99, 102, 241, 0.2)"; ctx.fill();
                }
                requestAnimationFrame(animateCanvas);
            }
            window.addEventListener("resize", initCanvas);
            initCanvas(); animateCanvas();
        }
    </script>
</body>
</html>