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

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

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

$fixture_id = filter_input(INPUT_POST, 'fixture_id', FILTER_VALIDATE_INT);
$redirect_url = $_POST['redirect_url'] ?? 'pay_referees.php';

if (!$fixture_id) {
    $_SESSION['flash_error'] = 'Invalid fixture ID.';
    header('Location: ' . $redirect_url);
    exit();
}

$fixtureModel = new Fixture();
$fixture = $fixtureModel->findById($fixture_id);

if (!$fixture || !$fixture->referee_id) {
    $_SESSION['flash_error'] = 'Fixture not found or referee not assigned.';
    header('Location: ' . $redirect_url);
    exit();
}

if ($fixture->board_paid_referee) {
    $_SESSION['flash_error'] = 'Referee has already been paid by the board.';
    header('Location: ' . $redirect_url);
    exit();
}

$settingModel = new Setting();
$settings = $settingModel->getAll();
$board_fee = (float)($settings['board_referee_fee'] ?? 0);

if ($board_fee <= 0) {
    $_SESSION['flash_error'] = 'Board referee fee is set to zero.';
    header('Location: ' . $redirect_url);
    exit();
}

$walletModel = new Wallet();

// 1. Get Board Wallet (Source)
$board_wallet = $walletModel->getOrCreateWallet('board', 0);
if (!$board_wallet) {
    $_SESSION['flash_error'] = 'Board wallet not found.';
    header('Location: ' . $redirect_url);
    exit();
}

// 2. Get Referee Wallet (Destination)
$referee_wallet = $walletModel->getOrCreateWallet('user', $fixture->referee_id);
if (!$referee_wallet) {
    $_SESSION['flash_error'] = 'Referee wallet could not be created.';
    header('Location: ' . $redirect_url);
    exit();
}

// 3. Check Board Balance
$board_balance = $walletModel->getBalance($board_wallet->id);
if ($board_balance < $board_fee) {
    $_SESSION['flash_error'] = 'Insufficient funds in Board Wallet.';
    header('Location: ' . $redirect_url);
    exit();
}

// 4. Process Transfer
// Using transfer() ensures money is deducted from Board and added to Referee
$description = "Referee Fee (Board): Match #$fixture_id";
if ($walletModel->transfer($board_wallet->id, $referee_wallet->id, $board_fee, $description)) {
    // 5. Update Fixture Status
    $db = new Database();
    $db->query("UPDATE fixtures SET board_paid_referee = 1 WHERE id = :id");
    $db->bind(':id', $fixture_id);
    $db->execute();

    $_SESSION['flash_message'] = 'Referee paid successfully.';
} else {
    $_SESSION['flash_error'] = 'Payment transfer failed.';
}

header('Location: ' . $redirect_url);
exit();