<?php
session_start();
require_once '../config/function.php';

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

$response = [
    'status' => 0,
    'msg' => 'Invalid request'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username      = trim($_POST['username'] ?? '');
    $provider_code = trim($_POST['provider_code'] ?? '');
    $game_code     = trim($_POST['game_code'] ?? '');
    $call_rtp      = trim($_POST['call_rtp'] ?? '');
    $call_type     = trim($_POST['call_type'] ?? '');

    if ($username === '' || $provider_code === '' || $game_code === '' || $call_rtp === '' || $call_type === '') {
        $response['msg'] = 'Missing required parameters';
        echo json_encode($response);
        exit;
    }

    $call_type = in_array($call_type, ['1','2']) ? (int)$call_type : 1;

    $call_rtp = (int)$call_rtp;

    $apiUrl = "https://api.nexusggr.com";
    $postData = [
        "method"        => "call_apply",
        "agent_code"    => $this->agentCode,
        "agent_token"   => $this->secretKey,
        "provider_code" => $provider_code,
        "game_code"     => $game_code,
        "user_code"     => $username,
        "call_rtp"      => $call_rtp,
        "call_type"     => $call_type
    ];

    // Kirim request ke API menggunakan cURL
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 15); // timeout 15 detik

    $apiResponse = curl_exec($ch);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        $response['msg'] = "cURL Error: $curlErr";
        echo json_encode($response);
        exit;
    }

    $result = json_decode($apiResponse, true);

    // Validasi response dari API
    if (!empty($result) && isset($result['status'])) {
        if ($result['status'] == 1) {
            $response['status'] = 1;
            $response['msg'] = $result['msg'] ?? 'Call applied successfully';
            $response['called_money'] = $result['called_money'] ?? 0;
        } else {
            $response['status'] = 0;
            $response['msg'] = $result['msg'] ?? 'Failed to apply call';
        }
    } else {
        $response['msg'] = 'No response from API or invalid response format';
    }

    echo json_encode($response);
    exit;
}

// Jika bukan POST
echo json_encode($response);
exit;
