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

// Protect this page: redirect to login if user is not logged in.
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['player_ids'])) {
    // Redirect if accessed incorrectly
    header('Location: fantasy_transfers.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$fantasy_team_id = filter_input(INPUT_POST, 'fantasy_team_id', FILTER_VALIDATE_INT);
$player_ids = $_POST['player_ids'] ?? [];

// --- Basic Validation ---
if (count($player_ids) !== 15) {
    header('Location: fantasy.php?error=squad_size_invalid');
    exit();
}

// --- Organize into Starters and Substitutes ---
$playerModel = new Player();

// Get Fantasy Team to know the league
$fantasyModel = new Fantasy();
$user_fantasy_team = $fantasyModel->getTeamById($fantasy_team_id);
if (!$user_fantasy_team || $user_fantasy_team->user_id != $user_id) {
    header('Location: fantasy.php?error=no_team');
    exit();
}

$all_players_info = $playerModel->getPlayersForFantasySelection($user_fantasy_team->league_id);
$player_map = array_column($all_players_info, null, 'id');

$squad_by_pos = ['Goalkeeper' => [], 'Defender' => [], 'Midfielder' => [], 'Forward' => []];
$squad_value = 0.0;

foreach ($player_ids as $pid) {
    if (isset($player_map[$pid])) {
        $squad_by_pos[$player_map[$pid]->position][] = $pid;
        $squad_value += (float)$player_map[$pid]->fantasy_price;
    }
}

// --- Strict Position Count Validation ---
if (count($squad_by_pos['Goalkeeper']) !== 2 || 
    count($squad_by_pos['Defender']) !== 5 || 
    count($squad_by_pos['Midfielder']) !== 5 || 
    count($squad_by_pos['Forward']) !== 3) {
    header('Location: fantasy.php?error=invalid_position_counts');
    exit();
}

// Default lineup: 1 GK, 4 DEF, 4 MID, 2 FWD (4-4-2)
$starters = [];
$substitutes = [];
$formation = '4-4-2';

$starters = array_merge(
    array_slice($squad_by_pos['Goalkeeper'], 0, 1),
    array_slice($squad_by_pos['Defender'], 0, 4),
    array_slice($squad_by_pos['Midfielder'], 0, 4),
    array_slice($squad_by_pos['Forward'], 0, 2)
);

$substitutes = array_diff($player_ids, $starters);

if (count($starters) !== 11 || count($substitutes) !== 4) {
    // This can happen if the user didn't pick the right number of players per position.
    // The JS should prevent this, but we validate here as a safeguard.
    header('Location: fantasy.php?error=invalid_position_counts');
    exit();
}

// --- Determine Current Gameweek ---
// This logic should be consistent across the app.
$fixtureModel = new Fixture();
$league_id = $user_fantasy_team->league_id;

$current_gameweek = 1; // Default
$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;
    }
}

// --- Save the Squad ---
$fantasySquadModel = new FantasySquad();
$success = $fantasySquadModel->setSquad($user_fantasy_team->id, $starters, $substitutes, $formation, $current_gameweek);

if ($success) {
    // Update the team's bank balance based on the initial squad cost
    $new_bank = 100.0 - $squad_value;
    $fantasyModel->updateBank($user_fantasy_team->id, $new_bank);
}

// Redirect back to the main fantasy page
header('Location: fantasy_lineup.php?squad_updated=' . ($success ? 'true' : 'false') . '&league_id=' . $league_id);
exit();
?>