<?php
/* ===============================
   PRODUCTION CONFIG
=============================== */
ini_set('display_errors', '0');
error_reporting(E_ALL & ~E_NOTICE);

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

require_once 'koneksi.php';
require_once __DIR__ . '/../../web/config/call_refund.php';

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

/* ===============================
   INPUT
=============================== */
$agent_name = trim($_POST['user_agent']   ?? ($_POST['agent_name'] ?? ''));
$secret_key = trim($_POST['signature']    ?? '');
$username   = trim($_POST['user_member']  ?? '');
$provider   = trim($_POST['provider_code']?? '');
$gamecode   = trim($_POST['game_code']    ?? '');
$callrtp    = trim($_POST['call_rtp']      ?? '');
$calltype   = trim($_POST['call_type']     ?? '');

if (
    $agent_name === '' || $secret_key === '' || $username === '' ||
    $provider === '' || $gamecode === '' || $callrtp === '' || $calltype === ''
) {
    http_response_code(400);
    echo json_encode(['status'=>'fail','msg'=>'INVALID PARAMETER']);
    exit;
}

if (!ctype_digit($callrtp) || !in_array((int)$calltype, [1,2], true)) {
    http_response_code(400);
    echo json_encode(['status'=>'fail','msg'=>'INVALID CALL PARAM']);
    exit;
}

/* ===============================
   SANITIZE
=============================== */
$agent_name = mysqli_real_escape_string($call, $agent_name);
$secret_key = mysqli_real_escape_string($call, $secret_key);
$username   = mysqli_real_escape_string($call, $username);
$provider   = mysqli_real_escape_string($call, $provider);
$gamecode   = mysqli_real_escape_string($call, $gamecode);
$callrtp    = (int)$callrtp;
$calltype   = (int)$calltype;

$client_ip = getClientIP();

/* ===============================
   AGENT VALIDATION + BALANCE
=============================== */
$agent = agent_find_by_name($call, $agent_name, $secret_key);

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

$agent_row_name = mysqli_real_escape_string($call, agent_public_name($agent));
$agent_user_where = agent_reference_condition($call, 'agent_code', $agent);

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

$whitelist = array_filter(array_map('trim', explode(',', $agent['agent_IP1'])));
if (!in_array($client_ip, $whitelist, true)) {
    http_response_code(403);
    echo json_encode(['status'=>'fail','msg'=>"IP $client_ip NOT ALLOWED"]);
    exit;
}

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

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

$user     = mysqli_fetch_assoc($qUser);
$usercode = $user['intUser'];


$playerResponse = $GGR->callPlayer();

if (!isset($playerResponse['status']) || (int)$playerResponse['status'] !== 1) {
    http_response_code(502);
    echo json_encode(['status'=>'fail','msg'=>'FAILED CALL PLAYER']);
    exit;
}

$playerData = null;

foreach ($playerResponse['data'] as $row) {
    if ($row['user_code'] === $usercode && $row['provider_code'] === $provider && $row['game_code'] === $gamecode
    ) {
        $playerData = $row;
        break;
    }
}

if ($playerData === null) {
    http_response_code(404);
    echo json_encode(['status'=>'fail','msg'=>'PLAYER DATA NOT FOUND']);
    exit;
}

$bet = (int)$playerData['bet'];
$payout_percentage = $bet * ($callrtp / 100);

if ($agent['agent_balance'] < $payout_percentage) {
    http_response_code(402);
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'INSUFFICIENT BALANCE AGENT',
        'data'   => [
            'required' => $payout_percentage,
            'balance'  => (int)$agent['agent_balance']
        ]
    ]);
    exit;
}

$ggrResponse = $GGR->callApply(
    $provider,
    $gamecode,
    $usercode,
    $callrtp,
    $calltype
);

if (!isset($ggrResponse['status']) || (int)$ggrResponse['status'] !== 1) {
    http_response_code(502);
    echo json_encode([
        'status'=>'fail',
        'msg'=>$ggrResponse['msg'] ?? 'CALL APPLY FAILED'
    ]);
    exit;
}

$calledMoney = (int)($ggrResponse['called_money'] ?? 0);

/* ===============================
   DOUBLE SAFETY CHECK
=============================== */
if ($agent['agent_balance'] < $calledMoney) {
    http_response_code(402);
    echo json_encode([
        'status'=>'fail',
        'msg'=>'INSUFFICIENT AGENT BALANCE'
    ]);
    exit;
}

/* ===============================
   BALANCE TRANSACTION
=============================== */
mysqli_begin_transaction($call);

try {

    $update = mysqli_query(
        $call,
        "UPDATE tb_agent
         SET agent_balance = agent_balance - $calledMoney
         WHERE agent_name='$agent_row_name'
           AND agent_balance >= $calledMoney"
    );

    if (!$update || mysqli_affected_rows($call) !== 1) {
        throw new Exception('BALANCE UPDATE FAILED');
    }

    $ledgerRecorded = call_rtp_record_apply($call, [
        'provider_response' => $ggrResponse,
        'intUser' => $usercode,
        'extUser' => $username,
        'agent_name' => agent_public_name($agent),
        'agent_code' => $agent['agent_code'] ?? '',
        'provider_code' => $provider,
        'game_code' => $gamecode,
        'call_rtp' => $callrtp,
        'call_type' => $calltype,
        'bet_amount' => $bet,
        'called_money' => $calledMoney,
        'user_credit_amount' => 0,
        'source' => 'api',
    ]);
    if (!$ledgerRecorded) {
        throw new Exception('CALL LEDGER RECORD FAILED');
    }

    mysqli_commit($call);

} catch (Throwable $e) {
    mysqli_rollback($call);

    http_response_code(500);
    echo json_encode([
        'status'=>'fail',
        'msg'=>'BALANCE TRANSACTION FAILED'
    ]);
    exit;
}

/* ===============================
   RESPONSE
=============================== */
echo json_encode([
    'status'  => 200,
    'message' => 'success',
    'data' => [
        'called_money'      => $calledMoney
    ]
]);
