<?php
/**
 * GetGameUrl.php - Game Launcher (Seamless Wallet) for casinoapi.shop
 *
 * This file lives on YOUR website's server. When a player taps a game,
 * your frontend calls this file; it authenticates the player, reads the
 * wallet balance from YOUR database, calls the GamingAPI launch endpoint
 * and returns the game URL.
 *
 * SETUP:
 * 1. Fix the include paths for your own DB connection file below.
 * 2. Put your API token in API_TOKEN (Client Panel -> Settings).
 * 3. Set EXIT_URL to your lobby/home page.
 * 4. Whitelist this server's IP in Client Panel -> Settings.
 * 5. Upload this file to your server.
 */

// ============================================
// CONFIGURATION
// ============================================
define('GAME_LAUNCHER_ACCESS', true);

// Your own database connection (edit the path):
// include_once "../../conn.php";

define('API_URL',   'https://casinoapi.shop/api/public/v1/launch');
define('API_TOKEN', 'YOUR_TOKEN');                  // Client Panel -> Settings
define('EXIT_URL',  'https://yourwebsite.com/');    // where the player returns after the game
// ============================================

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

$res = ['code' => 11, 'msg' => 'Method not allowed'];

$body = json_decode(file_get_contents('php://input'), true);

// 1. CHECK PARAMETERS
if (!isset($body['gameCode'])) {
    echo json_encode(['code' => 7, 'msg' => 'Invalid Parameters']);
    exit;
}
$gameCode = preg_replace('/[^A-Za-z0-9_\-]/', '', $body['gameCode']);

// 2. AUTHENTICATE THE PLAYER (your own JWT/session check)
$bearer  = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$token   = $bearer[1] ?? '';
// $auth = json_decode(is_jwt_valid($token), true);   // <- your own auth helper
// if (($auth['status'] ?? '') !== 'Success') {
//     http_response_code(401);
//     echo json_encode(['code' => 4, 'msg' => 'Permission Denied']);
//     exit;
// }
// $user_id = $auth['payload']['id'];
$user_id = '10001'; // <- replace with the authenticated player's id

// 3. READ THE PLAYER BALANCE FROM YOUR DATABASE
// Example (adapt table/column names to your schema):
// $stmt = $conn->prepare("SELECT balance FROM wallets WHERE user_id = ?");
// $stmt->bind_param("s", $user_id);
// $stmt->execute();
// $walletBalance = (float)($stmt->get_result()->fetch_assoc()['balance'] ?? 0);
$walletBalance = 0.00; // <- replace with the real balance

// 4. CALL THE GAMINGAPI LAUNCH ENDPOINT
$payload = [
    'token'     => API_TOKEN,
    'user_id'   => (string)$user_id,
    'balance'   => $walletBalance,
    'game_uid'  => $gameCode,       // game_uid from /api/public/v1/games
    'language'  => 'en',
    'return'    => EXIT_URL,
];

$ch = curl_init(API_URL);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_TIMEOUT        => 30,
]);
$api_response = curl_exec($ch);
$curl_error   = curl_error($ch);
curl_close($ch);

// 5. HANDLE RESPONSE
if ($curl_error) {
    echo json_encode(['code' => 8, 'msg' => 'Provider Connection Error']);
    exit;
}

$r = json_decode($api_response, true);

if (($r['code'] ?? 1) === 0 && !empty($r['data']['url'])) {
    // SUCCESS - your frontend reads data.url and redirects the player
    echo json_encode([
        'code' => 0,
        'msg'  => 'Success',
        'data' => [
            'url'        => $r['data']['url'],
            'session_id' => $r['data']['session_id'] ?? null,
            'returnType' => '1',
        ],
    ]);
    exit;
}

// Low balance / disabled product / other API error: show the message
echo json_encode([
    'code' => $r['code'] ?? 8,
    'msg'  => $r['msg']  ?? 'Game Launch Failed',
]);
