<?php
session_start();
include 'db/koneksi.php';
include_once 'api/nexus.php';
include_once 'api/sgx.php';

function debug_log($msg) {
    $file = __DIR__ . "/debug_game_launch.log";
    $time = date("Y-m-d H:i:s");
    file_put_contents($file, "[$time] $msg" . PHP_EOL, FILE_APPEND);
}

// =========================================================================
// 🔹 ENDPOINT AJAX: SINKRONISASI SALDO KETIKA KELUAR GAME (TOMBOL ATAU BACK HP)
// =========================================================================
if (isset($_GET['action']) && $_GET['action'] === 'sync_balance_exit') {
    header('Content-Type: application/json');
    $player = $_SESSION['extplayer'] ?? '';
    $nama_pengguna = $_SESSION['username'] ?? '';

    if (!empty($player) && !empty($nama_pengguna)) {
        $freshNexusRaw = $nx->info_member($player);
        $freshNexus    = json_decode($freshNexusRaw);
        $freshSgxRaw   = $SGX->info_member($player);
        $freshSgx      = json_decode($freshSgxRaw);

        $fresh_bal_nexus = (float)($freshNexus->user->balance ?? $freshNexus->balance ?? 0);
        $fresh_bal_sgx   = (float)($freshSgx->data->balance ?? $freshSgx->balance ?? 0);
        $highest_bal     = max($fresh_bal_nexus, $fresh_bal_sgx);

        $highest_bal = mysqli_real_escape_string($koneksi, $highest_bal);
        mysqli_query($koneksi, "UPDATE tb_user SET saldo_nexus='$highest_bal', saldo_sgx='$highest_bal', saldo='$highest_bal' WHERE username='$nama_pengguna'");
        
        // Simpan ke session lokal agar dashboard langsung sinkron tanpa refresh
        $_SESSION['saldo'] = $highest_bal;

        echo json_encode(['success' => true, 'new_balance' => number_format($highest_bal, 0, ',', '.')]);
        exit();
    }
    echo json_encode(['success' => false]);
    exit();
}

debug_log("===== GAME LAUNCH START =====");

if (!isset($_SESSION['extplayer']) || !isset($_SESSION['username'])) {
    debug_log("SESSION NOT FOUND — redirect to login.php");
    header("Location: login");
    exit();
}

$game_code     = mysqli_real_escape_string($koneksi, $_GET['game'] ?? '');
$provider_code = mysqli_real_escape_string($koneksi, $_GET['provider'] ?? '');
$player        = $_SESSION['extplayer'];
$nama_pengguna = $_SESSION['username'];
$game_type     = mysqli_real_escape_string($koneksi, $_GET['type'] ?? '');
// --- TAMBAHAN LOGIKA STATUS GAME ---
$cek_status = mysqli_query($koneksi, "SELECT status_game FROM tb_user WHERE username = '$nama_pengguna' LIMIT 1");
$data_status = mysqli_fetch_assoc($cek_status);

if ($data_status && $data_status['status_game'] === 'NonActive') {
    debug_log("❌ AKSES DITOLAK: Status game akun $nama_pengguna adalah NonActive");
    
    echo "
    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'success', // Ikon centang hijau
                title: 'Mohon Maaf',
                text: 'Akses permainan untuk akun Anda sedang dinonaktifkan.',
                confirmButtonText: 'OK',
                confirmButtonColor: '#28a745'
            }).then((result) => {
                window.location.replace('/');
            });
        });
    </script>";
    exit();
}

debug_log("INPUT | player=$player | username=$nama_pengguna | game_code=$game_code | provider_code=$provider_code");

if (empty($game_code) || empty($provider_code)) {
    debug_log("❌ Parameter game/provider kosong");
    header('Location: /');
    exit();
}

$launch_url = null;
$game_name  = 'Unknown Game';
$game_source = 'NEXUS'; 

// =========================================================================
// 🔹 1. DETEKSI CODES SPORTSBOOK SGX (HARDCODED FILTER)
// =========================================================================
$sgx_sportsbook_codes = ['CM', 'FB', 'IB', 'IM', 'S3', 'WB', 'WE'];

