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

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)) {
        // Beri sedikit jeda untuk sistem provider memproses transaksi terakhir
        sleep(1); 

        $freshNexus = json_decode($nx->info_member($player));
        $freshSgx   = json_decode($SGX->info_member($player));

        $bal_nexus = (float)($freshNexus->user->balance ?? $freshNexus->balance ?? 0);
        $bal_sgx   = (float)($freshSgx->data->balance ?? $freshSgx->balance ?? 0);
        
        // Logika: Ambil yang paling besar jika keduanya aktif
        $highest = max($bal_nexus, $bal_sgx);

        // Debug log untuk memastikan saldo benar-benar berubah
        error_log("SYNC DEBUG - User: $nama_pengguna | Nexus: $bal_nexus | SGX: $bal_sgx | Final: $highest");

        $stmt = $koneksi->prepare("UPDATE tb_user SET saldo_nexus=?, saldo_sgx=?, saldo=? WHERE username=?");
        $stmt->bind_param("ddds", $bal_nexus, $bal_sgx, $highest, $nama_pengguna);
        $stmt->execute();
        
        $_SESSION['saldo'] = $highest;
        echo json_encode(['success' => true, 'new_balance' => number_format($highest, 0, ',', '.')]);
        exit();
    }
    echo json_encode(['success' => false]);
    exit();
}

// 2. LOGIKA LAUNCH GAME
if (!isset($_SESSION['extplayer']) || !isset($_SESSION['username'])) {
    header("Location: login");
    exit();
}

// Tutup sesi agar tidak mengunci file saat proses API (menambah kecepatan)
session_write_close();

$game_code     = $_GET['game'] ?? '';
$provider_code = $_GET['provider'] ?? '';
$game_type     = $_GET['type'] ?? '';
$player        = $_SESSION['extplayer'];

if (empty($game_code) || empty($provider_code)) { header('Location: /'); exit(); }

$launch_url = null;
$game_name  = 'Loading...';
$sgx_codes  = ['CM', 'FB', 'IB', 'IM', 'S3', 'WB', 'WE'];

// Deteksi Provider
if (in_array(strtoupper($provider_code), $sgx_codes) || isset($_GET['is_sgx'])) {
    $res = json_decode($SGX->launch_game($player, $game_code), true);
    $launch_url = $res['data']['gameUrl'] ?? ($res['launch_url'] ?? null);
} else {
    $res = json_decode($nx->launch_game($player, $provider_code, $game_code), true);
    $launch_url = $res['data']['gameUrl'] ?? ($res['launch_url'] ?? null);
}

if (!$launch_url) {
    die("<script>alert('Provider sedang Maintenance!'); window.history.back();</script>");
}

// Catat ke log/DB (dilakukan di latar belakang/setelah launch)
// PENTING: Jangan lakukan pengecekan saldo di sini agar loading instan!
?>
<!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>Game Active</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #000; }
        #btn-exit-game { position: fixed; top: 10px; left: 10px; z-index: 9999; background: #e74c3c; color: #fff; padding: 8px 15px; border-radius: 20px; border: none; cursor: pointer; }
        #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:9998; color:#fff; }
        iframe { width: 100%; height: 100%; border: none; }
    </style>
</head>
<body>
    <button id="btn-exit-game" onclick="triggerExitAndSync()">✕ KELUAR</button>
    <div id="loading-overlay">
        <div style="margin-bottom:10px;">MEMUAT PERMAINAN...</div>
    </div>

    <iframe id="game-frame" src="<?php echo htmlspecialchars($launch_url); ?>" onload="document.getElementById('loading-overlay').style.display='none'"></iframe>

    <script>
        function triggerExitAndSync() {
            var btn = document.getElementById('btn-exit-game');
            btn.disabled = true;
            btn.innerText = "MENYINKRONKAN...";
            $.ajax({
                url: window.location.pathname + '?action=sync_balance_exit',
                type: 'GET',
                success: function() { window.location.replace('/'); }
            });
        }
    </script>
</body>
</html>