<?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';

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

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

$agent_name = mysqli_real_escape_string($call, $agent_name);
$secret_key = mysqli_real_escape_string($call, $secret_key);
$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;
}

/* ===============================
   MAP USER: intUser => username
=============================== */
$userMap = [];
$agent_user_where = agent_reference_condition($call, 'agent_code', $agent);

$qUsers = mysqli_query(
    $call,
    "SELECT intUser, extUser
     FROM tb_user
     WHERE $agent_user_where"
);

while ($u = mysqli_fetch_assoc($qUsers)) {
    $userMap[$u['intUser']] = $u['extUser'];
}

if (empty($userMap)) {
    echo json_encode([
        'status'  => 200,
        'message' => 'success',
        'data'    => [],
        'note'    => 'NO USER UNDER THIS AGENT'
    ]);
    exit;
}

$ggrResponse = $GGR->callPlayer();

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

$result = [];

foreach ($ggrResponse['data'] as $row) {

    $userCode = $row['user_code'] ?? null;

    if ($userCode !== null && isset($userMap[$userCode])) {
        $result[] = [
            'user'     => $userMap[$userCode],
            'user_member'   => $userMap[$userCode],
            'provider_code' => $row['provider_code'],
            'game'     => $row['game_code'],
            'game_code'     => $row['game_code'],
            'bet'           => (int)$row['bet'],
            'balance'       => (int)$row['balance'],
            'real_rtp'      => (int)$row['real_rtp'],
            'target_rtp'    => (int)$row['target_rtp']
        ];
    }
}

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