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

// --- Authentication & Basic Validation ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

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

$user_id = $_SESSION['user_id'];
$transfers = $_POST['transfers'] ?? [];
$redirect_to = $_POST['redirect_to'] ?? 'fantasy_transfers.php';
$league_id = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT);

if (!$league_id) {
    header('Location: ' . $redirect_to . '?error=missing_league_id');
    exit();
}

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$playerModel = new Player();
$fixtureModel = new Fixture();
$gameweekModel = new Gameweek();

// --- Get User's Fantasy Team ---
$latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);
$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $league_id);

if (!$user_fantasy_team) {
    header('Location: ' . $redirect_to . '?error=no_team');
    exit();
}

// --- Determine Current Gameweek & Deadline ---
$current_gameweek = 1;
$latest_finished_gameweek = $fixtureModel->getLatestFinishedGameweek($league_id);
if ($latest_finished_gameweek) {
    $current_gameweek = $latest_finished_gameweek + 1;
} else {
    $next_fixture = $fixtureModel->getNextUpcomingFixture($league_id);
    if ($next_fixture) $current_gameweek = $next_fixture->gameweek;
}

if ($gameweekModel->hasDeadlinePassed($current_gameweek, $league_id, $latest_season)) {
    // If deadline passed, transfers apply to next gameweek
    $current_gameweek++;
}

// --- Validate Transfers & Calculate Cost ---
$bank = (float)$user_fantasy_team->bank;
$free_transfers = (int)($user_fantasy_team->free_transfers ?? 1);
$cost = 0;
$transfers_count = count($transfers);

if ($transfers_count > 0) {
    // Calculate cost
    $chargeable_transfers = max(0, $transfers_count - $free_transfers);
    $cost = $chargeable_transfers * 4;

    // Validate Bank Balance
    foreach ($transfers as $t) {
        $playerOut = $playerModel->getPlayersForFantasySelection($league_id, $t['out'])[0] ?? null;
        $playerIn = $playerModel->getPlayersForFantasySelection($league_id, $t['in'])[0] ?? null;

        if (!$playerOut || !$playerIn) {
            header('Location: ' . $redirect_to . '?error=invalid_players');
            exit();
        }

        $bank += (float)$playerOut->fantasy_price;
        $bank -= (float)$playerIn->fantasy_price;
    }

    if ($bank < 0) {
        header('Location: ' . $redirect_to . '?error=insufficient_funds');
        exit();
    }

    // --- Process Transfers ---
    // Update free transfers count
    $new_free_transfers = max(0, $free_transfers - $transfers_count);
    $db = new Database();
    $db->query("UPDATE fantasy_teams SET free_transfers = :ft WHERE id = :id");
    $db->bind(':ft', $new_free_transfers);
    $db->bind(':id', $user_fantasy_team->id);
    $db->execute();

    if ($fantasyModel->processTransfers($user_fantasy_team->id, $transfers, $cost, $bank, $current_gameweek)) {
        header('Location: ' . $redirect_to . '?transfers_status=success&league_id=' . $league_id);
    } else {
        header('Location: ' . $redirect_to . '?error=transfer_failed&league_id=' . $league_id);
    }
} else {
    header('Location: ' . $redirect_to . '?league_id=' . $league_id);
}
exit();
?>