<?php
include '../config/koneksi.php';
include '../helpers/functions.php';

if (!isLogin() || !isClient()) redirect('../auth/login.php');

if (isset($_POST['simpan'])) {
    $user_id = $_SESSION['id'];
    $nominal = (float) $_POST['nominal'];
    $bank = trim($_POST['bank_tujuan']);
    $rekening = trim($_POST['rekening_tujuan']);
    $nama = trim($_POST['nama_rekening']);

    $user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT saldo FROM users WHERE id=$user_id"));

    if ($nominal < 1000) {
        setFlash('danger', 'Nominal minimal Rp 1.000');
        redirect('dashboard.php');
    }

    if ($nominal > $user['saldo']) {
        setFlash('danger', 'Saldo tidak mencukupi');
        redirect('dashboard.php');
    }

    $stmt = mysqli_prepare($conn, "INSERT INTO withdrawals (user_id, nominal, bank_tujuan, rekening_tujuan, nama_rekening, status) VALUES (?, ?, ?, ?, ?, 'pending')");
    mysqli_stmt_bind_param($stmt, "idsss", $user_id, $nominal, $bank, $rekening, $nama);
    mysqli_stmt_execute($stmt);

    setFlash('success', 'Permintaan penarikan berhasil diajukan');
    redirect('dashboard.php');
}
?>