<?php
require_once '../core/bootstrap.php';
 
// Protect this page: redirect to login if user is not logged in.
if (!isset($_SESSION['user_id'])) {
    // Respond with an error or redirect, depending on if this is an API endpoint.
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $team_name = trim($_POST['team_name'] ?? '');
    $league_id = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT);

    if (empty($team_name) || !$league_id) {
        // Handle error - maybe redirect back with an error message
        header('Location: fantasy.php?error=empty_name_or_league');
        exit();
    }

    // --- Instantiate Models ---
    $fantasyModel = new Fantasy();
    $seasonModel = new Season();
    
    // Get the latest season dynamically, just like on the fantasy dashboard page.
    $latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);

    $data = [
        'user_id' => $user_id,
        'name' => $team_name,
        'season' => $latest_season,
        'league_id' => $league_id
    ];

    if ($fantasyModel->create($data)) {
        // Success! Redirect to the fantasy page, which will now show the dashboard.
        header('Location: fantasy.php?league_id=' . $league_id . '&team_created=true');
        exit();
    } else {
        // Handle database error
        header('Location: fantasy.php?league_id=' . $league_id . '&error=db_error');
        exit();
    }
}

// If accessed directly, just redirect away.
header('Location: fantasy.php');
exit();
?>