<?php
session_start();

// ==============================
// 1. KONEKSI & API
// ==============================
require_once __DIR__ . '/../../function/connect.php'; 
require_once __DIR__ . '/functions.php'; // sudah buat $SGX otomatis

if (!$koneksi) {
    die("Koneksi database gagal");
}

// ==============================
// 2. VALIDASI LOGIN
// ==============================
$username_session = $_SESSION['username'] ?? '';
$id_user_session  = $_SESSION['id'] ?? '';

if (!$username_session || !$id_user_session) {
    header("Location: /?page=masuk");
    exit();
}

// ==============================
// 3. AMBIL PARAMETER URL
// ==============================
$extplayer = isset($_GET['extplayer']) ? mysqli_real_escape_string($koneksi, $_GET['extplayer']) : '';
$gameCode  = isset($_GET['gameCode']) ? mysqli_real_escape_string($koneksi, $_GET['gameCode']) : '';
$provider  = isset($_GET['provider']) ? mysqli_real_escape_string($koneksi, $_GET['provider']) : '';

if (empty($extplayer) || empty($gameCode) || empty($provider)) {
    die("Parameter tidak lengkap.");
}

// ==============================
// 4. VALIDASI USER
// ==============================
$cekUser = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id = '$id_user_session' LIMIT 1");

if (!$cekUser) {
    die("Query user error: " . mysqli_error($koneksi));
}

$dataUser = mysqli_fetch_assoc($cekUser);

if (!$dataUser || $dataUser['username'] !== $extplayer) {
    die("Akses tidak valid.");
}

// ==============================
// 5. CEK / CREATE USER DI API
// ==============================
$cekAPI = $SGX->userbalance($extplayer);

if (
    !isset($cekAPI['status']) || 
    ($cekAPI['status'] != 1 && strtoupper($cekAPI['status']) != 'SUCCESS')
) {
    $SGX->create($extplayer);
}

// ==============================
// 6. SINKRON SALDO API → DB
// ==============================
$resAPI = $SGX->userbalance($extplayer);

if (
    isset($resAPI['status']) && 
    ($resAPI['status'] == 1 || strtoupper($resAPI['status']) == 'SUCCESS')
) {

    $saldo_api = (float)($resAPI['user']['balance'] ?? 0);

    $cariID = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE username = '$extplayer' LIMIT 1");
    $hasilID = mysqli_fetch_assoc($cariID);

    if ($hasilID) {
        $id_numerik = $hasilID['id'];

        $updateSaldo = mysqli_query($koneksi, "
            UPDATE tb_saldo 
            SET active = '$saldo_api' 
            WHERE id_user = '$id_numerik'
        ");

        if (mysqli_affected_rows($koneksi) == 0) {
            mysqli_query($koneksi, "
                INSERT INTO tb_saldo (id_user, active) 
                VALUES ('$id_numerik', '$saldo_api')
            ");
        }
    }
}

// ==============================
// 7. OPEN GAME
// ==============================
$launchGame = $SGX->opengame($extplayer, $gameCode, $provider);

// ==============================
// 8. HANDLE RESPONSE (FIX SEMUA FORMAT API)
// ==============================
$status = $launchGame['status'] ?? '';
$msg    = strtoupper($launchGame['msg'] ?? '');

if (
    $status == 1 || 
    strtoupper($status) == 'SUCCESS' || 
    strpos($msg, 'SUCCESS') !== false
) {

    $urlGame = $launchGame['launch_url'] ?? '';

    if (!empty($urlGame)) {
        header("Location: " . $urlGame);
        exit();
    } else {
        echo "<script>alert('Game berhasil tapi URL tidak ada'); window.location.href='/';</script>";
        exit();
    }

} else {

    // DEBUG JIKA ERROR
    echo "<pre>";
    print_r($launchGame);
    echo "</pre>";

    echo "<script>alert('Error API: " . ($launchGame['msg'] ?? 'Unknown') . "'); window.location.href='/';</script>";
    exit();
}