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

// --- Authentication Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'team_manager') {
    header('Location: login.php');
    exit();
}

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

$fixture_id = filter_input(INPUT_POST, 'fixture_id', FILTER_VALIDATE_INT);
$team_id = filter_input(INPUT_POST, 'team_id', FILTER_VALIDATE_INT);
$payment_method = $_POST['payment_method'] ?? 'wallet';
$wallet_type = $_POST['wallet_type'] ?? null;

if (!$fixture_id || !$team_id) {
    error_log("Referee Payment Error: Invalid request parameters. FixtureID: " . ($fixture_id ?? 'null') . ", TeamID: " . ($team_id ?? 'null'));
    header('Location: my_team.php?error=' . urlencode('Invalid request parameters.'));
    exit();
}

$fixtureModel = new Fixture();
$teamModel = new Team();
$walletModel = new Wallet();
$settingModel = new Setting();
$userModel = new User();

// Verify Team Ownership
$team = $teamModel->getTeamByManagerId($_SESSION['user_id']);
if (!$team || $team->id != $team_id) {
    error_log("Referee Payment Error: Unauthorized action. UserID: {$_SESSION['user_id']}, TeamID: $team_id");
    header('Location: my_team.php?error=' . urlencode('Unauthorized action.'));
    exit();
}

$fixture = $fixtureModel->findById($fixture_id);
if (!$fixture) {
    error_log("Referee Payment Error: Fixture not found. FixtureID: $fixture_id");
    header('Location: my_team.php?error=' . urlencode('Fixture not found.'));
    exit();
}

if (!$fixture->referee_id) {
    error_log("Referee Payment Error: Referee not assigned. FixtureID: $fixture_id");
    header('Location: my_team.php?error=' . urlencode('Referee not assigned to this match. Cannot pay fee.'));
    exit();
}

// --- Security Check: Ensure Team is Participant ---
if ($fixture->home_team_id != $team->id && $fixture->away_team_id != $team->id) {
    error_log("Referee Payment Error: Team not participant. TeamID: $team_id, FixtureID: $fixture_id");
    header('Location: my_team.php?error=' . urlencode('Your team is not participating in this match.'));
    exit();
}

// --- Check if Already Paid ---
$is_home = ($fixture->home_team_id == $team->id);
if (($is_home && $fixture->home_team_paid_referee) || (!$is_home && $fixture->away_team_paid_referee)) {
    error_log("Referee Payment Error: Fee already paid. TeamID: $team_id, FixtureID: $fixture_id");
    header('Location: my_team.php?error=' . urlencode('Referee fee already paid.'));
    exit();
}

$settings = $settingModel->getAll();
$fee_amount = (float)($settings['referee_fee'] ?? 50);

if ($payment_method === 'wallet') {
    // Explicitly check that the payment is coming from a team wallet context.
    if ($wallet_type !== 'team') {
        error_log("Referee Payment Error: Invalid wallet type '$wallet_type'. Must be 'team'.");
        header('Location: my_team.php?error=' . urlencode('Invalid wallet type specified. Must be a team wallet.'));
        exit();
    }

    $team_wallet = $walletModel->getOrCreateWallet('team', $team->id);
    $wallet_id = $team_wallet->id;
    
    // Check balance
    $current_balance = $walletModel->getBalance($wallet_id);
    if ($current_balance < $fee_amount) {
        error_log("Referee Payment Error: Insufficient balance. WalletID: $wallet_id, Balance: $current_balance, Fee: $fee_amount");
        header('Location: my_team.php?error=' . urlencode('Insufficient wallet balance. Please top up or use online payment.'));
        exit();
    }

    // Process Payment
    $ref = 'REF-FEE-' . uniqid();
    $commission_percent = $settings['site_commission_referee'] ?? 0;

    // Ensure Board/System wallet exists for commission
    $walletModel->getOrCreateWallet('board', 0);
    $walletModel->getOrCreateWallet('site', 0);
    $walletModel->getOrCreateWallet('user', $fixture->referee_id); // Ensure Referee wallet exists

    if ($walletModel->distributePaymentWithCommission($fee_amount, 'referee_fee', 'user', $fixture->referee_id, "Referee Fee: Match #$fixture_id", $ref, $wallet_id, $commission_percent)) {
        // Update Fixture Status
        $column = ($fixture->home_team_id == $team->id) ? 'home_team_paid_referee' : 'away_team_paid_referee';
        $db = new Database();
        $db->query("UPDATE fixtures SET $column = 1 WHERE id = :id");
        $db->bind(':id', $fixture_id);
        $db->execute();

        header('Location: my_team.php?status=success&msg=' . urlencode('Referee fee paid successfully.'));
    } else {
        error_log("Referee Payment Error: distributePaymentWithCommission failed. WalletID: $wallet_id, Amount: $fee_amount");
        header('Location: my_team.php?error=' . urlencode('Payment failed. Please try again.'));
    }
} elseif ($payment_method === 'gateway') {
    // --- Prepare Flutterwave Payment ---
    $flutterwave_secret_key = $settings['flutterwave_secret_key'] ?? '';
    if (empty($flutterwave_secret_key)) {
        error_log("Referee Payment Error: Flutterwave secret key missing.");
        header('Location: my_team.php?error=' . urlencode('Payment configuration error.'));
        exit();
    }

    $tx_ref = 'REF-FEE-GW-' . uniqid();
    $currency = $settings['system_currency'] ?? 'USD';
    
    // Get user details for the payment request
    $user = $userModel->findById($_SESSION['user_id']);
    $email = $user->email ?? '';
    $name = ($user->first_name ?? '') . ' ' . ($user->last_name ?? '');

    $request = [
        'tx_ref' => $tx_ref,
        'amount' => $fee_amount,
        'currency' => $currency,
        'payment_options' => 'card,mobilemoney,ussd',
        'redirect_url' => URL_ROOT . '/app/flutterwave_verify.php?payment_context=referee_fee',
        'customer' => [
            'email' => $email,
            'name' => $name,
        ],
        'meta' => [
            'fixture_id' => $fixture_id,
            'team_id' => $team->id,
            'type' => 'referee_fee'
        ],
        'customizations' => [
            'title' => 'Referee Fee',
            'description' => "Match #$fixture_id Fee",
            'logo' => $settings['app_logo'] ?? ''
        ]
    ];

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.flutterwave.com/v3/payments',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_POSTFIELDS => json_encode($request),
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer ' . $flutterwave_secret_key,
            'Content-Type: application/json'
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        error_log("Referee Payment Error: cURL Error: $err");
        header('Location: my_team.php?error=' . urlencode('Payment initialization failed: ' . $err));
        exit();
    }

    $res = json_decode($response);
    if ($res && isset($res->status) && $res->status == 'success') {
        header('Location: ' . $res->data->link);
        exit();
    } else {
        $msg = $res->message ?? 'Unknown error';
        error_log("Referee Payment Error: Flutterwave API Error: $msg");
        header('Location: my_team.php?error=' . urlencode('Payment initialization failed: ' . $msg));
        exit();
    }
} else {
    error_log("Referee Payment Error: Invalid payment method '$payment_method'.");
    header('Location: my_team.php?error=' . urlencode('Invalid payment method.'));
}
exit();
?>