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

// Menghapus rtrim urlweb karena tidak digunakan untuk logika API HGI langsung di sini
$currentPass = $u['password'];
$metode = $_POST['metode'];

// Membersihkan input nominal dari karakter non-angka
$nominal_input = preg_replace('/[^0-9]/', '', $_POST['nominal']);
$amounts = (float) $nominal_input;

$usersID = $_POST['userID'];
// $users berasal dari session.php yang berisi username member
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Mengambil data bank untuk catatan transaksi
$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'];

// Cek Saldo Lokal
$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');

try {
    // 1. Validasi Password
    if (!password_verify($password, $currentPass)) {
        header("Location: ../m/account/withdrawal?notif=3"); // Password Salah
        exit();
    }

    // 2. Validasi Minimal Withdraw
    if ($amounts < 50000) {
        header("Location: ../m/account/withdrawal?notif=2"); // Minimal 20rb
        exit();
    }

    // 3. Validasi Saldo Mencukupi
    if ($saldoAktif < $amounts) {
        header("Location: ../m/account/withdrawal?notif=4"); // Saldo Kurang
        exit();
    }

    include('../config/class_softgaming.php');
    $WL = new fiver();
    
    $agent_sign = 'WD_' . $kd_transaksi . '_' . time();
    $resNexus = $WL->withdraw($users, $amounts, $agent_sign);

    if (isset($resNexus['status']) && $resNexus['status'] == 1) {
        $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','$amounts', 0, '$catatan', '', '0','2','$metode','0','$usersID', 0)") 
            or die(mysqli_error($conn));

        $updateBalance = mysqli_query($conn, "UPDATE `tb_balance` 
            SET `active` = active - '$amounts', `pending` = pending + '$amounts' 
            WHERE userID = '$usersID'") 
            or die(mysqli_error($conn));

        header('Location: ../m/account/withdrawal?notif=1');
        exit();

    } else {
        $error_msg = isset($resNexus['msg']) ? $resNexus['msg'] : 'Gagal memproses penarikan ke provider.';
        throw new Exception($error_msg);
    }

} catch (Exception $e) {
    $errorMessage = urlencode($e->getMessage());
    // Mengarahkan kembali dengan pesan error kustom (notif=6)
    header("Location: ../m/account/withdrawal?notif=6&message=$errorMessage");
    exit();
}
?>