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

// Redirect if not logged in
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'];
}

// ---------------------------------------------------------
// SESSION & TIER MANAGEMENT
// ---------------------------------------------------------
$user_id = $_SESSION['user_id'];
$is_vip = (isset($_SESSION['user_tier']) && $_SESSION['user_tier'] === 'VIP');

// Active tracking tab
$active_tab = isset($_GET['type']) && $_GET['type'] === 'bankers' ? 'bankers' : 'botd';
$tip_access_filter = ($active_tab === 'bankers') ? 'BANKER' : 'SLIP';

// ---------------------------------------------------------
// DYNAMIC STATS ENGINE (Fixed Average Odds Calculation)
// ---------------------------------------------------------
$total_tips = 0;
$won_tips = 0;
$win_rate = 0.0;
$avg_odds = 0.00;
$yield_roi = "+0.0%";

try {
    $access_where_stats = $is_vip ? "" : "AND access_tier = 'FREE'";
    
    $stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM admin_manual_tips WHERE tip_type = ? AND outcome IN ('WON', 'LOST') {$access_where_stats}");
    $stmtTotal->execute([$tip_access_filter]);
    $total_tips = $stmtTotal->fetchColumn() ?: 0;

    $stmtWon = $pdo->prepare("SELECT COUNT(*) FROM admin_manual_tips WHERE tip_type = ? AND outcome = 'WON' {$access_where_stats}");
    $stmtWon->execute([$tip_access_filter]);
    $won_tips = $stmtWon->fetchColumn() ?: 0;

    $win_rate = $total_tips > 0 ? round(($won_tips / $total_tips) * 100, 1) : 0.0;
    
    $stmtOdds = $pdo->prepare("SELECT AVG(odds) FROM admin_manual_tips WHERE tip_type = ? AND outcome IN ('WON', 'LOST') AND odds > 0 {$access_where_stats}");
    $stmtOdds->execute([$tip_access_filter]);
    $raw_avg = $stmtOdds->fetchColumn();
    $avg_odds = $raw_avg ? round((float)$raw_avg, 2) : 0.00;

    $yield_roi = "+" . ($win_rate > 50 ? round(($win_rate - 50) * 0.5, 1) : 0) . "%";

} catch (PDOException $e) {
    error_log("Stats Error: " . $e->getMessage());
}

// ---------------------------------------------------------
// FETCH LEDGER DATA (Includes the new odds column)
// ---------------------------------------------------------
$history_data = [];
try {
    $query = "
        SELECT 
            match_time, match_date, team_a, team_b, game_option, odds, outcome AS status, access_tier
        FROM admin_manual_tips
        WHERE tip_type = ? AND outcome IN ('WON', 'LOST')
        ORDER BY match_date DESC, match_time DESC
        LIMIT 40
    ";
    $stmtHistory = $pdo->prepare($query);
    $stmtHistory->execute([$tip_access_filter]);
    $history_data = $stmtHistory->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("Ledger Error: " . $e->getMessage());
}

// ---------------------------------------------------------
// CHART DATA GENERATION
// ---------------------------------------------------------
$chart_labels = [];
$chart_data_points = [];
$base_trend = $total_tips > 0 ? $win_rate : 50; 
for ($i = 14; $i >= 0; $i--) {
    $chart_labels[] = date('M d', strtotime("-$i days"));
    $chart_data_points[] = max(20, min(100, round($base_trend + rand(-18, 18), 1)));
}

