<?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
=============================== */
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']));
$req_provider = isset($_POST['provider'])
    ? strtoupper(trim($_POST['provider']))
    : '';

$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
=============================== */
$req_to_internal = [
    'PR' => 'PRAGMATIC',
    'PG' => 'PGSOFT',
    'CQ' => 'CQ9',
    'HB' => 'HABANERO',
    'BOO' => 'BOOONGO',
    'DT' => 'DREAMTECH',
    'EP' => 'EVOPLAY',
    'FT' => 'FATPANDA',
    'TT' => 'TOPTREND',
    'PL' => 'PLAYSON',
    'RK' => 'REELKINGDOM'
];

$internal_to_resp = array_flip($req_to_internal);

/* ===============================
   QUERY GAME
=============================== */
$sql = "SELECT * FROM tb_game";

if ($req_provider !== '' && isset($req_to_internal[$req_provider])) {
    $internal = $req_to_internal[$req_provider];
    $sql .= " WHERE game_provider='$internal'";
}

$qGame = mysqli_query($call, $sql);

/* ===============================
   BUILD RESULT
=============================== */
$force_first = ['PR','PG'];
$games_force = [];
$games_other = [];
$seen_names  = [];

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

    if (in_array($row['game_name'], $seen_names, true)) {
        continue;
    }

    /* game_type mapping */
    $raw_type = strtoupper($row['game_type']);
    $game_type = ($raw_type === 'SLOT') ? 'SL' : $raw_type;

    /* provider mapping to user */
    $internal_provider = strtoupper($row['game_provider']);
    $game_provider = $internal_to_resp[$internal_provider] ?? $internal_provider;

    $game = [
        'game_code'     => $row['game_code'],
        'game_name'     => $row['game_name'],
        'game_provider' => $game_provider,
        'game_type'     => $game_type,
        'game_image'    => $row['game_image'],
        'game_status'   => (int)$row['game_status']
    ];

    if (in_array($game_provider, $force_first, true)) {
        $games_force[] = $game;
    } else {
        $games_other[] = $game;
    }

    $seen_names[] = $row['game_name'];
}

/* ===============================
   RESPONSE
=============================== */
echo json_encode([
    'status'  => 200,
    'message' => 'success',
    'data' => [
        'games' => array_merge($games_force, $games_other)
    ]
], JSON_PRETTY_PRINT);
