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

// 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'; // Uncomment if ads are active

$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'];
}

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

$is_vip = (isset($_SESSION['user_tier']) && $_SESSION['user_tier'] === 'VIP');

// ---------------------------------------------------------
// AI SLIP GENERATION LOGIC (Database Integrated)
// ---------------------------------------------------------
$generated_slip = [];
$total_odds = 1.00; // Base multiplier
$slip_generated = false;

// If user is VIP and they clicked "Generate AI Slip"
if ($is_vip && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $slip_generated = true;
    
    // Determine risk multiplier to adjust the amount of games pulled
    $risk_level = isset($_POST['risk']) ? (int)$_POST['risk'] : 2;
    $limit = ($risk_level === 1) ? 2 : (($risk_level === 3) ? 5 : 3); 

    try {
        // Dynamically pull pending matches using the new Hybrid schema
        $stmt = $pdo->prepare("
            SELECT 
                p.prediction_pick, 
                p.odds, 
                f.match_date,
                th.name AS home_team, 
                ta.name AS away_team
            FROM predictions p
            JOIN fixtures f ON p.fixture_id = f.id
            JOIN teams th ON f.home_team_id = th.id
            JOIN teams ta ON f.away_team_id = ta.id
            WHERE p.status = 'PENDING'
            ORDER BY RAND() 
            LIMIT :limit
        ");
        
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        $generated_slip = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Calculate exact total odds
        if (count($generated_slip) > 0) {
            foreach ($generated_slip as $item) {
                $total_odds *= (float)$item['odds'];
            }
        } else {
            $total_odds = 0.00;
        }

    } catch (PDOException $e) {
        $error_msg = "Database 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>AI Bet Builder - <?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; }
        
        /* Custom range slider styling - emerald color */
        input[type=range]::-webkit-slider-thumb {
            -webkit-appearance: none;
            height: 20px; width: 20px;
            border-radius: 50%;
            background: #10B981;
            cursor: pointer;
            box-shadow: 0 0 10px rgba(16, 185, 129, 0.5);
        }
        input[type=range]::-moz-range-thumb {
            height: 20px; width: 20px;
            border-radius: 50%;
            background: #10B981;
            cursor: pointer;
            border: 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-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-5xl 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">
                        <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">Generative AI Engine</span>
                    </div>
                    <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">AI Bet <span class="text-emerald-400">Builder</span></h1>
                    <p class="text-xs text-slate-400 mt-2 max-w-xl">Configure your parameters and let the neural network construct a mathematically optimized accumulator.</p>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-5 gap-8 relative">
                
                <?php if (!$is_vip): ?>
                    <div class="absolute inset-0 z-20 bg-slate-950/40 backdrop-blur-[6px] rounded-3xl flex flex-col items-center justify-center p-6 border border-amber-500/20">
                        <div class="text-center max-w-md bg-slate-900/90 border border-slate-800 p-8 rounded-3xl shadow-2xl">
                            <div class="w-16 h-16 bg-gradient-to-br from-amber-400 to-orange-600 rounded-2xl flex items-center justify-center mx-auto text-3xl mb-4 shadow-[0_0_20px_rgba(245,158,11,0.3)]">👑</div>
                            <h4 class="text-white text-lg font-black uppercase tracking-widest mb-2">Pro Engine Locked</h4>
                            <p class="text-xs text-slate-400 leading-relaxed mb-6">The Generative AI Bet Builder requires massive compute resources. Upgrade to the VIP Matrix to construct unlimited custom slips.</p>
                            <a href="billing.php" class="inline-block w-full bg-gradient-to-r from-amber-500 to-orange-500 hover:opacity-90 text-slate-950 font-black px-6 py-4 rounded-xl text-[10px] uppercase tracking-[0.2em] transition shadow-lg shadow-amber-500/20">Unlock Pro Builder</a>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="lg:col-span-2 space-y-6 <?php echo !$is_vip ? 'opacity-40 select-none' : ''; ?>">
                    <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden">
                        <div class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-500 to-teal-500"></div>
                        <h3 class="text-sm font-black text-white uppercase tracking-widest mb-6">Engine Parameters</h3>

                        <form method="POST" action="" class="space-y-6">
                            
                            <div class="space-y-3">
                                <div class="flex justify-between items-center">
                                    <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Risk Appetite</label>
                                    <span class="text-emerald-400 font-bold text-xs" id="riskValue">Balanced</span>
                                </div>
                                <input type="range" name="risk" min="1" max="3" value="<?php echo isset($_POST['risk']) ? $_POST['risk'] : 2; ?>" class="w-full h-1.5 bg-slate-800 rounded-lg appearance-none cursor-pointer" oninput="updateRisk(this.value)" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                <div class="flex justify-between text-[8px] font-bold text-slate-600 uppercase tracking-widest">
                                    <span>Safe (Bankers)</span>
                                    <span>Balanced</span>
                                    <span>High Yield</span>
                                </div>
                            </div>

                            <div class="space-y-2">
                                <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Target Total Odds</label>
                                <select class="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-emerald-500 transition-colors appearance-none" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                    <option>2.00 - 3.00 (Low Variance)</option>
                                    <option selected>3.00 - 5.00 (Standard Slip)</option>
                                    <option>5.00 - 10.00 (Aggressive)</option>
                                    <option>10.00+ (Moonshot)</option>
                                </select>
                            </div>

                            <div class="space-y-2">
                                <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Preferred Markets</label>
                                <div class="grid grid-cols-2 gap-2">
                                    <label class="flex items-center space-x-2 bg-slate-950 border border-slate-800 p-3 rounded-xl cursor-pointer hover:border-emerald-500/50 transition">
                                        <input type="checkbox" checked class="rounded border-slate-700 bg-slate-900 text-emerald-500 focus:ring-emerald-500" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                        <span class="text-[10px] font-bold text-slate-300 uppercase">Match Winner</span>
                                    </label>
                                    <label class="flex items-center space-x-2 bg-slate-950 border border-slate-800 p-3 rounded-xl cursor-pointer hover:border-emerald-500/50 transition">
                                        <input type="checkbox" checked class="rounded border-slate-700 bg-slate-900 text-emerald-500 focus:ring-emerald-500" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                        <span class="text-[10px] font-bold text-slate-300 uppercase">Over/Under</span>
                                    </label>
                                    <label class="flex items-center space-x-2 bg-slate-950 border border-slate-800 p-3 rounded-xl cursor-pointer hover:border-emerald-500/50 transition">
                                        <input type="checkbox" checked class="rounded border-slate-700 bg-slate-900 text-emerald-500 focus:ring-emerald-500" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                        <span class="text-[10px] font-bold text-slate-300 uppercase">BTTS</span>
                                    </label>
                                    <label class="flex items-center space-x-2 bg-slate-950 border border-slate-800 p-3 rounded-xl cursor-pointer hover:border-emerald-500/50 transition">
                                        <input type="checkbox" class="rounded border-slate-700 bg-slate-900 text-emerald-500 focus:ring-emerald-500" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                        <span class="text-[10px] font-bold text-slate-300 uppercase">Corners</span>
                                    </label>
                                </div>
                            </div>

                            <button type="submit" class="w-full bg-gradient-to-r from-emerald-500 to-teal-600 hover:opacity-90 text-white font-black py-4 rounded-xl text-[10px] uppercase tracking-[0.2em] transition shadow-lg shadow-emerald-500/25 flex justify-center items-center" <?php echo !$is_vip ? 'disabled' : ''; ?>>
                                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path></svg>
                                Generate AI Slip
                            </button>
                        </form>
                    </div>
                </div>

                <div class="lg:col-span-3 <?php echo !$is_vip ? 'opacity-20 select-none' : ''; ?>">
                    <div class="bg-slate-900/40 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 md:p-8 shadow-2xl h-full flex flex-col">
                        <div class="flex items-center justify-between mb-6 border-b border-slate-800/60 pb-4">
                            <h3 class="text-sm font-black text-white uppercase tracking-widest flex items-center">
                                <span class="text-emerald-400 mr-2">⚡</span> Generated Slip
                            </h3>
                            <div class="text-right">
                                <span class="text-[9px] font-bold text-slate-500 uppercase tracking-widest block mb-0.5">Total AI Odds</span>
                                <span class="text-2xl font-black text-white"><?php echo number_format($total_odds, 2); ?></span>
                            </div>
                        </div>

                        <div class="space-y-3 flex-1">
                            <?php if ($slip_generated && count($generated_slip) > 0): ?>
                                <?php foreach ($generated_slip as $item): ?>
                                    <div class="bg-slate-950/50 border border-slate-800 p-4 rounded-2xl flex items-center justify-between">
                                        <div class="flex flex-col">
                                            <span class="text-[9px] font-mono text-emerald-400 font-bold mb-1"><?php echo date('H:i', strtotime($item['match_date'])); ?></span>
                                            
                                            <span class="text-sm font-bold text-white"><?php echo htmlspecialchars($item['home_team']); ?> vs <?php echo htmlspecialchars($item['away_team']); ?></span>
                                            
                                            <span class="text-[10px] text-slate-400 uppercase tracking-wider mt-1 border border-slate-700 bg-slate-900 w-max px-2 py-0.5 rounded">
                                                Pick: <span class="text-emerald-400 font-bold"><?php echo htmlspecialchars($item['prediction_pick']); ?></span>
                                            </span>
                                        </div>
                                        <div class="bg-slate-900 border border-slate-700 px-3 py-2 rounded-xl text-white font-mono font-black shadow-inner">
                                            <?php echo number_format($item['odds'], 2); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php elseif ($slip_generated && count($generated_slip) === 0): ?>
                                <div class="h-full flex flex-col items-center justify-center text-center opacity-60 mt-10">
                                    <div class="text-4xl mb-4">🤷‍♂️</div>
                                    <p class="text-sm font-bold text-slate-300">Insufficient Data Matrix</p>
                                    <p class="text-xs text-slate-500 mt-1">There are not enough pending matches in the database to generate an accumulator right now.</p>
                                </div>
                            <?php else: ?>
                                <div class="h-full flex flex-col items-center justify-center text-center opacity-40 mt-10">
                                    <div class="text-4xl mb-4">⚙️</div>
                                    <p class="text-sm font-bold text-slate-300">Awaiting Parameters</p>
                                    <p class="text-xs text-slate-500 mt-1">Adjust your settings and initialize the engine to construct a slip.</p>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="mt-6 pt-6 border-t border-slate-800/60 grid grid-cols-2 gap-4">
                            <form method="POST" action="">
                                <input type="hidden" name="risk" value="<?php echo isset($_POST['risk']) ? $_POST['risk'] : 2; ?>">
                                <button type="submit" class="w-full bg-slate-800 hover:bg-slate-700 text-white font-bold py-3 rounded-xl text-[10px] uppercase tracking-widest transition" <?php echo (!$is_vip || !$slip_generated) ? 'disabled' : ''; ?>>Regenerate</button>
                            </form>
                            <button class="bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-black py-3 rounded-xl text-[10px] uppercase tracking-widest transition" <?php echo (!$is_vip || !$slip_generated) ? 'disabled' : ''; ?>>Copy to Bookmaker</button>
                        </div>
                    </div>
                </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');
        }

        // Run on page load to set correct label if re-submitted
        document.addEventListener('DOMContentLoaded', () => {
            const riskInput = document.querySelector('input[name="risk"]');
            if (riskInput) updateRisk(riskInput.value);
        });

        function updateRisk(val) {
            const labels = { 1: 'Safe (Bankers)', 2: 'Balanced', 3: 'High Yield' };
            const colors = { 1: '#10B981', 2: '#10B981', 3: '#F43F5E' }; // emerald for safe/balanced, red for high yield
            const riskValue = document.getElementById('riskValue');
            if(riskValue) {
                riskValue.innerText = labels[val];
                riskValue.style.color = colors[val];
            }
        }

        const canvas = document.getElementById("neuralCanvas");
        if(canvas) {
            const ctx = canvas.getContext("2d");
            let width, height, 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.2)"; ctx.fill();
                }
                requestAnimationFrame(animateCanvas);
            }
            window.addEventListener("resize", initCanvas);
            initCanvas(); animateCanvas();
        }
    </script>
</body>
</html>