if (in_array(strtoupper($provider_code), $sgx_sportsbook_codes) || in_array(strtoupper($game_code), $sgx_sportsbook_codes)) {
    $game_source = 'SGX';
    $sports_names = [
        'CM' => 'CMD SPORTSBOOK', 'FB' => 'FB SPORT', 'IB' => 'IBC',
        'IM' => 'IM SPORTBOOK', 'S3' => 'SBO SPORT', 'WB' => 'WBET',
        'WE' => 'WORLD ENTERTAINMENT SPORT'
    ];
    $game_name = $sports_names[strtoupper($provider_code)] ?? 'SGX Sportsbook';
    if (empty($game_code)) { $game_code = $provider_code; }
    debug_log("FILTER DETECTED | Target adalah Sportsbook SGX: $game_name ($provider_code)");
} else {
    // 🔹 2. JIKA BUKAN SPORTSBOOK -> CEK SUMBER GAME DI DATABASE
    $check_game = mysqli_query($koneksi, "SELECT source, game_name FROM tb_game WHERE game_code = '$game_code' AND game_provider = '$provider_code' LIMIT 1");
    if ($game_info = mysqli_fetch_assoc($check_game)) {
        $game_source = strtoupper($game_info['source']); 
        $game_name   = $game_info['game_name'];
        debug_log("DATABASE CHECK | Game Found! Source: $game_source | Name: $game_name");
    } else {
        if (!empty($_GET['is_sgx']) || strtoupper($provider_code) === 'PP_LIVE_PRO') { $game_source = 'SGX'; }
    }
}

// =========================================================================
// 🔹 3. EKSEKUSI LAUNCH KE API MASING-MASING PROVIDER
// =========================================================================
if ($game_source === 'SGX') {
    debug_log("Triggers SGX API Launch for Code: $game_code ...");
    $datasgx = $SGX->launch_game($player, $game_code);
    $ressgx = json_decode($datasgx, true);
    if ($ressgx && isset($ressgx['status']) && $ressgx['status'] == 200) {
        $launch_url = $ressgx['data']['gameUrl'] ?? ($ressgx['launch_url'] ?? null);
    }
} else {
    debug_log("Triggers NEXUS API Launch...");
    $datanxs = $nx->launch_game($player, $provider_code, $game_code);
    $resnxs = json_decode($datanxs, true);
    if ($resnxs && isset($resnxs['status']) && $resnxs['status'] == 1) {
        $launch_url = $resnxs['data']['gameUrl'] ?? ($resnxs['launch_url'] ?? null);
    }
}

if (!$launch_url) {
    debug_log("❌ Gagal memuat link game dari provider");
    echo "<script>alert('Game / Provider ini sedang Maintenance!'); window.history.back();</script>";
    exit();
}

// =========================================================================
// 🔹 4. SYNC BALANCE AWAL SEBELUM MASUK GAME
// =========================================================================
$freshNexusRaw = $nx->info_member($player);
$freshNexus    = json_decode($freshNexusRaw);
$freshSgxRaw   = $SGX->info_member($player);
$freshSgx      = json_decode($freshSgxRaw);
$fresh_bal_nexus = (float)($freshNexus->user->balance ?? $freshNexus->balance ?? 0);
$fresh_bal_sgx   = (float)($freshSgx->data->balance ?? $freshSgx->balance ?? 0);
$highest_bal     = max($fresh_bal_nexus, $fresh_bal_sgx);

$highest_bal = mysqli_real_escape_string($koneksi, $highest_bal);
mysqli_query($koneksi, "UPDATE tb_user SET saldo_nexus='$highest_bal', saldo_sgx='$highest_bal', saldo='$highest_bal' WHERE username='$nama_pengguna'");
$_SESSION['saldo'] = $highest_bal;

// =========================================================================
// 🔹 5. LOG RECORD PLAY KE DATABASE
// =========================================================================
$tc = md5(uniqid(rand(), true));
$cek = mysqli_query($koneksi, "SELECT id FROM tb_play WHERE player='$player' LIMIT 1");
$row = mysqli_fetch_assoc($cek);
$escaped_url  = mysqli_real_escape_string($koneksi, $launch_url);
$escaped_title = mysqli_real_escape_string($koneksi, $game_name);

