<?php
// admin/browser_sync.php
session_start();
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { die("Access Denied"); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Browser-Based Auto Sync</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-900 text-gray-200 h-screen flex items-center justify-center">

    <div class="bg-gray-800 p-8 rounded-xl shadow-2xl w-full max-w-3xl border border-gray-700">
        
        <div class="text-center mb-6">
            <h1 class="text-3xl font-bold text-yellow-500 mb-2"><i class="fas fa-bolt"></i> Browser-Based Sync</h1>
            <p class="text-gray-400 text-sm">⚠️ Ensure <b>"Allow CORS"</b> extension is ON before starting.</p>
        </div>

        <div class="w-full bg-gray-700 rounded-full h-6 mb-6 relative overflow-hidden">
            <div id="progress-bar" class="bg-blue-500 h-6 rounded-full transition-all duration-300" style="width: 0%"></div>
            <span id="progress-text" class="absolute inset-0 flex items-center justify-center text-xs font-bold text-white drop-shadow">0%</span>
        </div>

        <button id="start-btn" onclick="startSync()" class="w-full bg-yellow-600 hover:bg-yellow-500 text-black font-bold py-4 rounded-lg shadow-lg text-lg transition transform active:scale-95">
            START NOW (CORS ON)
        </button>

        <div id="logs" class="mt-6 bg-black/40 p-4 rounded-lg h-64 overflow-y-auto border border-gray-600 font-mono text-xs custom-scrollbar">
            <div class="text-gray-500 text-center mt-20">Waiting to start...</div>
        </div>

    </div>

    <script>
        const providers = [
            {id: 49, name: 'JILI'}, {id: 45, name: 'PGSoft'}, {id: 53, name: 'Pragmatic Play'}, 
            {id: 58, name: 'Evolution'}, {id: 57, name: 'Spribe'}, {id: 46, name: 'SABA Sports'},
            {id: 48, name: 'UnitedGaming'}, {id: 50, name: 'JDB'}, {id: 51, name: 'TADAGaming'},
            {id: 52, name: 'CQ9'}, {id: 54, name: 'PragmaticPlay-Asia'}, {id: 55, name: 'PragmaticLive-EU'},
            {id: 60, name: 'YeeBet'}, {id: 61, name: 'FaChai'}, {id: 62, name: 'BigTimeGaming'},
            {id: 64, name: 'GameArt'}, {id: 65, name: 'Bgaming'}, {id: 66, name: 'NoLimitCity'},
            {id: 68, name: 'Netent'}, {id: 70, name: 'RelaxGaming'}, {id: 71, name: 'Skywind'},
            {id: 72, name: 'Playtech'}, {id: 73, name: 'PlaynGo'}, {id: 74, name: 'RedTiger'},
            {id: 76, name: 'Playson'}, {id: 77, name: 'Evoplay'}, {id: 78, name: 'Ezugi'},
            {id: 79, name: 'iDeal'}, {id: 80, name: 'T1'}, {id: 81, name: 'PlayAce'},
            {id: 82, name: 'Astar'}, {id: 83, name: 'LuckySport'}, {id: 84, name: 'Rich88'},
            {id: 85, name: 'TF'}, {id: 86, name: 'NextSpin'}, {id: 87, name: 'DreamGaming'},
            {id: 88, name: 'Sexy Gaming'}, {id: 89, name: 'Sagaming'}, {id: 90, name: 'Microgaming'},
            {id: 91, name: 'Habanero'}, {id: 92, name: 'YGR'}, {id: 93, name: 'KoolBet'},
            {id: 94, name: 'DpEsports'}, {id: 95, name: 'DpSports'}, {id: 96, name: '3Oaks'},
            {id: 97, name: 'Hacksaw'}, {id: 100, name: 'Turbogames'}, {id: 101, name: 'Turbo World'},
            {id: 102, name: 'OneGaming'}, {id: 103, name: '5gGaming'}, {id: 104, name: 'Mini'},
            {id: 105, name: '2J'}, {id: 106, name: 'EpicWin'}, {id: 107, name: 'Smartsoft'},
            {id: 108, name: 'Wonwon'}, {id: 109, name: 'BtGaming'}, {id: 110, name: 'Pix'},
            {id: 111, name: 'Galaxsys'}, {id: 112, name: 'InOut'}, {id: 113, name: 'V8 CARD'},
            {id: 114, name: 'WM CASINO'}, {id: 117, name: 'EazyGaming'}, {id: 118, name: 'BtiGaming'},
            {id: 119, name: 'King Midas'}, {id: 121, name: 'OnGaming'}, {id: 122, name: 'AOG'},
            {id: 123, name: 'PgsGaming'}, {id: 124, name: 'Expanse'}, {id: 125, name: 'FAST SPIN'},
            {id: 126, name: 'SBO'}
        ];

        let currentIndex = 0;
        let total = providers.length;

        function startSync() {
            document.getElementById('start-btn').disabled = true;
            document.getElementById('start-btn').innerText = "Syncing...";
            document.getElementById('logs').innerHTML = "";
            processNext();
        }

        async function processNext() {
            if (currentIndex >= total) {
                logMsg("🎉 ALL PROVIDERS DONE!", "text-green-400 font-bold border border-green-500 p-2");
                return;
            }

            let p = providers[currentIndex];
            let percent = Math.round(((currentIndex + 1) / total) * 100);
            document.getElementById('progress-bar').style.width = percent + '%';
            document.getElementById('progress-text').innerText = percent + '%';

            try {
                // 1. Browser Fetches Data (Bypasses Server Block)
                let response = await fetch(`https://igamingapis.com/provider/brands.php?brand_id=${p.id}`);
                let json = await response.json();

                if (json.games && json.games.length > 0) {
                    // 2. Browser Sends Data to Server
                    let saveRes = await fetch('save_games_ajax.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            provider_name: p.name, 
                            games: json.games 
                        })
                    });
                    let saveJson = await saveRes.json();
                    
                    if(saveJson.status) {
                        logMsg(`✅ ${p.name}: Synced ${saveJson.count} games`, "text-green-400");
                    } else {
                        logMsg(`❌ ${p.name}: DB Error - ${saveJson.msg}`, "text-red-400");
                    }
                } else {
                    logMsg(`⚠️ ${p.name}: No games found in API`, "text-yellow-500");
                }

            } catch (err) {
                console.error(err);
                logMsg(`❌ ${p.name}: Failed (Is CORS Extension ON?)`, "text-red-500 font-bold");
            }

            currentIndex++;
            setTimeout(processNext, 500);
        }

        function logMsg(msg, classes) {
            let div = document.createElement('div');
            div.className = classes + " border-b border-gray-700 py-1";
            div.innerHTML = msg;
            let logs = document.getElementById('logs');
            logs.appendChild(div);
            logs.scrollTop = logs.scrollHeight;
        }
    </script>
    <style>
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #444; border-radius: 3px; }
    </style>
</body>
</html>