<?php
session_start();

// ==============================
// 1. KONEKSI & API
// ==============================
require_once __DIR__ . '/../../function/connect.php'; 
require_once __DIR__ . '/functions.php';

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
// ==============================
$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($provider)) {
    die("Parameter tidak lengkap.");
}

// fallback
if (empty($gameCode)) {
    $gameCode = 0;
}

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

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

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

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

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

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

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

    $q = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE username='$extplayer'");
    $u = mysqli_fetch_assoc($q);

    if ($u) {
        mysqli_query($koneksi, "
            UPDATE tb_saldo SET active='$saldo_api' 
            WHERE id_user='{$u['id']}'
        ");

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

// ==============================
// ðŸ”¥ 7. PROVIDER MAPPING (WAJIB)
// ==============================
switch ($provider) {

    case 'M9BET':
        $provider_api = 'M9BET';
        break;

    case 'IBC':
        $provider_api = 'IBCB';
        break;

    case 'FBSPORT':
        $provider_api = 'FBSPORT';
        break;

    case 'DIGITAIN':
        $provider_api = 'DIGITAIN';
        break;

    case 'CMDSPORTSBOOK':
        $provider_api = 'CMDSPORTSBOOK';
        break;
      
    default:
        $provider_api = $provider;
}

// ==============================
// 8. DETEKSI GAME TYPE
// ==============================
$getType = mysqli_query($koneksi, "SELECT game_type FROM games WHERE game_code='$gameCode' LIMIT 1");
$typeData = mysqli_fetch_assoc($getType);

$game_type = strtolower($typeData['game_type'] ?? '');

// ==============================
// 9. OPEN GAME
// ==============================
if ($game_type == 'sportbook') {

    $launchGame = $SGX->opengame(
        $extplayer,
        0,
        $provider_api,
        'sportbook'
    );

} elseif ($game_type == 'lottery') {

    $launchGame = $SGX->opengame(
        $extplayer,
        $gameCode,
        $provider_api,
        'lottery'
    );

} elseif ($game_type == 'poker') {

    // 🃏 POKER (FIX)
    $launchGame = $SGX->opengame(
        $extplayer,
        $gameCode,
        $provider_api,
        'poker'
    );

} else {

    // 🎰 SLOT & CASINO
    $launchGame = $SGX->opengame(
        $extplayer,
        $gameCode,
        $provider_api
    );
}
// ==============================
// 10. RESPONSE
// ==============================
$status = $launchGame['status'] ?? '';
$msg    = strtoupper($launchGame['msg'] ?? '');

if ($status == 1 || $status == 'SUCCESS') {

    header("Location: " . $launchGame['launch_url']);
    exit();

} else {

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

    echo "<script>alert('ERROR: ".$msg."');history.back();</script>";
} 
if ($provider_api == 'IBC') {
    echo "DEBUG IBC RESPONSE:<br>";
    echo "<pre>";
    print_r($launchGame); 
    echo "</pre>";
    die();
} 
?>