<?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'];
$captain_id = filter_input(INPUT_POST, 'captain', FILTER_VALIDATE_INT);
$vice_captain_id = filter_input(INPUT_POST, 'vice_captain', FILTER_VALIDATE_INT);
$league_id = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT) ?: 1;

// --- Validation ---
if (!$captain_id || !$vice_captain_id || $captain_id === $vice_captain_id) {
    header('Location: fantasy.php?captain_status=error');
    exit();
}

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$fantasySquadModel = new FantasySquad();

// --- Get User's Fantasy Team (for security and context) ---
$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) {
    // This should not happen if they can see the form, but it's a good safeguard.
    header('Location: fantasy.php?error=no_team');
    exit();
}

// --- Process the Captaincy Update ---
$success = $fantasySquadModel->setCaptains($user_fantasy_team->id, $captain_id, $vice_captain_id);

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