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

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

require_once 'koneksi.php';

/* ===============================
   METHOD CHECK
=============================== */
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']     ?? '');
$provider   = trim($_POST['provider_code'] ?? '');
$gamecode   = trim($_POST['game_code']     ?? '');

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

/* ===============================
   SANITIZE
=============================== */
$agent_name = mysqli_real_escape_string($call, $agent_name);
$secret_key = mysqli_real_escape_string($call, $secret_key);
$provider   = mysqli_real_escape_string($call, $provider);
$gamecode   = mysqli_real_escape_string($call, $gamecode);

$client_ip = getClientIP();

/* ===============================
   VALIDASI AGENT
=============================== */
$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;
}

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;
}

/* ===============================
   AGENT BALANCE (HARD CAST)
=============================== */
$agentBalance = max(0, (int)$agent['agent_balance']);

/* ===============================
   BALANCE TOO SMALL → RETURN EMPTY
=============================== */
if ($agentBalance <= 0) {
    echo json_encode([
        'status'  => 200,
        'message' => 'success',
        'data'    => ['calls' => []]
    ]);
    exit;
}

/* ===============================
   CALL GGR
=============================== */
$ggrResponse = $GGR->callList($provider, $gamecode);

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

/* ===============================
   FILTER RTP (STRICT)
=============================== */
$filteredCalls = [];

foreach ($ggrResponse['calls'] as $callData) {

    if (!isset($callData['rtp'])) {
        continue;
    }

    $rtpValue = (int)$callData['rtp'];

    if ($rtpValue <= 0) {
        continue;
    }

    if ($rtpValue > $agentBalance) {
        continue;
    }

    $filteredCalls[] = $callData;
}

usort($filteredCalls, function ($a, $b) {
    return ((int)$a['rtp']) <=> ((int)$b['rtp']);
});

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