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

$currentPass = $u['password'];
$metode = $_POST['metode'];
$nominal = preg_replace('/[^0-9\-]/', '', $_POST['nominal']);
$amount_str = str_replace('.', '', $nominal);
$amounts = (float) $amount_str;


$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'];

$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');


try {
    if (password_verify($password, $currentPass)) {
        if ($nominal < 20000) {
            throw new Exception('Penarikan minimal adalah Rp 20.000,-');
        }
        if ($saldoAktif < $nominal) {
            throw new Exception('Saldo tidak mencukupi untuk melakukan penarikan');
        }
        $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));
        $updateBalance = mysqli_query($conn, "UPDATE `tb_balance` SET `active` = active - '$nominal', `pending` = pending + '$nominal' WHERE userID = '$usersID'") or die(mysqli_error($conn));
        /* TELEGRAM NOTIF WD */
$bot_token = "8613767634:AAH0L9ZS3XvupoWH34ym61dJjSFteqCOqRI";
$chat_id   = "-1003937011850";
$topic_id  = 5;

$pesan  = "💸 REQUEST WITHDRAW\n\n";
$pesan .= "👤 User : ".$u['username']."\n";
$pesan .= "💰 Nominal : Rp ".number_format($nominal,0,',','.')."\n";
$pesan .= "🏦 Bank : ".$gb['akun']."\n";
$pesan .= "💳 Rek : ".$gb['no_rek']."\n";
$pesan .= "👤 Nama : ".$gb['pemilik']."\n";
$pesan .= "🆔 KD : ".$kd_transaksi."\n";
$pesan .= "⏰ ".$created_date."\n";
$pesan .= "🔔 Status : PENDING";

$url = "https://api.telegram.org/bot".$bot_token."/sendMessage";

$data = [
    'chat_id' => $chat_id,
    'message_thread_id' => $topic_id,
    'text' => $pesan
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ]
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if(curl_errno($ch)){
    error_log(curl_error($ch));
}

curl_close($ch);
echo $response;
exit;

error_log($response);
        $deposit = $WL->transaksi($users, 'withdraw', $amounts);
        header('Location:../desktop/?notif=9'); // Notifikasi berhasil
        exit();
    } else {
        throw new Exception('Password tidak valid');
    }
} catch (Exception $e) {
    $errorMessage = urlencode($e->getMessage());
    header("Location:../m/account/withdrawal.php?notif=6&message=$errorMessage");
    exit();
}
?>
