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

mysqli_begin_transaction($conn);

try {

    // AMBIL INPUT
    $usersID = $_POST['userID'];
    $metode  = $_POST['metode'];
    $nominal = (int) preg_replace('/[^0-9]/', '', $_POST['nominal']);

    // 🔒 LOCK SALDO (ANTI RACE CONDITION)
    $cekBalance = mysqli_query($conn, "
        SELECT * FROM tb_balance 
        WHERE userID = '$usersID' 
        FOR UPDATE
    ");

    if (!$cekBalance) {
        throw new Exception("Gagal ambil saldo");
    }

    $cb = mysqli_fetch_array($cekBalance);
    $saldoAktif = (int)$cb['active'];

    // ❗ VALIDASI MIN WD
    if ($nominal < 50000) {
        throw new Exception("Minimal withdraw 50.000");
    }

    // ❗ VALIDASI SALDO
    if ($nominal > $saldoAktif) {
        throw new Exception("Saldo tidak cukup");
    }

    // ❗ CEK TRANSAKSI PENDING (FIX: tidak pakai id)
    $cekTransaksi = mysqli_query($conn, "
        SELECT 1 FROM tb_transaksi 
        WHERE userID = '$usersID' 
        AND jenis = 2 
        AND status = 0
    ");

    if (!$cekTransaksi) {
        throw new Exception("Gagal cek transaksi");
    }

    if (mysqli_num_rows($cekTransaksi) > 0) {
        throw new Exception("Masih ada withdraw pending");
    }

    // 👤 AMBIL DATA USER
    $user = mysqli_query($conn, "SELECT * FROM tb_user WHERE cuid = '$usersID'");
    if (!$user) {
        throw new Exception("User tidak ditemukan");
    }

    $u = mysqli_fetch_array($user);
    $extplayer = $u['extplayer'];

    // 🏦 AMBIL DATA BANK
    $bank = mysqli_query($conn, "SELECT * FROM tb_bank WHERE userID = '$usersID'");
    if (!$bank) {
        throw new Exception("Data bank tidak ditemukan");
    }

    $b = mysqli_fetch_array($bank);
    $catatan = $b['akun'].' '.$b['no_rek'].' a/n '.$b['pemilik'];

    // 🔢 GENERATE KODE TRANSAKSI
    $kd_transaksi = date('YmdHis') . rand(100,999);
    $created_date = date('Y-m-d H:i:s');

    // 🔥 CALL API DULU (BIAR TIDAK MINUS JIKA GAGAL)
    $res = $kingisback->withdrawBalance($extplayer, $nominal);

    if (!$res || (int)$res['status'] !== 200) {
        throw new Exception("Withdraw ke provider gagal");
    }

    // 💸 POTONG SALDO
    $updateSaldo = mysqli_query($conn, "
        UPDATE tb_balance 
        SET active = active - $nominal 
        WHERE userID = '$usersID'
    ");

    if (!$updateSaldo) {
        throw new Exception("Gagal update saldo");
    }

    // 📝 INSERT TRANSAKSI
    $insert = 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','Withdraw','$nominal','0','$catatan','','0','2','$metode','0','$usersID','0')
    ");

    if (!$insert) {
        throw new Exception("Gagal simpan transaksi");
    }

    // ✅ COMMIT
    mysqli_commit($conn);

    $_SESSION['notif'] = [
        'type' => 'success',
        'message' => 'Withdraw berhasil diajukan'
    ];

} catch (Exception $e) {

    // ❌ ROLLBACK JIKA ERROR
    mysqli_rollback($conn);

    $_SESSION['notif'] = [
        'type' => 'danger',
        'message' => $e->getMessage()
    ];
}

// 🔁 REDIRECT
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;