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

// --- Security Check ---
$allowed_roles = ['admin', 'super_admin', 'finance_manager'];
$current_role = $_SESSION['user_role'] ?? $_SESSION['admin_user_role'] ?? '';
if (!in_array($current_role, $allowed_roles)) {
    $_SESSION['flash_error'] = 'You do not have permission to perform this action.';
    header('Location: dashboard.php');
    exit();
}

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

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'mark_fine_paid':
        $fine_id = filter_input(INPUT_POST, 'fine_id', FILTER_VALIDATE_INT);
        if ($fine_id) {
            $fineModel = new Fine();
            if ($fineModel->markAsPaid([$fine_id])) {
                $_SESSION['flash_message'] = "Fine #{$fine_id} marked as paid.";
            } else {
                $_SESSION['flash_error'] = "Failed to update fine #{$fine_id}.";
            }
        }
        header('Location: manage_fines.php');
        break;

    case 'issue_fine':
        $entity_type = $_POST['entity_type'] ?? '';
        $entity_id = filter_input(INPUT_POST, 'entity_id', FILTER_VALIDATE_INT);
        $reason = trim($_POST['reason'] ?? '');
        $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);

        if ($entity_type && $entity_id && $reason && $amount > 0) {
            $fineModel = new Fine();
            $data = [
                'entity_type' => $entity_type,
                'entity_id' => $entity_id,
                'reason' => $reason,
                'amount' => $amount
            ];
            if ($fineModel->create($data)) {
                $_SESSION['flash_message'] = 'Fine issued successfully.';
            } else {
                $_SESSION['flash_error'] = 'Failed to issue fine.';
            }
        } else {
            $_SESSION['flash_error'] = 'Invalid data provided for issuing fine.';
        }
        header('Location: manage_fines.php');
        break;

    case 'mark_reg_paid':
        $club_id = filter_input(INPUT_POST, 'club_id', FILTER_VALIDATE_INT);
        if ($club_id) {
            $walletModel = new Wallet();
            $club_wallet = $walletModel->getOrCreateWallet('club', $club_id);

            // Calculate remaining amount
            $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);

            $db->query("SELECT SUM(amount) as total FROM wallet_transactions WHERE wallet_id = :wid AND type = 'registration_fee' AND (status = 'completed')");
            $db->bind(':wid', $club_wallet->id);
            $res = $db->single();
            $paid = (float)($res->total ?? 0);
            
            $remaining = $reg_fee_total - $paid;

            if ($remaining > 0) {
                // Create a manual transaction to cover the rest
                $walletModel->createTransaction(
                    $club_wallet->id,
                    'registration_fee',
                    $remaining,
                    'Manual Clearance by Admin',
                    'MANUAL-' . uniqid(),
                    'completed'
                );
            }
            $_SESSION['flash_message'] = "Club #{$club_id} registration marked as fully paid.";
        }
        header('Location: club_payments.php');
        break;

    case 'manual_topup':
        $wallet_id = filter_input(INPUT_POST, 'wallet_id', FILTER_VALIDATE_INT);
        $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
        $description = trim($_POST['description'] ?? 'Manual Top-Up by Admin');
        
        if ($wallet_id && $amount > 0) {
            $walletModel = new Wallet();
            if ($walletModel->deposit($wallet_id, $amount, $description, 'MANUAL-' . uniqid())) {
                $_SESSION['flash_message'] = "Wallet #{$wallet_id} topped up successfully.";
            } else {
                $_SESSION['flash_error'] = "Failed to top up wallet #{$wallet_id}.";
            }
        }
        header('Location: wallet_management.php');
        break;

    case 'mark_ref_fee_paid':
        $fixture_id = filter_input(INPUT_POST, 'fixture_id', FILTER_VALIDATE_INT);
        if ($fixture_id) {
            $db = new Database();
            $db->query("UPDATE fixtures SET referee_payment_status = 'paid', home_team_paid_referee = 1, away_team_paid_referee = 1 WHERE id = :id");
            $db->bind(':id', $fixture_id);
            if ($db->execute()) {
                $_SESSION['flash_message'] = "Referee fee for fixture #{$fixture_id} marked as paid.";
            } else {
                $_SESSION['flash_error'] = "Failed to update referee fee status for fixture #{$fixture_id}.";
            }
        }
        header('Location: manage_fixtures.php');
        break;

    default:
        header('Location: dashboard.php');
        break;
}
exit();