<?php
include('session.php');

if (!isset($_SESSION['user'])) {
    $playUrl = $urlweb . '/login/';
    header("Location: $playUrl");
    exit();
}

$extplayer = $_SESSION['user'];
$query = "SELECT * FROM tb_user WHERE user='" . mysqli_real_escape_string($conn, $extplayer) . "' LIMIT 1";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

$provider   = isset($_GET['provider']) ? $_GET['provider'] : 'PRAGMATIC';
$gamecode   = isset($_GET['gamecode']) ? $_GET['gamecode'] : '';
$ext        = $data['extplayer'];

// 🔑 Data POST
$postArray = [
    "agent_code"   => "terate22",
    "agent_token"  => "770cf7d8671955a7b1caa8761756f6af",
    "user_code"    => $ext,
    "game_type"    => "slot",
    "provider_code"=> $provider,
    "game_code"    => $gamecode,
    "lang"         => "id"
];

$jsonData = json_encode($postArray);
$headerArray = ['Content-Type: application/json'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.88xgame.net/api/v2/game_launch');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

$res = curl_exec($ch);

if (curl_errno($ch)) {
    die("cURL Error: " . curl_error($ch));
}
curl_close($ch);

$decode = json_decode($res, true);

// ✅ Ambil launch_url, bukan gameUrl
if (isset($decode['status']) && $decode['status'] == 1 && !empty($decode['launch_url'])) {
    $gameURL = $decode['launch_url'];
    header("Location: $gameURL");
    exit();
} else {
    echo "<pre>❌ Gagal Launch Game\n";
    print_r($decode);
    echo "</pre>";
}
?>
