<?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;
}

/* ===============================
   INPUT
=============================== */
$agent_name = $_POST['user_agent'] ?? ($_POST['agent_name'] ?? '');
$secret_key = $_POST['signature']  ?? '';
$username   = $_POST['user_member'] ?? '';

$agent_name = mysqli_real_escape_string($call, trim($agent_name));
$secret_key = mysqli_real_escape_string($call, trim($secret_key));
$username   = mysqli_real_escape_string($call, trim($username));
$username   = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');

$client_ip = getClientIP();

if ($agent_name === '' || $secret_key === '' || $username === '') {
    echo json_encode(['status'=>'fail','msg'=>'INVALID PARAMETER'], JSON_PRETTY_PRINT);
    exit;
}

/* ===============================
   CEK 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;
}

$agent_user_where = agent_reference_condition($call, 'agent_code', $data_op);

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;
}

/* ===============================
   CEK USER
=============================== */
$qUser = mysqli_query(
    $call,
    "SELECT * FROM tb_user
     WHERE extUser = '$username'
       AND $agent_user_where
     LIMIT 1"
);

if (!$qUser || mysqli_num_rows($qUser) === 0) {
    echo json_encode(['status'=>'fail','msg'=>'MEMBER NOT FOUND'], JSON_PRETTY_PRINT);
    exit;
}

$data_user = mysqli_fetch_assoc($qUser);

$intUser    = $data_user['intUser'];
$db_balance = (float)$data_user['balance'];
$total_add  = 0;

/* ===============================
   SGX BALANCE → WITHDRAW
=============================== */
$SGX_info = $SGX->userbalance($intUser);

if (is_array($SGX_info) && (int)($SGX_info['status'] ?? 0) === 200) {
    $sgx_balance = (float)($SGX_info['data']['balance'] ?? 0);

    if ($sgx_balance > 0) {
        $wd = $SGX->resetBalance($intUser);
        if (is_array($wd) && (int)($wd['status'] ?? 0) === 200) {
            $total_add += $sgx_balance;
        }
    }
}

/* ===============================
   GGR BALANCE → WITHDRAW
=============================== */
$GGR_info = $GGR->userbalance($intUser);

if (is_array($GGR_info) && (int)($GGR_info['status'] ?? 0) === 1) {
    $ggr_balance = (float)($GGR_info['user']['balance'] ?? 0);

    if ($ggr_balance > 0) {
        $wd = $GGR->resetBalance($intUser);
        if (is_array($wd) && (int)($wd['status'] ?? 0) === 1) {
            $total_add += $ggr_balance;
        }
    }
}

/* ===============================
   UPDATE DATABASE BALANCE
=============================== */
if ($total_add > 0) {
    mysqli_begin_transaction($call);

    try {
        $qUserLock = mysqli_query(
            $call,
            "SELECT id, balance
             FROM tb_user
             WHERE extUser = '$username'
               AND $agent_user_where
             LIMIT 1
             FOR UPDATE"
        );

        if (!$qUserLock || mysqli_num_rows($qUserLock) === 0) {
            throw new Exception('MEMBER NOT FOUND');
        }

        $locked_user = mysqli_fetch_assoc($qUserLock);
        $user_id = (int)$locked_user['id'];
        $new_balance = (float)$locked_user['balance'] + $total_add;

        $updated = mysqli_query(
            $call,
            "UPDATE tb_user
             SET balance = '$new_balance'
             WHERE id = '$user_id'"
        );

        if (!$updated || mysqli_affected_rows($call) < 1) {
            throw new Exception('UPDATE BALANCE FAILED');
        }

        mysqli_commit($call);
    } catch (Exception $e) {
        mysqli_rollback($call);

        echo json_encode([
            'status' => 'fail',
            'msg'    => $e->getMessage()
        ], JSON_PRETTY_PRINT);
        exit;
    }
} else {
    $new_balance = $db_balance;
}

/* ===============================
   RESPONSE (SALDO DB ONLY)
=============================== */
echo json_encode([
    'status'  => 200,
    'message' => 'success',
    'data' => [
        'username' => $username,
        'balance'  => (int)$new_balance
    ],
], JSON_PRETTY_PRINT);
