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

if (!function_exists('get_active_base_url')) {
    require_once(__DIR__ . '/../config/url_helper.php');
}
$siteBase = get_active_base_url();
if ($siteBase === '' && !empty($s0['urlweb'])) {
    $siteBase = rtrim($s0['urlweb'], '/');
}

// Menghapus rtrim urlweb karena tidak digunakan untuk logika API HGI langsung di sini
$currentPass = $u['password'];
$metode = isset($_POST['metode']) ? mysqli_real_escape_string($conn, (string)$_POST['metode']) : '';

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

// Pakai user dari sesi saja (hindari manipulasi POST)
$usersID = (int) $userID;
$postedUid = isset($_POST['userID']) ? (int) $_POST['userID'] : 0;
if ($postedUid > 0 && $postedUid !== $usersID) {
    header('Location: ' . $siteBase . '/m/account/withdrawal?notif=6&message=' . urlencode('Sesi tidak valid. Muat ulang halaman lalu coba lagi.'));
    exit();
}

// $users berasal dari session.php yang berisi username member
$password = isset($_POST['password']) ? (string) $_POST['password'] : '';

// Rekening yang dipilih di form (bukan baris bank pertama sembarang)
$getBank = mysqli_query($conn, "SELECT * FROM `tb_bank` WHERE cuid = '" . $metode . "' AND userID = '" . $usersID . "' LIMIT 1") or die(mysqli_error($conn));
$gb = mysqli_fetch_array($getBank);
if (!$gb || empty($gb['cuid'])) {
    header('Location: ' . $siteBase . '/m/account/withdrawal?notif=6&message=' . urlencode('Rekening penarikan tidak valid. Daftarkan rekening di profil terlebih dahulu.'));
    exit();
}
$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: ' . $siteBase . '/m/account/withdrawal?notif=3');
        exit();
    }

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

    // 3. Validasi Saldo Mencukupi
    if ($saldoAktif < $amounts) {
        header('Location: ' . $siteBase . '/m/account/withdrawal?notif=4');
        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: ' . $siteBase . '/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());
    header('Location: ' . $siteBase . '/m/account/withdrawal?notif=6&message=' . $errorMessage);
    exit();
}
?>