<?php
// Admin Engine: Specialized AI Autonomous Compute
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

$success_msg = '';
$error_msg = '';
$processing_logs = [];

// =========================================================
// THE SPECIALIZED AI COMPUTE ENGINE (WITH ADJUSTABLE PARAMS)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_neural_engine'])) {
    
    // Admin Model Parameters
    $min_confidence   = (int)($_POST['min_confidence'] ?? 60);
    $favorite_weight  = (float)($_POST['favorite_weight'] ?? 1.05);
    $underdog_penalty = (float)($_POST['underdog_penalty'] ?? 0.95);
    
    try {
        // Fetch fixtures that haven't been computed yet (or re-run them)
        $stmt = $pdo->query("SELECT id, home_odds, draw_odds, away_odds, home_team_id, away_team_id FROM fixtures WHERE match_date >= CURDATE() AND (ai_pick IS NULL OR ai_pick = '')");
        $unprocessed = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $processed_count = 0;
        $update_stmt = $pdo->prepare("UPDATE fixtures SET ai_pick = ?, ai_confidence = ? WHERE id = ?");

        foreach ($unprocessed as $match) {
            $h_odds = (float)($match['home_odds'] ?? 0);
            $d_odds = (float)($match['draw_odds'] ?? 0);
            $a_odds = (float)($match['away_odds'] ?? 0);
            
            if ($h_odds <= 0 || $d_odds <= 0 || $a_odds <= 0) continue;

            // Step 1: Base Implied Probability
            $prob_home = 1 / $h_odds;
            $prob_draw = 1 / $d_odds;
            $prob_away = 1 / $a_odds;

            // Step 2: Apply Admin Weights
            $margin = $prob_home + $prob_draw + $prob_away;
            $true_home = (($prob_home / $margin) * 100);
            $true_draw = (($prob_draw / $margin) * 100);
            $true_away = (($prob_away / $margin) * 100);

            // Boost or penalize based on favorite status
            if ($true_home > $true_away) {
                $true_home *= $favorite_weight;
                $true_away *= $underdog_penalty;
            } else {
                $true_away *= $favorite_weight;
                $true_home *= $underdog_penalty;
            }

            // Step 3: Neural Decision Tree
            $ai_pick = '';
            $confidence = 0;

            if ($true_home > $true_away && $true_home > $true_draw) {
                if ($true_home >= 55) {
                    $ai_pick = '1';
                    $confidence = min(99, round($true_home + 15)); 
                } else {
                    $ai_pick = '1X';
                    $confidence = min(85, round($true_home + $true_draw));
                }
            } elseif ($true_away > $true_home && $true_away > $true_draw) {
                if ($true_away >= 55) {
                    $ai_pick = '2';
                    $confidence = min(99, round($true_away + 15));
                } else {
                    $ai_pick = 'X2'; 
                    $confidence = min(85, round($true_away + $true_draw));
                }
            } else {
                $ai_pick = 'X';
                $confidence = 50; 
            }

            // Step 4: Strict Confidence Gatekeeper
            if ($confidence >= $min_confidence) {
                $update_stmt->execute([$ai_pick, $confidence, $match['id']]);
                $processed_count++;
                
                if ($processed_count <= 5) {
                    $processing_logs[] = "Processed Fixture #{$match['id']} -> Pick: {$ai_pick} (Conf: {$confidence}%)";
                }
            }
        }
        
        if ($processed_count > 0) {
            $success_msg = "Model Execution Complete. Generated {$processed_count} highly-confident predictions.";
        } else {
            $error_msg = "Compute finished. Zero matches met your strict confidence threshold of {$min_confidence}%.";
        }

    } catch (PDOException $e) {
        $error_msg = "Engine Failure: " . $e->getMessage();
    }
}

