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

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

/* ===============================
   HELPER : REAL CLIENT IP
=============================== */
/* ===============================
   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
=============================== */
if ((empty($_POST['user_agent']) && empty($_POST['agent_name'])) || empty($_POST['signature'])) {
    echo json_encode([
        'status' => 'fail',
        'msg'    => 'INVALID PARAMETER'
    ], 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();

/* ===============================
   VALIDASI AGENT
=============================== */
$data_op = agent_find_by_name($call, $agent_name, $secret_key);

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

if ($data_op['agent_status'] === 'blocked') {
    echo json_encode(['status'=>'fail','msg'=>'AGENT STATUS INACTIVE'], JSON_PRETTY_PRINT);
    exit;
}

/* ===============================
   IP WHITELIST
=============================== */
$whitelisted_ips = array_map('trim', explode(',', $data_op['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;
}

/* ===============================
   PROVIDER MAPPING (NEXUSGGR)
=============================== */
$nexus_allow = ['PRAGMATIC','CQ9','PGSOFT','HABANERO','BOOONGO','DREAMTECH','EVOPLAY','FATPANDA','TOPTREND','PLAYSON','REELKINGDOM'];

$nexus_map = [
    'PRAGMATIC'     => 'PR',
    'PGSOFT'        => 'PG',
    'CQ9'           => 'CQ',
    'HABANERO'      => 'HB',
    'BOOONGO'        => 'BOO',
    'DREAMTECH'     => 'DT',
    'EVOPLAY'       => 'EP',
    'FATPANDA'      => 'FT',
    'TOPTREND'      => 'TT',
    'PLAYSON'       => 'PL',
    'REELKINGDOM'   => 'RK',
];

/* ===============================
   QUERY PROVIDER
=============================== */
$qProvider = mysqli_query($call, "SELECT * FROM tb_provider");

$providers = [];
$added     = [];

while ($row = mysqli_fetch_assoc($qProvider)) {

    $internal_code = strtoupper($row['provider_code']);
    $provider_api  = strtoupper($row['provider_api']);

    /* ---------- FILTER KHUSUS NEXUSGGR ---------- */
    if ($provider_api === 'NEXUSGGR') {
        if (!in_array($internal_code, $nexus_allow, true)) {
            continue; // skip provider nexus yang tidak diizinkan
        }
        $display_code = $nexus_map[$internal_code];
    } else {
        // non nexus tampil apa adanya
        $display_code = $internal_code;
    }

    /* ---------- ANTI DUPLICATE ---------- */
    if (isset($added[$display_code])) {
        continue;
    }

    /* ---------- PROVIDER TYPE MAPPING ---------- */
    $type = strtolower($row['provider_type']) === 'slot'
        ? 'SL'
        : strtoupper($row['provider_type']);

    $providers[] = [
        'provider_code'   => $display_code,
        'provider_name'   => $row['provider_name'],
        'provider_type'   => $type,
        'provider_status' => (int)$row['provider_status']
    ];

    $added[$display_code] = true;
}

/* ===============================
   RESPONSE
=============================== */
echo json_encode([
    'status'   => 'success',
    'provider' => $providers,
    'msg'      => 'SUCCESS'
], JSON_PRETTY_PRINT);
