<?php
error_reporting(E_ALL);
require_once('session.php');

$usersID = $_POST['userID'];
$amounts = (int)$_POST['nominal']; // pastikan integer
$jenis   = $_POST['jenis'];

$today = date('Y-m-d');
$sql_3 = mysqli_query($conn,"SELECT * FROM `tb_transaksi` ORDER BY cuid DESC LIMIT 1") or die(mysqli_error($conn));
$s33   = mysqli_num_rows($sql_3);
if($s33 == 0){
    $unikID = 0;
} else {
    $s3     = mysqli_fetch_array($sql_3);
    $unikID = $s3['cuid'];
}
$no_invoice   = 'INV/'.date('y').'/'.date('m').'/'.date('s').$unikID;
$created_date = date('Y-m-d H:i:s');

$getBalance = mysqli_query($conn,"SELECT * FROM `tb_balance` WHERE userID = '$usersID'") or die(mysqli_error($conn));
$gb         = mysqli_fetch_array($getBalance);
$saldoAktif = $gb['active'];

// 🔹 ambil extplayer untuk API
$getUser = mysqli_query($conn,"SELECT * FROM tb_user WHERE cuid='$usersID' LIMIT 1") or die(mysqli_error($conn));
$userData = mysqli_fetch_assoc($getUser);
$ext = $userData['extplayer'];

// 🔹 API config (FINAL)
$agent_code  = "terate22";
$agent_token = "770cf7d8671955a7b1caa8761756f6af";
$headerArray = ['Content-Type: application/json'];

function call_api($url, $payload, $headerArray) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    if (curl_errno($ch)) {
        return ["status"=>0,"msg"=>"cURL Error: ".curl_error($ch)];
    }
    curl_close($ch);
    return json_decode($res, true);
}

if($u['level'] == 'superadmin'){
    if($jenis == 0){ // Top Up
        $newSaldo = $saldoAktif + $amounts;
        mysqli_query($conn,"INSERT INTO `tb_transaksi` 
            (`kd_transaksi`,`date`,`transaksi`,`total`,`saldo`,`note`,`gameid`,`providerID`,`jenis`,`metode`,`pay_from`,`userID`,`status`)
            VALUES ('$no_invoice','$created_date','Top Up Saldo','$amounts',0,'Top Up','','1','1','1','0','$usersID',1)") 
            or die(mysqli_error($conn));
        mysqli_query($conn,"UPDATE `tb_balance` SET active = $newSaldo WHERE userID = '$usersID'");
        mysqli_query($conn,"UPDATE `tb_seo` SET coin = coin - '$amounts' WHERE cuid = '1'");

        // 🔹 API Deposit
        $postArray = [
            "agent_code"  => $agent_code,
            "agent_token" => $agent_token,
            "user_code"   => $ext,
            "amount"      => $amounts
        ];
        $apiRes = call_api("https://api.88xgame.net/api/v2/user_deposit", $postArray, $headerArray);

    } elseif($jenis == 2){ // Bonus
        $newSaldo = $saldoAktif + $amounts;
        mysqli_query($conn,"INSERT INTO `tb_transaksi` 
            (`kd_transaksi`,`date`,`transaksi`,`total`,`saldo`,`note`,`gameid`,`providerID`,`jenis`,`metode`,`pay_from`,`userID`,`status`)
            VALUES ('$no_invoice','$created_date','Bonus Saldo','$amounts',0,'Bonus','','1','1','1','0','$usersID',1)") 
            or die(mysqli_error($conn));
        mysqli_query($conn,"UPDATE `tb_balance` SET active = $newSaldo WHERE userID = '$usersID'");
        mysqli_query($conn,"UPDATE `tb_seo` SET coin = coin - '$amounts' WHERE cuid = '1'");

        // 🔹 API Deposit (bonus = deposit juga)
        $postArray = [
            "agent_code"  => $agent_code,
            "agent_token" => $agent_token,
            "user_code"   => $ext,
            "amount"      => $amounts
        ];
        $apiRes = call_api("https://api.88xgame.net/api/v2/user_deposit", $postArray, $headerArray);

    } else { // Pengurangan Saldo
        $newSaldos = $saldoAktif - $amounts;
        $newSaldo  = ($newSaldos < 0) ? 0 : $newSaldos;

        mysqli_query($conn,"INSERT INTO `tb_transaksi` 
            (`kd_transaksi`,`date`,`transaksi`,`total`,`saldo`,`note`,`gameid`,`providerID`,`jenis`,`metode`,`pay_from`,`userID`,`status`)
            VALUES ('$no_invoice','$created_date','Pengurangan Saldo','$amounts',0,'Pengurangan Saldo','','1','2','0','0','$usersID',1)") 
            or die(mysqli_error($conn));
        mysqli_query($conn,"UPDATE `tb_balance` SET active = $newSaldo WHERE userID = '$usersID'");
        mysqli_query($conn,"UPDATE `tb_seo` SET coin = coin + '$amounts' WHERE cuid = '1'");

        // 🔹 API Withdraw
        $postArray = [
            "agent_code"  => $agent_code,
            "agent_token" => $agent_token,
            "user_code"   => $ext,
            "amount"      => $amounts
        ];
        $apiRes = call_api("https://api.88xgame.net/api/v2/user_withdraw", $postArray, $headerArray);
    }

    // Optional log
    // file_put_contents("log_api.txt", date('c')." - ".json_encode($apiRes)."\n", FILE_APPEND);

    header('location:../balance/?notif=1');
    exit();
}
?>