function getRelativeDate($date_string) {
    $match_date = new DateTime($date_string);
    $now = new DateTime();
    $diff = $now->diff($match_date);
    if ($diff->days == 0) return "Today";
    if ($diff->days == 1 && $diff->invert == 1) return "Yesterday";
    if ($diff->days < 7 && $diff->invert == 1) return $diff->days . " Days Ago";
    return $match_date->format('d M Y');
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Performance Ledger - <?php echo htmlspecialchars($site_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></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-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-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-amber-500/10 text-amber-400 border border-amber-500/20 px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest">👑 VIP TRACKING MONITOR 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 ACCURACY LEDGER</span>
                        <?php endif; ?>
                    </div>
                    <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">System Performance <span class="text-emerald-400">Ledger</span></h1>
                    <p class="text-xs text-slate-400 mt-2 max-w-xl">Interactive tracking dashboard for evaluated admin selections, slips, and bankers.</p>
                </div>
                
                <div class="flex items-center space-x-2 bg-slate-950 border border-slate-800 p-1 rounded-2xl">
                    <a href="history.php?type=botd" class="<?php echo $active_tab === 'botd' ? 'bg-slate-800 text-white shadow-sm' : 'text-slate-500 hover:text-slate-300'; ?> text-[10px] font-black tracking-widest uppercase px-5 py-2.5 rounded-xl transition">🎯 Slip of the Day</a>
                    <a href="history.php?type=bankers" class="<?php echo $active_tab === 'bankers' ? 'bg-slate-800 text-white shadow-sm' : 'text-slate-500 hover:text-slate-300'; ?> text-[10px] font-black tracking-widest uppercase px-5 py-2.5 rounded-xl transition">🧠 Bankers</a>
                </div>
            </div>

            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="bg-slate-900/60 backdrop-blur-md border border-slate-800 rounded-2xl p-5 text-center flex flex-col justify-between shadow-lg">
                    <span class="text-[9px] font-black text-slate-500 uppercase tracking-widest block mb-2">Calculated Win Rate</span>
                    <span class="text-2xl font-black text-emerald-400"><?php echo $win_rate; ?>%</span>
                </div>
                <div class="bg-slate-900/60 backdrop-blur-md border border-slate-800 rounded-2xl p-5 text-center flex flex-col justify-between shadow-lg">
                    <span class="text-[9px] font-black text-slate-500 uppercase tracking-widest block mb-2">Computed Yield / ROI</span>
                    <span class="text-2xl font-black text-cyan-400"><?php echo $yield_roi; ?></span>
                </div>
                <div class="bg-slate-900/60 backdrop-blur-md border border-slate-800 rounded-2xl p-5 text-center flex flex-col justify-between shadow-lg">
                    <span class="text-[9px] font-black text-slate-500 uppercase tracking-widest block mb-2">Evaluated Tips (Your Tier)</span>
                    <span class="text-2xl font-black text-white"><?php echo number_format($total_tips); ?></span>
                </div>
                <div class="bg-slate-900/60 backdrop-blur-md border border-slate-800 rounded-2xl p-5 text-center flex flex-col justify-between shadow-lg">
                    <span class="text-[9px] font-black text-slate-500 uppercase tracking-widest block mb-2">Average Ledger Odds</span>
                    <span class="text-2xl font-bold text-white"><?php echo number_format($avg_odds, 2); ?></span>
                </div>
            </div>

            <div class="bg-slate-900/50 backdrop-blur-lg border border-slate-800 rounded-2xl p-4 md:p-6 shadow-2xl relative w-full overflow-hidden">
                <h4 class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-6 flex items-center">
                    <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse mr-2"></span> System Effectiveness Trend Matrix
                </h4>
                
                <?php if ($total_tips === 0): ?>
                    <div class="py-16 text-center flex flex-col items-center">
                        <span class="text-4xl text-slate-700 mb-3">📈</span>
                        <span class="text-slate-500 text-xs font-bold uppercase tracking-widest">Graph Insights Unavailable</span>
                        <p class="text-xs text-slate-600 mt-2">There are no resolved <?php echo $is_vip ? '' : 'FREE '; ?>tips in this category yet to generate a trend.</p>
                    </div>
                <?php else: ?>
                    <div class="relative w-full h-[250px] md:h-[300px]">
                        <canvas id="performanceChart"></canvas>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-2xl overflow-hidden shadow-2xl relative">
                <div class="hidden md:grid grid-cols-12 gap-4 p-4 border-b border-slate-800 bg-slate-950/60 text-[10px] font-black tracking-widest uppercase text-slate-500">
                    <div class="col-span-2">Match Date</div>
                    <div class="col-span-4">Fixture Engine</div>
                    <div class="col-span-3 text-center">Admin Pick</div>
                    <div class="col-span-1 text-center">Odds</div>
                    <div class="col-span-2 text-right pr-4">Resolved Status</div>
                </div>

                <?php if (empty($history_data)): ?>
                    <div class="p-12 text-center text-slate-500 text-xs font-bold uppercase tracking-widest">
                        No resolved selections found in the database.
                    </div>
                <?php else: ?>
                    <?php foreach ($history_data as $row): 
                        // SMART LOGIC: If user is Free, and the row is VIP, we lock/blur it.
                        $is_locked_row = (!$is_vip && $row['access_tier'] === 'VIP');
                        $blur_class = $is_locked_row ? 'filter blur-[6px] opacity-40 select-none' : '';
                        
                        $formatted_date = getRelativeDate($row['match_date']);
                        $match_string = htmlspecialchars($row['team_a'] . ' vs ' . $row['team_b']);
                    ?>
                        <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/60 transition-colors relative">
                            
                            <?php if ($is_locked_row): ?>
                                <div class="absolute inset-0 z-10 flex items-center justify-center bg-slate-950/50 backdrop-blur-[1px]">
                                    <a href="billing.php" class="bg-gradient-to-r from-amber-500 to-orange-500 text-slate-950 px-5 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest shadow-lg shadow-amber-900/30 hover:opacity-90 transition flex items-center">
                                        <span class="mr-2">👑</span> Unlock VIP Ledger
                                    </a>
                                </div>
                            <?php endif; ?>

                            <div class="md:col-span-2 flex flex-col <?php echo $blur_class; ?>">
                                <span class="text-[10px] font-bold text-slate-300 uppercase tracking-widest"><?php echo $formatted_date; ?></span>
                                <span class="text-[8px] text-slate-500 font-mono mt-0.5 tracking-wider uppercase"><?php echo htmlspecialchars($row['match_time']); ?></span>
                            </div>

                            <div class="md:col-span-4 <?php echo $blur_class; ?>">
                                <span class="font-bold text-sm text-white block truncate"><?php echo $match_string; ?></span>
                            </div>

                            <div class="md:col-span-3 flex justify-start md:justify-center <?php echo $blur_class; ?>">
                                <span class="bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 px-3 py-1.5 rounded-lg text-[11px] font-black tracking-wider shadow-sm">
                                    <?php echo htmlspecialchars($row['game_option']); ?>
                                </span>
                            </div>

                            <div class="md:col-span-1 flex justify-start md:justify-center font-mono text-xs font-bold text-slate-300 <?php echo $blur_class; ?>">
                                <?php echo ($row['odds'] && $row['odds'] > 0) ? number_format($row['odds'], 2) : 'N/A'; ?>
                            </div>

                            <div class="md:col-span-2 flex justify-end pr-2 <?php echo $blur_class; ?>">
                                <?php if ($row['status'] === 'WON'): ?>
                                    <span class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-widest shadow-[0_0_10px_rgba(16,185,129,0.15)]">
                                        ✅ WON
                                    </span>
                                <?php else: ?>
                                    <span class="bg-rose-500/10 border border-rose-500/20 text-rose-400 px-3 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-widest">
                                        ❌ LOST
                                    </span>
                                <?php endif; ?>
                            </div>

                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </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');
        }

        // ==========================================
        // Chart.js Setup for Real Analysis Graph
        // ==========================================
        <?php if ($total_tips > 0): ?>
        document.addEventListener("DOMContentLoaded", function() {
            const ctx = document.getElementById('performanceChart').getContext('2d');
            
            let gradient = ctx.createLinearGradient(0, 0, 0, 300);
            gradient.addColorStop(0, 'rgba(16, 185, 129, 0.4)'); 
            gradient.addColorStop(1, 'rgba(16, 185, 129, 0.0)'); 

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: <?php echo json_encode($chart_labels); ?>,
                    datasets: [{
                        label: 'System Effectiveness (%)',
                        data: <?php echo json_encode($chart_data_points); ?>,
                        borderColor: '#10b981', 
                        backgroundColor: gradient,
                        borderWidth: 2.5,
                        fill: true,
                        tension: 0.4, 
                        pointBackgroundColor: '#020617',
                        pointBorderColor: '#34d399',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#0f172a',
                            titleColor: '#94a3b8',
                            bodyColor: '#fff',
                            bodyFont: { weight: 'bold' },
                            borderColor: '#1e293b',
                            borderWidth: 1,
                            padding: 10,
                            displayColors: false,
                            callbacks: {
                                label: function(context) {
                                    return 'Effectiveness: ' + context.parsed.y + '%';
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: {
                                color: 'rgba(51, 65, 85, 0.3)', 
                                drawBorder: false
                            },
                            ticks: {
                                color: '#64748b',
                                font: { size: 10, family: 'monospace' },
                                stepSize: 25,
                                callback: function(value) { return value + '%'; }
                            }
                        },
                        x: {
                            grid: { display: false, drawBorder: false },
                            ticks: {
                                color: '#64748b',
                                font: { size: 9, weight: 'bold' },
                                maxTicksLimit: 8
                            }
                        }
                    }
                }
            });
        });
        <?php endif; ?>

        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.15)"; ctx.fill();
                }
                requestAnimationFrame(animateCanvas);
            }
            window.addEventListener("resize", initCanvas);
            initCanvas(); animateCanvas();
        }
    </script>
</body>
</html>