// Fetch System Stats
try {
    $total_matrix = $pdo->query("SELECT COUNT(*) FROM fixtures WHERE match_date >= CURDATE()")->fetchColumn();
    $ai_processed = $pdo->query("SELECT COUNT(*) FROM fixtures WHERE ai_pick IS NOT NULL AND match_date >= CURDATE()")->fetchColumn();
    
    // Fetch latest AI outputs
    $stmt = $pdo->query("
        SELECT f.id, f.match_date, f.ai_pick, f.ai_confidence, ht.name AS home, at.name AS away 
        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.ai_pick IS NOT NULL 
        ORDER BY f.id DESC LIMIT 10
    ");
    $latest_ai = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $total_matrix = 0; $ai_processed = 0; $latest_ai = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Specialized AI Engine</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .terminal-bg {
            background: #0a0a0f;
            border-color: #1a1a2e;
        }
        .terminal-text {
            color: #a5f3fc;
        }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <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-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                    <span>System Online</span>
                </div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">AI Algorithm Tuning</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Configure neural weights and process raw API data into autonomous predictions.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Unprocessed API Matrix</span>
                <span class="block text-3xl font-black text-slate-900 dark:text-white mt-1"><?php echo max(0, $total_matrix - $ai_processed); ?> <span class="text-sm font-normal text-slate-500">matches</span></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">AI Processed & Deployed</span>
                <span class="block text-3xl font-black text-emerald-600 dark:text-emerald-500 mt-1"><?php echo $ai_processed; ?> <span class="text-sm font-normal text-slate-500">picks</span></span>
            </div>
        </div>

        <!-- ========== MAIN CONTENT ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- MODEL PARAMETERS CARD -->
            <div class="lg:col-span-1">
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm transition-colors duration-300 sticky top-6">
                    <h3 class="font-bold text-sm text-slate-900 dark:text-white uppercase tracking-widest border-b border-slate-200 dark:border-slate-800 pb-3 mb-5">⚙️ Model Parameters</h3>
                    
                    <form action="" method="POST" class="space-y-5">
                        <div>
                            <div class="flex justify-between items-center mb-1.5">
                                <label class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase font-bold tracking-wider">Min. Confidence Gate</label>
                                <span class="text-xs font-mono text-cyan-500 font-bold" id="confDisplay">65%</span>
                            </div>
                            <input type="range" name="min_confidence" id="confSlider" min="50" max="95" value="65" class="w-full h-1.5 bg-slate-200 dark:bg-slate-700 rounded-lg appearance-none cursor-pointer accent-cyan-500">
                            <p class="text-[9px] text-slate-400 dark:text-gray-500 mt-2 leading-relaxed">If the AI calculates a win probability lower than this threshold, it will discard the match.</p>
                        </div>

                        <div>
                            <label class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase font-bold tracking-wider mb-1.5">Favorite Bias Weight</label>
                            <select name="favorite_weight" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 text-sm transition-all">
                                <option value="1.00">1.00 (Neutral - Raw Odds)</option>
                                <option value="1.05" selected>1.05 (Slight Boost to Favorites)</option>
                                <option value="1.15">1.15 (Heavy Bias to Favorites)</option>
                            </select>
                        </div>

                        <div class="pt-3 border-t border-slate-200 dark:border-slate-800">
                            <button type="submit" name="run_neural_engine" class="w-full bg-gradient-to-r from-cyan-600 to-blue-600 hover:from-cyan-500 hover:to-blue-500 text-white font-black py-3.5 rounded-xl transition shadow-lg shadow-cyan-900/30 text-xs tracking-widest uppercase flex items-center justify-center gap-2">
                                <span>⚡ Execute Batch Compute</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- TERMINAL & RECENT AI TABLE -->
            <div class="lg:col-span-2 space-y-6">
                
                <!-- Terminal Output -->
                <div class="terminal-bg border border-slate-700 rounded-2xl p-5 shadow-2xl relative overflow-hidden font-mono text-xs">
                    <div class="flex items-center justify-between border-b border-slate-700 pb-2 mb-3">
                        <span class="text-slate-500 uppercase tracking-widest font-bold text-[10px]">Compute Terminal Output</span>
                        <span class="flex space-x-1">
                            <span class="w-2 h-2 rounded-full bg-rose-500"></span>
                            <span class="w-2 h-2 rounded-full bg-amber-500"></span>
                            <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
                        </span>
                    </div>
                    
                    <div class="text-emerald-400 space-y-1 h-48 overflow-y-auto">
                        <?php if (!empty($processing_logs)): ?>
                            <?php foreach($processing_logs as $log): ?>
                                <p class="terminal-text text-xs">> <?php echo $log; ?></p>
                            <?php endforeach; ?>
                            <p class="text-cyan-400 text-xs">> ... [Execution completed successfully]</p>
                        <?php else: ?>
                            <p class="text-slate-500 text-xs">> Awaiting command execution...</p>
                            <p class="text-slate-500 text-xs">> Use the parameters panel and click 'Execute Batch Compute'</p>
                        <?php endif; ?>
                    </div>
                    <?php if ($ai_processed > 0): ?>
                        <div class="border-t border-slate-700 pt-2 mt-3 text-[10px] text-slate-500">
                            Last run: <?php echo date('H:i:s'); ?> • <?php echo $ai_processed; ?> total predictions deployed
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Most Recent AI Classifications -->
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                    <h3 class="font-bold text-sm text-slate-900 dark:text-white uppercase tracking-widest border-b border-slate-200 dark:border-slate-800 pb-3 mb-4">Most Recent AI Classifications</h3>
                    <div class="overflow-x-auto -mx-5 px-5">
                        <table class="w-full text-left text-xs border-collapse min-w-[500px]">
                            <thead class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800">
                                <tr>
                                    <th class="py-2 px-2 font-normal uppercase tracking-widest">Date</th>
                                    <th class="py-2 px-2 font-normal uppercase tracking-widest">Teams</th>
                                    <th class="py-2 px-2 font-normal uppercase tracking-widest text-center">Pick</th>
                                    <th class="py-2 px-2 font-normal uppercase tracking-widest text-center">Confidence</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300">
                                <?php foreach($latest_ai as $ai): ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition">
                                    <td class="py-3 px-2 text-cyan-600 dark:text-cyan-400 font-mono"><?php echo date("d M", strtotime($ai['match_date'])); ?></td>
                                    <td class="py-3 px-2 text-slate-900 dark:text-white font-medium"><?php echo htmlspecialchars($ai['home']); ?> vs <?php echo htmlspecialchars($ai['away']); ?></td>
                                    <td class="py-3 px-2 text-center text-emerald-600 dark:text-emerald-400 font-bold"><?php echo htmlspecialchars($ai['ai_pick']); ?></td>
                                    <td class="py-3 px-2 text-center">
                                        <div class="flex items-center justify-center gap-2">
                                            <span class="font-mono font-bold <?php echo $ai['ai_confidence'] >= 80 ? 'text-emerald-500' : ($ai['ai_confidence'] >= 60 ? 'text-amber-500' : 'text-rose-500'); ?>"><?php echo $ai['ai_confidence']; ?>%</span>
                                            <div class="w-16 bg-slate-200 dark:bg-slate-700 rounded-full h-1.5">
                                                <div class="h-1.5 rounded-full <?php echo $ai['ai_confidence'] >= 80 ? 'bg-emerald-500' : ($ai['ai_confidence'] >= 60 ? 'bg-amber-500' : 'bg-rose-500'); ?>" style="width: <?php echo $ai['ai_confidence']; ?>%"></div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($latest_ai)): ?>
                                    <tr><td colspan="4" class="py-6 text-center text-slate-400 dark:text-gray-500 text-xs">No predictions have been generated yet.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>

    </main>

    <script>
        // Sync the confidence slider with the display
        const slider = document.getElementById('confSlider');
        const display = document.getElementById('confDisplay');
        if (slider && display) {
            slider.addEventListener('input', function() {
                display.textContent = this.value + '%';
            });
        }
    </script>
</body>
</html>