<?php
// c:\xampp\htdocs\smart_football\admin\process_board_withdrawal.php
require_once '../core/bootstrap.php';

// --- Admin Check ---
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin'])) {
    header('Location: login.php');
    exit();
}

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

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

if (!$wallet_id || !$amount || $amount <= 0 || empty($details)) {
    $_SESSION['flash_message'] = 'Invalid input details.';
    $_SESSION['flash_type'] = 'error';
    header('Location: board_wallet.php');
    exit();
}

$walletModel = new Wallet();
$balance = $walletModel->getBalance($wallet_id);

if ($balance < $amount) {
    $_SESSION['flash_message'] = 'Insufficient wallet balance.';
    $_SESSION['flash_type'] = 'error';
    header('Location: board_wallet.php');
    exit();
}

if ($walletModel->requestWithdrawal($wallet_id, $amount, "Withdrawal Request: " . $details)) {
    // Create Withdrawal Request Record
    $db = new Database();
    $db->query("INSERT INTO withdrawal_requests (wallet_id, amount, details, status, requested_by, created_at) VALUES (:wid, :amt, :det, 'pending', :uid, NOW())");
    $db->bind(':wid', $wallet_id);
    $db->bind(':amt', $amount);
    $db->bind(':det', $details);
    $db->bind(':uid', $_SESSION['user_id']);
    $db->execute();

    $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Withdrawal request submitted for approval.'];
} else {
    error_log("Board Withdrawal Request Failed. Wallet ID: $wallet_id, Amount: $amount");
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Failed to submit request. Insufficient funds or error.'];
}

header('Location: board_wallet.php');
exit();
?>
