<?php
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

require 'koneksi.php';
header('Content-Type: application/json');

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

/* ===============================
   REQUIRED PARAMS
=============================== */
$required = ['signature'];

foreach ($required as $p) {
    if (!isset($_POST[$p]) || trim($_POST[$p]) === '') {
        echo json_encode([
            'status' => 'fail',
            'msg'    => "MISSING PARAM: $p"
        ], JSON_PRETTY_PRINT);
        exit;
    }
}

if (empty($_POST['user_agent']) && empty($_POST['agent_name'])) {
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'MISSING PARAM: user_agent'
    ], JSON_PRETTY_PRINT);
    exit;
}

/* ===============================
   INPUT
=============================== */
$agent_name = mysqli_real_escape_string($call, trim($_POST['user_agent'] ?? ($_POST['agent_name'] ?? '')));
$secret_key = mysqli_real_escape_string($call, trim($_POST['signature']));
$client_ip  = getClientIP();

/* ===============================
   CEK AGENT
=============================== */
$data_agent = agent_find_by_name($call, $agent_name, $secret_key);

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

/* ===============================
   IP WHITELIST
=============================== */
$whitelisted_ips = array_filter(
    array_map('trim', explode(',', $data_agent['agent_IP1'] ?? ''))
);

if (!in_array($client_ip, $whitelisted_ips, true)) {
    echo json_encode([
        'status' => 'fail',
        'msg'    => "IP $client_ip Tidak Diizinkan"
    ], JSON_PRETTY_PRINT);
    exit;
}

/* ===============================
   AGENT STATUS
=============================== */
if ($data_agent['agent_status'] !== 'active') {
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'AGENT STATUS INACTIVE'
    ], JSON_PRETTY_PRINT);
    exit;
}

/* ===============================
   RESPONSE
=============================== */
echo json_encode([
    'status'  => 200,
    'message' => 'success',
    'data' => [
        'balance' => $data_agent['agent_balance']
    ]
], JSON_PRETTY_PRINT);
