<?php
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();
}

$msg = '';
$error_msg = null;

// Handle feature flag updates to the config.php file dynamically
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_api_source'])) {
    
    // PHP 8 Fix: Checkboxes send nothing if unchecked. We must use isset() to fallback to 'manual'
    $new_source = isset($_POST['data_source_flag']) ? 'api' : 'manual'; 
    $api_key    = trim($_POST['api_key'] ?? '');
    $api_url    = trim($_POST['api_url'] ?? '');

    // Read existing config.php content
    $config_path = __DIR__ . '/../config/config.php';
    
    if (file_exists($config_path) && is_writable($config_path)) {
        $config_content = file_get_contents($config_path);

        // Refactored Regex: Safely handles both single and double quotes to prevent config corruption
        $config_content = preg_replace("/define\(\s*['\"]DATA_SOURCE['\"]\s*,\s*['\"](.*?)['\"]\s*\);/i", "define('DATA_SOURCE', '$new_source');", $config_content);
        $config_content = preg_replace("/define\(\s*['\"]FOOTBALL_API_KEY['\"]\s*,\s*['\"](.*?)['\"]\s*\);/i", "define('FOOTBALL_API_KEY', '$api_key');", $config_content);
        $config_content = preg_replace("/define\(\s*['\"]FOOTBALL_API_URL['\"]\s*,\s*['\"](.*?)['\"]\s*\);/i", "define('FOOTBALL_API_URL', '$api_url');", $config_content);

        file_put_contents($config_path, $config_content);
        
        // Force immediate reload to update flags
        header("Location: api-integration.php?updated=true");
        exit();
    } else {
        $error_msg = "Error: config.php is not writable. Check file permissions.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Dual Source 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; }
    </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-6 md:p-10 overflow-x-hidden flex flex-col gap-6">
        
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <h2 class="text-3xl font-bold text-slate-900 dark:text-white tracking-wide">API & Dual-Source Integration</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-1">Master feature flag abstraction feed system controller</p>
            </div>
            
            <div class="bg-white dark:bg-slate-900 px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-800 flex items-center justify-between md:justify-start space-x-4 w-full md:w-auto shadow-sm transition-colors duration-300">
                <span class="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider font-semibold">Active Engine:</span>
                <span class="bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-500/10 dark:border-blue-500/30 dark:text-blue-500 font-extrabold text-xs px-3 py-1 rounded-full uppercase tracking-wider">
                    <?php echo defined('DATA_SOURCE') ? DATA_SOURCE : 'UNKNOWN'; ?>
                </span>
            </div>
        </div>

        <?php if(isset($_GET['updated'])): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-600 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-500 border p-4 rounded-xl text-sm font-semibold shadow-sm">
                Data source and API sync keys updated successfully. System constants re-indexed!
            </div>
        <?php endif; ?>
        <?php if(isset($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-600 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-500 border p-4 rounded-xl text-sm font-semibold shadow-sm">
                <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-6 h-fit shadow-sm transition-colors duration-300">
                <h3 class="font-bold text-lg mb-6 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Master Architecture Feature Switch</h3>
                
                <form action="api-integration.php" method="POST" class="space-y-5">
                    
                    <div class="bg-slate-50 dark:bg-slate-950 p-4 rounded-xl border border-slate-200 dark:border-slate-800 flex items-center justify-between transition-colors duration-300">
                        <div>
                            <span class="block text-sm font-bold text-slate-900 dark:text-white tracking-wide">Data Source Mode</span>
                            <span class="text-[10px] text-slate-500 dark:text-gray-400 block mt-0.5">Toggle between manual entries or external automated feeds</span>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="text-[10px] font-extrabold uppercase tracking-wider text-slate-500 dark:text-gray-400">Manual</span>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="data_source_flag" value="api" <?php if(defined('DATA_SOURCE') && DATA_SOURCE == 'api') echo 'checked'; ?> class="sr-only peer">
                                <div class="w-11 h-6 bg-slate-300 dark:bg-slate-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-500"></div>
                            </label>
                            <span class="text-[10px] font-extrabold uppercase tracking-wider text-emerald-600 dark:text-emerald-500">API</span>
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Football API Key</label>
                        <input type="text" name="api_key" value="<?php echo defined('FOOTBALL_API_KEY') ? htmlspecialchars(FOOTBALL_API_KEY) : ''; ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors font-mono" placeholder="Enter API Key...">
                    </div>

                    <div>
                        <label class="block text-xs text-slate-500 dark:text-gray-400 mb-1 tracking-wider uppercase font-semibold">Football API Base URL Endpoint</label>
                        <input type="url" name="api_url" value="<?php echo defined('FOOTBALL_API_URL') ? htmlspecialchars(FOOTBALL_API_URL) : ''; ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-lg p-3 text-slate-900 dark:text-white focus:outline-none focus:border-emerald-500 text-sm transition-colors font-mono" placeholder="https://v3.football.api-sports.io/">
                    </div>

                    <button type="submit" name="save_api_source" class="w-full bg-emerald-500 hover:bg-emerald-600 text-white dark:text-slate-900 font-bold py-3.5 rounded-xl transition shadow-lg shadow-emerald-500/20 tracking-widest uppercase text-xs mt-2">
                        TEST SYNC & RE-INDEX ENGINE
                    </button>
                </form>
            </div>

            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-6 h-fit space-y-4 shadow-sm transition-colors duration-300">
                <h3 class="font-bold text-lg text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Automated Cron Synchronizer Logs</h3>
                
                <div class="bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-4 font-mono text-[10px] h-60 overflow-y-auto space-y-2 text-slate-600 dark:text-gray-400 shadow-inner transition-colors duration-300">
                    
                    <?php if(defined('DATA_SOURCE') && DATA_SOURCE == 'api'): ?>
                        <p class="text-blue-600 dark:text-blue-500">[<?php echo date('H:i:s'); ?>] SYSTEM: API Data Source Mode Active.</p>
                        <p class="text-emerald-600 dark:text-emerald-500">[<?php echo date('H:i:s'); ?>] SYNC: Connection initialized. Awaiting scheduled cron job to fetch fixtures...</p>
                    <?php else: ?>
                        <p class="text-amber-600 dark:text-amber-500">⚠️ DORMANT: Background API query listener standing by.</p>
                        <p class="text-emerald-600 dark:text-emerald-500">⏳ System running in Manual Database Mode. Toggle API mode to begin synchronization.</p>
                    <?php endif; ?>
                    
                </div>
            </div>

        </div>
    </main>
</body>
</html>