<?php
require_once '../core/bootstrap.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: wallet.php');
    exit();
}

$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$details = trim($_POST['details'] ?? '');

if (!$amount || $amount <= 0 || empty($details)) {
    header('Location: wallet.php?error=' . urlencode('Invalid amount or details.'));
    exit();
}

$walletModel = new Wallet();
$userWallet = $walletModel->getOrCreateWallet('user', $_SESSION['user_id']);

if ($walletModel->requestWithdrawal($userWallet->id, $amount, "Withdrawal Request: " . $details)) {
    header('Location: wallet.php?status=success&msg=' . urlencode('Withdrawal request submitted. Funds are reserved until approval.'));
} else {
    header('Location: wallet.php?error=' . urlencode('Insufficient funds or error processing request.'));
}
exit();