<?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);

if (!$amount || $amount <= 0) {
    header('Location: my_club.php?tab=finances&error=' . urlencode('Invalid payment amount.'));
    exit();
}

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

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

// Get Settings & Wallet
// Fetch League Settings for this Club
$db = new Database();
$db->query("SELECT l.reg_fee_total FROM clubs c JOIN leagues l ON c.league_id = l.id WHERE c.id = :club_id");
$db->bind(':club_id', $club->id);
$league_settings = $db->single();

$reg_fee_total = (float)($league_settings->reg_fee_total ?? 0);
$club_wallet = $walletModel->getOrCreateWallet('club', $club->id);

// Calculate Total Paid So Far
$reg_paid = 0;
$all_club_txns = $walletModel->getTransactions($club_wallet->id, 1000); 
foreach ($all_club_txns as $txn) {
    if ($txn->type === 'registration_fee' && ($txn->status === 'success' || $txn->status === 'completed')) {
        $reg_paid += $txn->amount;
    }
}

// Validate Overpayment
$remaining = $reg_fee_total - $reg_paid;
// Allow a small buffer for float comparison, but generally prevent paying more than needed
if ($amount > ($remaining + 0.01)) {
    header('Location: my_club.php?tab=finances&error=' . urlencode('Amount exceeds remaining balance of ' . number_format($remaining, 2)));
    exit();
}

// Check Wallet Balance
if ($club_wallet->balance < $amount) {
    header('Location: my_club.php?tab=finances&error=' . urlencode('Insufficient funds in club wallet. Please top up first.'));
    exit();
}

// Process Payment
// We use 'registration_fee' as the type. The recipient is 'board' (system owner).
$settings = $settingModel->getAll();
$commission_percent = $settings['site_commission_registration'] ?? 0;

// Ensure Board/System wallet exists
$walletModel->getOrCreateWallet('board', 0);
$walletModel->getOrCreateWallet('site', 0);

if ($walletModel->distributePaymentWithCommission(
    $amount,
    'registration_fee',
    'board',
    0, // Board ID (System)
    "Registration Fee Payment",
    'REG-' . uniqid(),
    $club_wallet->id,
    $commission_percent
)) {
    header('Location: my_club.php?tab=finances&status=success&msg=' . urlencode('Registration fee payment successful.'));
} else {
    header('Location: my_club.php?tab=finances&error=' . urlencode('Transaction failed. Please try again.'));
}
exit();
?>