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

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

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

$wallet_type = isset($_POST['wallet_type']) ? htmlspecialchars($_POST['wallet_type']) : '';
$fine_ids = $_POST['fine_ids'] ?? [];
$custom_redirect = $_POST['redirect_to'] ?? null;

// Determine redirect URL based on context
$redirect_url = $custom_redirect 
    ? $custom_redirect 
    : (($wallet_type === 'club') ? 'my_club.php?tab=finances' : 'my_team.php?tab=fines');
$separator = (strpos($redirect_url, '?') !== false) ? '&' : '?';

if (empty($fine_ids) || !is_array($fine_ids)) {
    header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('No fines selected.'));
    exit();
}

$walletModel = new Wallet();
$fineModel = new Fine();
$clubManagerModel = new ClubManager();
$teamModel = new Team();
$settingModel = new Setting();

$wallet_id = null;
$context_club_id = null;

// Validate User Role and Get Wallet
if ($wallet_type === 'club') {
    if ($_SESSION['user_role'] !== 'club_manager') {
        header('Location: login.php'); exit();
    }
    $club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
    if (!$club) {
        header('Location: ' . $redirect_url . '&error=' . urlencode('Club not found.')); exit();
    }
    $wallet = $walletModel->getOrCreateWallet('club', $club->id);
    if (!$wallet) {
        header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('Club wallet not found.')); exit();
    }
    $wallet_id = $wallet->id;
    $context_club_id = $club->id;
} elseif ($wallet_type === 'team') {
    if ($_SESSION['user_role'] !== 'team_manager') {
        header('Location: login.php'); exit();
    }
    $team = $teamModel->getTeamByManagerId($_SESSION['user_id']);
    if (!$team) {
        header('Location: ' . $redirect_url . '&error=' . urlencode('Team not found.')); exit();
    }
    $wallet = $walletModel->getOrCreateWallet('team', $team->id);
    if (!$wallet) {
        header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('Team wallet not found.')); exit();
    }
    $wallet_id = $wallet->id;
    $context_club_id = $team->club_id;
} else {
    header('Location: index.php'); exit();
}

// Calculate total amount for selected unpaid fines
$total_amount = 0;
$fines_to_pay = [];

foreach ($fine_ids as $fine_id) {
    // Securely fetch fine ensuring it belongs to the context club
    $fine = $fineModel->getFineDetailsByIdAndClubId($fine_id, $context_club_id);
    if ($fine && $fine->status === 'unpaid') {
        $total_amount += $fine->amount;
        $fines_to_pay[] = $fine;
    }
}

if ($total_amount <= 0) {
    header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('Selected fines are invalid or already paid.'));
    exit();
}

// Check wallet balance
$balance = $walletModel->getBalance($wallet_id);
// Use round to avoid floating point precision errors (e.g. 49.99999 < 50.00)
if (round((float)$balance, 2) < round((float)$total_amount, 2)) {
    header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('Insufficient wallet balance.'));
    exit();
}

// Process Payment
$description = "Fine Payment (" . count($fines_to_pay) . " items)";
$ref = 'FINE-PAY-' . uniqid();

$settings = $settingModel->getAll();
$commission_percent = (float)($settings['site_commission_fine'] ?? 0);

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

// --- Manual Transaction Processing ---
// Calculate splits
$commission_amount = round(($total_amount * $commission_percent) / 100, 2);
$board_amount = $total_amount - $commission_amount;

// 1. Deduct from Payer (Club/Team) using new withdraw method
$deduction_success = $walletModel->withdraw($wallet_id, $total_amount, $description, $ref, 'fine');

if ($deduction_success) {
    // 2. Deposit to Site (Commission)
    if ($commission_amount > 0 && $siteWallet) {
        $walletModel->deposit($siteWallet->id, $commission_amount, "Commission: $description", $ref);
    }
    // 3. Deposit to Board (Net Amount)
    if ($boardWallet) {
        $walletModel->deposit($boardWallet->id, $board_amount, "Received: $description", $ref);
    }
    
    $fineModel->markAsPaid($fine_ids);
    header('Location: ' . $redirect_url . $separator . 'status=success&msg=' . urlencode('Fines paid successfully.'));
} else {
    header('Location: ' . $redirect_url . $separator . 'error=' . urlencode('Payment failed. Please try again.'));
}
exit();