if ($row) {
    mysqli_query($koneksi, "UPDATE tb_play SET provider='$provider_code', gamecode='$game_code', tc='$tc', gamestart=NOW(), url='$escaped_url', title='$escaped_title', type='$game_type' WHERE player='$player'");
} else {
    mysqli_query($koneksi, "INSERT INTO tb_play (player, provider, gamecode, tc, gamestart, url, title, type) VALUES ('$player','$provider_code','$game_code','$tc',NOW(),'$escaped_url','$escaped_title','$game_type')");
}

debug_log("IFRAME RENDER ACTIVE | Source=$game_source");
debug_log("===== GAME LAUNCH END =====");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Playing - <?php echo htmlspecialchars($game_name); ?></title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        html, body {
            margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background-color: #000; font-family: sans-serif;
        }
        #game-container {
            position: relative; width: 100%; height: 100%;
        }
        #btn-exit-game {
            position: fixed; top: 12px; left: 12px; z-index: 999999;
            background: rgba(231, 76, 60, 0.85); color: #fff; border: 1px solid #c0392b;
            padding: 8px 16px; border-radius: 30px; font-weight: bold; font-size: 13px;
            cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.5); transition: background 0.2s;
        }
        #btn-exit-game:hover { background: #c0392b; }
        iframe {
            width: 100%; height: 100%; border: none; display: block;
        }
        #loading-overlay {
            position: fixed; top:0; left:0; width:100%; height:100%; background:#111;
            display:flex; flex-direction:column; justify-content:center; align-items:center; z-index:999998; color:#fff;
        }
        .spinner {
            width: 40px; height: 40px; border: 4px solid rgba(255,255,255,0.1); border-top-color: #f39c12; border-radius: 50%; animation: spin 1s infinite linear; margin-bottom: 15px;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

    <button id="btn-exit-game" onclick="triggerExitAndSync()">✕ KELUAR GAME</button>

    <div id="loading-overlay">
        <div class="spinner"></div>
        <div style="font-size:14px; font-weight:bold; letter-spacing:1px;">MEMUAT PERMAINAN...</div>
    </div>

    <div id="game-container">
        <iframe id="game-frame" src="<?php echo $launch_url; ?>" allowfullscreen onload="hideLoading()"></iframe>
    </div>

    <script>
        function hideLoading() {
            document.getElementById('loading-overlay').style.display = 'none';
        }

        // =========================================================================
        // 🔥 SISTEM PENCEGAT TOMBOL BACK HP / BRWS NAVIGASI
        // =========================================================================
        $(document).ready(function() {
            // Memaksa browser mencatat state history baru agar tombol back tertahan 1x
            window.history.pushState({ page: "game_active" }, "", window.location.href);
            
            // Listen ketika tombol navigasi kembali di HP ditekan
            window.onpopstate = function(event) {
                // Interupsi rute keluar asli, lalu paksa jalankan sinkronisasi saldo backend
                triggerExitAndSync();
            };
        });
        // =========================================================================
        
        var isSyncing = false;
        
        function triggerExitAndSync() {
            // Kunci fungsi jika AJAX sedang berjalan agar tidak terjadi tabrakan (anti-spam klik)
            if (isSyncing) return;
            isSyncing = true;

            var btn = document.getElementById('btn-exit-game');
            if (btn) {
                btn.disabled = true;
                btn.innerText = "PROSES KELUAR DARI GAME...";
                btn.style.background = "#7f8c8d";
            }

            // Munculkan kembali overlay layar memuat untuk efek transisi halus
            document.getElementById('loading-overlay').style.display = 'flex';
            document.getElementById('loading-overlay').innerHTML = '<div class="spinner"></div><div style="font-size:14px; font-weight:bold;">MENYINGKRONKAN SALDO AKTIF...</div>';

            // Kirim request ke action internal php di atas secara background
            $.ajax({
                url: window.location.pathname + '?action=sync_balance_exit',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Jika website utama terbuka di tab asal, ganti element teks saldo-nya secara real-time
                        if (window.opener && !window.opener.closed) {
                            $(window.opener.document).find('.balance-amount, #user-balance, .saldo-user').text(response.new_balance);
                        }
                    }
                },
                complete: function() {
                    // Copat event listener agar tidak terjadi perulangan history
                    window.onpopstate = null;
                    // Alihkan penuh halaman kembali ke dashboard beranda utama
                    window.location.replace('/');
                }
            });
        }
    </script>
</body>
</html>