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

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

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

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

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

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

$datanxs = $nx->launch_game($player, $provider_code, $game_code);
debug_log("NX RAW RESPONSE: " . ($datanxs ?: '[EMPTY]'));
$resnxs = json_decode($datanxs, true);

$datasgx = $SGX->launch_game($player, $game_code);
debug_log("SGX RAW RESPONSE: " . ($datasgx ?: '[EMPTY]'));
$ressgx = json_decode($datasgx, true);

$response = null;
if ($resnxs && isset($resnxs['status']) && $resnxs['status'] == 1) {
    $response = $resnxs;
    debug_log("✅ Using NX response");
} elseif ($ressgx && isset($ressgx['status']) && $ressgx['status'] == 200) {
    $response = $ressgx;
    debug_log("✅ Using SGX response");
} else {
    debug_log("❌ Both NX and SGX failed to return valid JSON");
    echo "<script>
    alert('Game ini sedang Maintenance!')
    window.history.back()
    </script>
    ";
    exit();
}

$launch_url = $response['data']['gameUrl'] ?? null;
$game_name  = $response['data']['game_name'] ?? 'Unknown Game';
if (!$launch_url) {
    $launch_url = $response['launch_url'] ?? null;
}

$tc = md5(uniqid(rand(), true));
$cek = mysqli_query($koneksi, "SELECT id FROM tb_play WHERE player='$player' LIMIT 1");
$row = mysqli_fetch_assoc($cek);

if ($row) {
    $id = $row['id'];
    $update = "UPDATE tb_play 
               SET provider='$provider_code', tc='$tc', gamestart=NOW(), 
                   url='$launch_url', title='$game_name', type='$game_type'
               WHERE player='$player'";
    $exec = mysqli_query($koneksi, $update);
    debug_log("QUERY UPDATE: $update | RESULT=" . ($exec ? "OK" : mysqli_error($koneksi)));
} else {
    $insert = "INSERT INTO tb_play (player, provider, gamecode, tc, gamestart, url, title, type)
               VALUES ('$player','$provider_code','$game_code','$tc',NOW(),'$launch_url','$game_name','$game_type')";
    $exec = mysqli_query($koneksi, $insert);
    debug_log("QUERY INSERT: $insert | RESULT=" . ($exec ? "OK" : mysqli_error($koneksi)));
}

debug_log("REDIRECT SUCCESS | player=$player | provider=$provider_code | URL=$launch_url");
debug_log("===== GAME LAUNCH END =====");

header("Location: $launch_url");
exit();
