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

// Ambil data dari POST
$metode = $_POST['metode'];
$nominal = preg_replace('/[^0-9]/', '', $_POST['nominal']);
$usersID = $_POST['userID'];

// Ambil data bank
$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'];

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

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

// Ambil data user eksternal
$cek_usernya = mysqli_query($conn, "SELECT * FROM tb_user WHERE cuid = '$usersID'");
$data_usernya = mysqli_fetch_array($cek_usernya);
$extplayer = $data_usernya['extplayer'];

// Cek minimal withdraw
if ($nominal < 50000) {
    header('location:../account/withdrawal?notif=2');
    exit();
} else {
    // Cek transaksi pending
    $cekTransaksi = mysqli_query($conn, "SELECT * FROM `tb_transaksi` WHERE jenis = 2 AND userID = '$usersID' AND status = 0") or die(mysqli_error($conn));
    if (mysqli_num_rows($cekTransaksi) > 0) {
        header('location:../account/withdrawal?notif=3');
        exit();
    } else {
        
        $kingisback->withdrawBalance($extplayer, $nominal);

        // Insert transaksi ke database
        $insert_transaksi = 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));

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