<?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.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? 'save';
$fantasySquadModel = new FantasySquad();
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$leagueModel = new League();

// --- Determine League Context ---
$league_id = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT);
if (!$league_id) {
    $league_id = 1; // Fallback or handle error
}

// --- 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: fantasy.php?error=no_team');
    exit();
}

if ($action === 'reset') {
    // Clear the squad and redirect to the squad builder
    $fantasySquadModel->deleteSquad($user_fantasy_team->id);
    // Reset bank to 100
    $fantasyModel->updateBank($user_fantasy_team->id, 100.0);
    header('Location: fantasy.php?status=squad_reset');
    exit();
}

$starter_ids = $_POST['starters'] ?? [];
$bench_ids = $_POST['bench'] ?? [];
$captain_id = filter_input(INPUT_POST, 'captain', FILTER_VALIDATE_INT);
$vice_captain_id = filter_input(INPUT_POST, 'vice_captain', FILTER_VALIDATE_INT);

// --- Validation ---
if (count($starter_ids) !== 11 || count($bench_ids) !== 4) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Invalid squad count.'));
    exit();
}

// --- Validate GK Count ---
// EPL Rules: 1 GK, Min 3 DEF, Min 2 MID, Min 1 FWD
$db = new Database();
$ids_placeholder = implode(',', array_fill(0, count($starter_ids), '?'));
$db->query("SELECT position FROM players WHERE user_id IN ($ids_placeholder)");
$positions = $db->resultSet($starter_ids);

$pos_counts = ['Goalkeeper' => 0, 'Defender' => 0, 'Midfielder' => 0, 'Forward' => 0];
foreach ($positions as $p) {
    $pos_counts[$p->position]++;
}

if ($pos_counts['Goalkeeper'] !== 1) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Lineup must have exactly 1 Goalkeeper.'));
    exit();
}
if ($pos_counts['Defender'] < 3) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Lineup must have at least 3 Defenders.'));
    exit();
}
if ($pos_counts['Midfielder'] < 2) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Lineup must have at least 2 Midfielders.'));
    exit();
}
if ($pos_counts['Forward'] < 1) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Lineup must have at least 1 Forward.'));
    exit();
}

if (!$captain_id || !$vice_captain_id || $captain_id === $vice_captain_id) {
    header('Location: fantasy_lineup.php?lineup_status=error&reason=' . urlencode('Invalid captain selection.'));
    exit();
}

// --- Handle Chips ---
$active_chip = $_POST['active_chip'] ?? null;
$valid_chips = ['TC', 'BB', 'FH', 'WC'];
if ($active_chip && !in_array($active_chip, $valid_chips)) {
    $active_chip = null;
}

// Validate if chip is already used (prevent re-use)
if ($active_chip === 'TC' && !is_null($user_fantasy_team->tc_played_gw)) $active_chip = null;
if ($active_chip === 'BB' && !is_null($user_fantasy_team->bb_played_gw)) $active_chip = null;
if ($active_chip === 'FH' && !is_null($user_fantasy_team->fh_played_gw)) $active_chip = null;
if ($active_chip === 'WC' && !is_null($user_fantasy_team->wc_played_gw)) $active_chip = null;

$db->query("UPDATE fantasy_teams SET active_chip = :chip WHERE id = :id");
$db->bind(':chip', $active_chip);
$db->bind(':id', $user_fantasy_team->id);
$db->execute();

// --- Process Updates in a Transaction ---
$success = $fantasySquadModel->updateLineupAndCaptains($user_fantasy_team->id, $starter_ids, $bench_ids, $captain_id, $vice_captain_id);

if ($success) {
    header('Location: fantasy_lineup.php?lineup_status=success&league_id=' . $league_id);
} else {
    header('Location: fantasy_lineup.php?lineup_status=error&league_id=' . $league_id);
}
exit();
?>