<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

/* =========================
   NEXUS CORE
========================= */
function nexusRequest($params)
{
    $ch = curl_init('https://api.nexusggr.com');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($params),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 15
    ]);

    $res = curl_exec($ch);

    if ($res === false) {
        return [
            'status' => 0,
            'msg' => curl_error($ch)
        ];
    }

    curl_close($ch);
    return json_decode($res, true);
}

/* =========================
   ROUTER
========================= */
$input  = json_decode(file_get_contents("php://input"), true);
$action = $_GET['action'] ?? $input['action'] ?? 'players';

$agent = [
    'agent_code'  => 'balanceqqqq',
    'agent_token' => 'ab81a405329f1f4b8bf5e3b6a5213e55'
];

/* =========================
   ACTION HANDLER
========================= */
switch ($action) {

    /* ===== PLAYERS ===== */
    case 'players':
        echo json_encode(nexusRequest([
            'method' => 'call_players',
            ...$agent
        ]));
        break;

    /* ===== CALL LIST ===== */
    case 'call_list':
        if (empty($input['provider_code']) || empty($input['game_code'])) {
            echo json_encode(['status'=>0,'msg'=>'Invalid parameter']);
            break;
        }

        echo json_encode(nexusRequest([
            'method' => 'call_list',
            ...$agent,
            'provider_code' => $input['provider_code'],
            'game_code'     => $input['game_code']
        ]));
        break;

    /* ===== CALL APPLY ===== */
    case 'call_apply':
        if (
            empty($input['user_code']) ||
            empty($input['provider_code']) ||
            empty($input['game_code']) ||
            empty($input['call_rtp'])
        ) {
            echo json_encode(['status'=>0,'msg'=>'Invalid parameter']);
            break;
        }

        echo json_encode(nexusRequest([
            'method' => 'call_apply',
            ...$agent,
            'provider_code' => $input['provider_code'],
            'game_code'     => $input['game_code'],
            'user_code'     => $input['user_code'],
            'call_rtp'      => (int)$input['call_rtp'],
            'call_type'     => 1
        ]));
        break;

    default:
        echo json_encode(['status'=>0,'msg'=>'Unknown action']);
}