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

$currentPass = $u['pass'];
$metode = $_POST['metode'];
$nominal = preg_replace('/[^0-9\-]/','',$_POST['nominal']);
$usersID = $_POST['userID'];
$password = mysqli_real_escape_string($conn,$_POST['password']);

$getBank = mysqli_query($conn,"SELECT * FROM `tb_bank` WHERE userID = '$usersID'") or die(mysqli_error($conn));
$gb = mysqli_fetch_array($getBank);

$catatan = $gb['akun'].' '.$gb['no_rek'].' a/n '.$gb['pemilik'];

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

$kode_unik = substr(str_shuffle(1234567890),0,3);
$kd_transaksi = date('Ymds').$kode_unik;
$created_date = date('Y-m-d H:i:s');

if(password_verify($password,$currentPass)){
    if($nominal < 20000){
        header('Location:../m/withdraw.php/?notif=2');
        exit();
    } elseif($saldoAktif < $nominal){
        header('Location:../m/withdraw.php/?notif=4');
        exit();
    } else {
        $cekTransaksi = mysqli_query($conn,"SELECT * FROM `tb_transaksi` WHERE jenis = 2 AND userID = '$usersID' AND status = 0") or die(mysqli_error($conn));
        $ct = mysqli_num_rows($cekTransaksi);
        if($ct > 0){
            header('Location:../m/withdraw.php/?notif=5');
            exit();
        } else {
            // Insert transaksi & memo
            mysqli_query($conn,"INSERT INTO `tb_transaksi` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) 
                                VALUES ('$kd_transaksi','$created_date','Penarikan Dana','$nominal',0,'$catatan','','0','2','$metode','0','$usersID',0)") or die(mysqli_error($conn));

            mysqli_query($conn,"INSERT INTO `tb_memo` (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) 
                                VALUES ('$kd_transaksi','$created_date','Penarikan Dana','$nominal',0,'withdraw','','0','2','$metode','0','$usersID',0)") or die(mysqli_error($conn));

            // Update saldo lokal
            mysqli_query($conn,"UPDATE `tb_balance` 
                                SET `active` = active - '$nominal', 
                                    `pending` = pending + '$nominal' 
                                WHERE userID = '$usersID'") or die(mysqli_error($conn));
            
            // ambil user extplayer
            $query = "SELECT * FROM tb_user WHERE cuid='$usersID' LIMIT 1";
            $result = mysqli_query($conn, $query);
            $data = mysqli_fetch_assoc($result);
            $ext = $data['extplayer'];

            // 🔹 API baru: user_withdraw
            $postArray = [
                "agent_code"  => "terate22",
                "agent_token" => "770cf7d8671955a7b1caa8761756f6af",
                "user_code"   => $ext,
                "amount"      => (int)$nominal   // kalau mau tarik semua saldo provider, baris ini bisa dihapus
            ];

            $jsonData = json_encode($postArray);
            $headerArray = ['Content-Type: application/json'];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://api.88xgame.net/api/v2/user_withdraw');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                die("cURL Error: " . curl_error($ch));
            }
            curl_close($ch);

            $decode = json_decode($response, true);

            if (!isset($decode['status']) || $decode['status'] != 1) {
                echo "<pre>❌ Withdraw API gagal:\n";
                print_r($decode);
                echo "</pre>";
                exit();
            }

            header('Location:../m/withdraw.php/?notif=1');
            exit();
        }
    }
} else {
    header('location:../m/withdraw.php?notif=3');
    exit();
}
?>
