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

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

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

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

if ($action === 'issue_fine') {
    $entity_type = $_POST['entity_type'];
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $reason = trim($_POST['reason']);
    
    $player_id = null;
    $club_id = null;

    if ($entity_type === 'player') {
        $player_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
        if (!$player_id) {
            header('Location: wallet_management.php?status=error&msg=Invalid User');
            exit();
        }
    } elseif ($entity_type === 'club') {
        $club_id = filter_input(INPUT_POST, 'club_id', FILTER_VALIDATE_INT);
        if (!$club_id) {
            header('Location: wallet_management.php?status=error&msg=Invalid Club');
            exit();
        }
    }

    if ($amount <= 0 || empty($reason)) {
        header('Location: wallet_management.php?status=error&msg=Invalid Data');
        exit();
    }

    $db = new Database();
    $db->query("INSERT INTO fines (entity_type, player_id, club_id, amount, reason, status, issued_date) VALUES (:type, :pid, :cid, :amount, :reason, 'unpaid', NOW())");
    $db->bind(':type', $entity_type);
    $db->bind(':pid', $player_id);
    $db->bind(':cid', $club_id);
    $db->bind(':amount', $amount);
    $db->bind(':reason', $reason);

    if ($db->execute()) {
        // Optionally notify the user/club here
        header('Location: wallet_management.php?status=success');
    } else {
        header('Location: wallet_management.php?status=error');
    }
} else {
    header('Location: wallet_management.php');
}
exit();