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

// ---------------------------------------------------------
// AUTHENTICATION CHECK
// ---------------------------------------------------------
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login-register.php");
    exit;
}

require_once __DIR__ . '/../../config/config.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 TIER MANAGEMENT (Synced to Database users table)
// ---------------------------------------------------------
$user_id = $_SESSION['user_id'];
$is_vip = false;
$vip_expires_at = null;
$user_name = 'User';

try {
    $user_stmt = $pdo->prepare("SELECT full_name, user_tier, vip_expires_at FROM users WHERE id = ?");
    $user_stmt->execute([$user_id]);
    $u_row = $user_stmt->fetch(PDO::FETCH_ASSOC);

    if ($u_row) {
        $user_name = $u_row['full_name'] ?: 'User';
        $is_vip = ($u_row['user_tier'] === 'VIP' && strtotime($u_row['vip_expires_at']) > time());
        $vip_expires_at = $u_row['vip_expires_at'];
    }
} catch (PDOException $e) {
    error_log("Dashboard User Query Error: " . $e->getMessage());
}

// ---------------------------------------------------------
// DYNAMIC SUBSCRIPTION PLAN FETCH (Synced to subscription_plans table)
// ---------------------------------------------------------
$active_plan_name = 'Free Basic';
$plan_duration_days = 0;
try {
    $plan_stmt = $pdo->prepare("
        SELECT p.plan_name, p.duration_days 
        FROM transactions t 
        JOIN subscription_plans p ON t.plan_id = p.id 
        WHERE t.user_id = ? AND t.status = 'approved' AND DATE(DATE_ADD(t.created_at, INTERVAL p.duration_days DAY)) >= CURDATE()
        ORDER BY p.price DESC 
        LIMIT 1
    ");
    $plan_stmt->execute([$user_id]);
    $plan_row = $plan_stmt->fetch(PDO::FETCH_ASSOC);

    if ($plan_row) {
        $active_plan_name = $plan_row['plan_name'];
        $plan_duration_days = $plan_row['duration_days'];
    }
} catch (PDOException $e) {
    error_log("Dashboard Plan Query Error: " . $e->getMessage());
}

// ---------------------------------------------------------
// NEURAL ENGINE DATA FETCH (Hybrid Matrix Query)
// ---------------------------------------------------------
$real_matches = [];
try {
    $stmt = $pdo->prepare("
        SELECT 
            p.prediction_pick, p.odds, p.confidence, p.is_vip,
            f.match_date, f.league_name,
            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) >= CURDATE()
        ORDER BY f.match_date ASC
        LIMIT 5
    ");
    $stmt->execute();
    $real_matches = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Dashboard Query Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Command Center - <?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; }
    </style>
</head>
<body class="bg-[#020617] text-slate-200 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-emerald-500 animate-pulse"></span>
                <span>tipspac <span class="text-emerald-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-8">
            
            <div class="flex flex-col md:flex-row md:items-end justify-between gap-6">
                <div>
                    <div class="inline-flex items-center space-x-2 mb-2">
                        <?php if ($is_vip): ?>
                            <span class="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest">VIP Terminal Active</span>
                        <?php else: ?>
                            <span class="bg-slate-800 text-slate-400 border border-slate-700 px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest">Free Terminal Active</span>
                        <?php endif; ?>
                    </div>
                    <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">
                        Welcome back, <span class="text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-teal-400"><?php echo htmlspecialchars($user_name); ?></span>
                    </h1>
                    <p class="text-xs text-slate-400 mt-2 max-w-xl">Your neural terminal is synced. System algorithms are actively processing live match data.</p>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php if ($is_vip): ?>
                    <div class="bg-gradient-to-br from-amber-500/10 to-orange-500/5 backdrop-blur-xl border border-amber-500/30 rounded-3xl p-6 flex flex-col justify-between relative overflow-hidden group hover:-translate-y-1 transition-transform">
                        <div class="absolute top-0 right-0 w-32 h-32 bg-amber-500/10 rounded-full blur-[40px]"></div>
                        <div>
                            <div class="flex items-center justify-between mb-4">
                                <span class="text-[9px] font-black tracking-widest uppercase text-amber-500 bg-amber-500/10 px-2.5 py-1 rounded">Active Subscription</span>
                                <span class="text-amber-500">👑</span>
                            </div>
                            <h3 class="text-2xl font-black text-white"><?php echo htmlspecialchars($active_plan_name); ?></h3>
                            <p class="text-[10px] text-amber-200/60 mt-1 font-medium">Full model access. Active tier expires on: <?= $vip_expires_at ? date("M d, Y", strtotime($vip_expires_at)) : 'N/A' ?></p>
                        </div>
                        <div class="mt-6 pt-4 border-t border-amber-500/20 flex justify-between items-center">
                            <span class="text-[9px] font-bold text-slate-400">Validity: <?= $plan_duration_days; ?> Days Scheme</span>
                            <a href="<?php echo SITE_URL; ?>/public/user/billing.php" class="text-[9px] font-bold text-amber-400 hover:text-amber-300 uppercase tracking-widest">Renew / Expand</a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 flex flex-col justify-between relative overflow-hidden group hover:-translate-y-1 transition-transform">
                        <div>
                            <div class="flex items-center justify-between mb-4">
                                <span class="text-[9px] font-black tracking-widest uppercase text-slate-400 bg-slate-800 px-2.5 py-1 rounded">Current Plan</span>
                                <span class="text-slate-500">🛡️</span>
                            </div>
                            <h3 class="text-2xl font-black text-white">Free Basic Tier</h3>
                            <p class="text-[10px] text-slate-400 mt-1">Limited access. Premium slips, bankers and model calculations are masked.</p>
                        </div>
                        <div class="mt-6 pt-4 border-t border-slate-800 flex justify-between items-center">
                            <a href="<?php echo SITE_URL; ?>/public/user/billing.php" class="w-full text-center bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-white py-2.5 rounded-xl text-[9px] font-black uppercase tracking-widest shadow-lg shadow-emerald-500/20 transition">Billing & Upgrades</a>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 flex flex-col justify-between relative overflow-hidden group hover:-translate-y-1 transition-transform">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-emerald-500/5 rounded-full blur-[40px]"></div>
                    <div>
                        <div class="flex items-center justify-between mb-4">
                            <span class="text-[9px] font-black tracking-widest uppercase text-slate-500">System Status</span>
                            <span class="flex items-center space-x-1.5 border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 rounded text-[8px] font-bold text-emerald-400 uppercase tracking-widest">
                                <span class="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse"></span>
                                <span>Online</span>
                            </span>
                        </div>
                        <h3 class="text-3xl font-black text-white tracking-tighter">162<span class="text-lg text-slate-500 font-bold ml-1">Nodes</span></h3>
                        <p class="text-[10px] text-slate-400 mt-1">Deep-learning algorithms actively crunching data.</p>
                    </div>
                    <div class="mt-6 pt-4 border-t border-slate-800 flex flex-col space-y-2">
                        <div class="flex justify-between text-[9px] font-bold">
                            <span class="text-slate-500 uppercase tracking-wider">Database Sync</span>
                            <span class="text-emerald-400">100%</span>
                        </div>
                        <div class="w-full bg-slate-950 rounded-full h-1">
                            <div class="bg-emerald-400 h-1 rounded-full w-full"></div>
                        </div>
                    </div>
                </div>

                <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 flex flex-col justify-between relative overflow-hidden group hover:-translate-y-1 transition-transform">
                    <?php if (!$is_vip): ?>
                        <div class="absolute inset-0 bg-slate-950/60 backdrop-blur-md flex flex-col items-center justify-center z-10 rounded-3xl">
                            <span class="text-amber-500 text-2xl mb-2">🔒</span>
                            <span class="text-[9px] font-black uppercase tracking-widest text-white">Pro Stat Locked</span>
                        </div>
                    <?php endif; ?>
                    <div class="<?php echo !$is_vip ? 'opacity-30 filter blur-sm' : ''; ?>">
                        <div class="flex items-center justify-between mb-4">
                            <span class="text-[9px] font-black tracking-widest uppercase text-slate-500">Last 7 Days ROI</span>
                            <span class="text-emerald-400">📈</span>
                        </div>
                        <h3 class="text-3xl font-black text-emerald-400 tracking-tighter">+84.2<span class="text-lg text-emerald-500/50 font-bold ml-1">%</span></h3>
                        <p class="text-[10px] text-slate-400 mt-1">Win rate across all premium generated tips.</p>
                    </div>
                    <div class="mt-6 pt-4 border-t border-slate-800 flex justify-between items-center <?php echo !$is_vip ? 'opacity-30 filter blur-sm' : ''; ?>">
                        <div class="flex space-x-1">
                            <span class="w-2 h-4 bg-emerald-500/20 rounded-sm"></span>
                            <span class="w-2 h-6 bg-emerald-500/40 rounded-sm"></span>
                            <span class="w-2 h-5 bg-emerald-500/60 rounded-sm"></span>
                            <span class="w-2 h-8 bg-emerald-500/80 rounded-sm"></span>
                            <span class="w-2 h-7 bg-emerald-500 rounded-sm"></span>
                        </div>
                        <a href="history.php" class="text-[9px] font-bold text-slate-400 uppercase tracking-widest hover:text-white transition">View History</a>
                    </div>
                </div>
            </div>

            <div class="mt-10">
                <div class="flex items-center justify-between mb-4 px-2">
                    <h3 class="text-lg font-black text-white tracking-tight">Today's <span class="text-emerald-400">Radar Preview</span></h3>
                    <a href="<?php echo SITE_URL; ?>/public/user/bet-of-the-day-pro.php" class="text-[9px] font-bold text-slate-400 hover:text-white uppercase tracking-widest flex items-center transition">
                        Open Terminal <svg class="w-3 h-3 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
                    </a>
                </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-[10px] font-black tracking-widest uppercase text-slate-500">
                        <div class="col-span-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">Odds</div>
                    </div>

                    <?php if (empty($real_matches)): ?>
                        <div class="p-10 text-center border-b border-slate-800/50">
                            <span class="text-3xl mb-3 block text-emerald-500 animate-pulse">📡</span>
                            <p class="text-sm font-bold text-slate-300">Neural Engine Processing...</p>
                            <p class="text-[10px] text-slate-500 mt-2 uppercase tracking-widest">Awaiting synchronization with the live fixture matrix.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($real_matches as $match): ?>
                            
                            <?php 
                                $kickoff = date('H:i', strtotime($match['match_date'])); 
                            ?>

                            <?php if ($match['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">
                                    <div class="md:col-span-2 flex md:flex-col items-center md:items-start justify-between md:justify-center">
                                        <span class="text-xs font-mono text-emerald-400 font-bold bg-emerald-500/10 px-2 py-0.5 rounded"><?php echo htmlspecialchars($kickoff); ?></span>
                                        <span class="text-[9px] text-slate-500 font-bold uppercase mt-1 truncate max-w-[120px]"><?php echo htmlspecialchars($match['league_name']); ?></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($match['home_team']); ?></div>
                                        <div class="font-bold text-sm text-slate-400"><?php echo htmlspecialchars($match['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-[10px] font-black tracking-widest text-amber-500 uppercase">VIP Tier Locked</span>
                                            <a href="<?php echo SITE_URL; ?>/public/user/billing.php" class="ml-4 bg-amber-500 text-slate-950 px-3 py-1 rounded text-[9px] 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">
                                        <span class="text-xs font-mono text-emerald-400 font-bold bg-emerald-500/10 px-2 py-0.5 rounded"><?php echo htmlspecialchars($kickoff); ?></span>
                                        <span class="text-[9px] text-slate-500 font-bold uppercase mt-1 truncate max-w-[120px]"><?php echo htmlspecialchars($match['league_name']); ?></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($match['home_team']); ?></div>
                                        <div class="font-bold text-sm text-slate-400"><?php echo htmlspecialchars($match['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-[11px] font-black tracking-wider shadow-[0_0_10px_rgba(16,185,129,0.1)]">
                                            <?php echo htmlspecialchars($match['prediction_pick']); ?>
                                        </span>
                                    </div>
                                    <div class="md:col-span-3 flex flex-col justify-center mt-2 md:mt-0">
                                        <div class="flex justify-between text-[10px] font-bold mb-1">
                                            <span class="text-slate-400">Model Compute</span>
                                            <span class="text-emerald-400 font-black"><?php echo htmlspecialchars($match['confidence']); ?>%</span>
                                        </div>
                                        <div class="w-full bg-slate-800 rounded-full h-1.5 overflow-hidden">
                                            <div class="bg-gradient-to-r from-emerald-500 to-teal-400 h-1.5 rounded-full" style="width: <?php echo htmlspecialchars($match['confidence']); ?>%"></div>
                                        </div>
                                    </div>
                                    <div class="md:col-span-1 flex justify-end">
                                        <span class="text-xs font-black text-slate-300"><?php echo htmlspecialchars($match['odds']); ?></span>
                                    </div>
                                </div>
                            <?php endif; ?>

                        <?php endforeach; ?>
                    <?php endif; ?>
                </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(16, 185, 129, 0.25)";
                    ctx.fill();
                }
                requestAnimationFrame(animateCanvas);
            }
            window.addEventListener("resize", initCanvas);
            initCanvas(); animateCanvas();
        }
    </script>
</body>
</html>