<?php
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE);

require 'koneksi.php';
header('Content-Type: application/json');

/* ===============================
   METHOD CHECK
=============================== */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'METHOD NOT ALLOWED'
    ]);
    exit;
}

/* ===============================
   REQUIRED PARAMS
=============================== */
$required = ['signature','user_member','game_code'];
foreach ($required as $p) {
    if (empty($_POST[$p])) {
        echo json_encode([
            'status' => 'fail',
            'msg'    => "MISSING PARAM: $p"
        ]);
        exit;
    }
}

if (empty($_POST['user_agent']) && empty($_POST['agent_name'])) {
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'MISSING PARAM: user_agent'
    ]);
    exit;
}

/* ===============================
   INPUT & SANITIZE
=============================== */
$agent_name = mysqli_real_escape_string($call, trim($_POST['user_agent'] ?? ($_POST['agent_name'] ?? '')));
$secret_key = mysqli_real_escape_string($call, trim($_POST['signature']));
$username   = mysqli_real_escape_string($call, trim($_POST['user_member']));
$game_code  = mysqli_real_escape_string($call, trim($_POST['game_code']));
$client_ip  = getClientIP();

/* ===============================
   VALIDASI AGENT
=============================== */
$data_agent = agent_find_by_name($call, $agent_name, $secret_key);

if ($data_agent === null) {
    echo json_encode(['status'=>'fail','msg'=>'INVALID AGENT']);
    exit;
}

if ($data_agent['agent_status'] !== 'active') {
    echo json_encode(['status'=>'fail','msg'=>'AGENT STATUS INACTIVE']);
    exit;
}

$agent_user_where = agent_reference_condition($call, 'agent_code', $data_agent);

$whitelist = array_filter(array_map('trim', explode(',', $data_agent['agent_IP1'])));
if (!in_array($client_ip, $whitelist, true)) {
    echo json_encode([
        'status'=>'fail',
        'msg'=>"IP $client_ip Tidak Diizinkan"
    ]);
    exit;
}

/* ===============================
   VALIDASI USER
=============================== */
$qUser = mysqli_query($call,"
    SELECT intUser, balance
    FROM tb_user
    WHERE extUser='$username'
      AND $agent_user_where
    LIMIT 1
");

if (!$qUser || mysqli_num_rows($qUser) === 0) {
    echo json_encode(['status'=>'fail','msg'=>'MEMBER NOT FOUND']);
    exit;
}

$data_user  = mysqli_fetch_assoc($qUser);
$intUser    = $data_user['intUser'];
$db_balance = (float)$data_user['balance'];

/* ===============================
   VALIDASI GAME
=============================== */
$qGame = mysqli_query($call,"
    SELECT game_name, game_provider, game_type, game_status, provider_api
    FROM tb_game
    WHERE game_code='$game_code'
    LIMIT 1
");

if (!$qGame || mysqli_num_rows($qGame) === 0) {
    echo json_encode(['status'=>'fail','msg'=>'INVALID GAME']);
    exit;
}

$data_game = mysqli_fetch_assoc($qGame);

if ((int)$data_game['game_status'] === 0) {
    echo json_encode(['status'=>'fail','msg'=>'UNDER MAINTENANCE']);
    exit;
}

/* ===============================
   PROVIDER & API SELECT
=============================== */
$provider_api = strtoupper($data_game['provider_api']);
$current_api  = ($provider_api === 'NEXUSGGR') ? 'NEXUSGGR' : 'SGX';

$providerMap = [
    'PR'=>'PRAGMATIC',
    'PG'=>'PGSOFT',
    'CQ'=>'CQ9',
    'HB'=>'HABANERO',
    'BOO'=>'BOOONGO',
    'DT'=>'DREAMTECH',
    'EP'=>'EVOPLAY',
    'FT'=>'FATPANDA',
    'TT'=>'TOPTREND',
    'PL'=>'PLAYSON',
    'RK'=>'REELKINGDOM'
];

$raw_provider    = strtoupper($data_game['game_provider']);
$mapped_provider = $providerMap[$raw_provider] ?? $raw_provider;

/* ===============================
   PROCESS
=============================== */
try {

    /* GET BALANCE PROVIDER */
    $api_balance = ($current_api === 'NEXUSGGR')
        ? (float)($GGR->userbalance($intUser)['user']['balance'] ?? 0)
        : (float)($SGX->userbalance($intUser)['data']['balance'] ?? 0);

    /* WITHDRAW PROVIDER → DB */
    if ($api_balance > 0) {

        if ($current_api === 'NEXUSGGR') {
            $wd = $GGR->withdraw($intUser, $api_balance);
            if (($wd['status'] ?? 0) != 1) {
                throw new Exception($wd['msg'] ?? 'WITHDRAW FAILED');
            }
        } else {
            $wd = $SGX->withdraw($intUser, $api_balance);
            if (($wd['status'] ?? 0) != 200) {
                throw new Exception($wd['message'] ?? 'WITHDRAW FAILED');
            }
        }

        mysqli_query($call,"UPDATE tb_user SET balance='0' WHERE intUser='$intUser'");
        $db_balance = $api_balance;
    }

    /* DEPOSIT DB → PROVIDER */
    if ($db_balance > 0) {

        if ($current_api === 'NEXUSGGR') {
            $dep = $GGR->deposit($intUser, $db_balance);
            if (($dep['status'] ?? 0) != 1) {
                throw new Exception($dep['msg'] ?? 'DEPOSIT FAILED');
            }
        } else {
            $dep = $SGX->deposit($intUser, $db_balance);
            if (($dep['status'] ?? 0) != 200) {
                throw new Exception($dep['message'] ?? 'DEPOSIT FAILED');
            }
        }
    }

    /* LAUNCH GAME */
    if ($current_api === 'NEXUSGGR') {
        $launch  = $GGR->opengame($intUser, $mapped_provider, $game_code);
        $gameUrl = $launch['launch_url'] ?? '';
        $ok      = (($launch['status'] ?? 0) == 1);
    } else {
        $launch  = $SGX->opengame($intUser, $game_code);
        $gameUrl = $launch['launch_url'] ?? '';
        $ok      = (($launch['status'] ?? 0) == 200);
    }

    if (!$ok || $gameUrl === '') {
        throw new Exception('LAUNCH FAILED');
    }

    echo json_encode([
        'status'  => 200,
        'message' => 'success',
        'data'    => [
            'gameUrl' => $gameUrl
        ]
    ]);

} catch (Exception $e) {

    if ($db_balance > 0) {
        ($current_api === 'NEXUSGGR')
            ? $GGR->withdraw($intUser, $db_balance)
            : $SGX->withdraw($intUser, $db_balance);
    }

    echo json_encode([
        'status' => 'fail',
        'msg'    => $e->getMessage()
    ]);
}
