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

// --- Authentication Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

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

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

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

$clubManagerModel = new ClubManager();
$walletModel = new Wallet();

$club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
if (!$club) {
    header('Location: my_club.php?error=no_club');
    exit();
}

$club_wallet = $walletModel->getOrCreateWallet('club', $club->id);

if ($walletModel->requestWithdrawal($club_wallet->id, $amount, $details)) {
    header('Location: club_finances.php?status=success&msg=' . urlencode('Withdrawal request submitted.'));
} else {
    header('Location: club_finances.php?error=' . urlencode('Insufficient funds or error processing request.'));
}
exit();