<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Protect this action - only logged-in users can create a team
require_once '../middleware/validate_token.php';

// Instantiate FantasyTeam model
$fantasyTeam = new FantasyTeam();

// Get raw posted data
$data = json_decode(file_get_contents("php://input"));

// Validation
$errors = [];
if (empty($data->name)) {
    $errors[] = 'A team name is required.';
}
if (empty($data->season)) {
    $errors[] = 'Season is required (e.g., "2023/2024").';
}

if (!empty($errors)) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

// Check if user already has a team for this season
if ($fantasyTeam->findByUserAndSeason($authenticated_user_data->id, $data->season)) {
    http_response_code(409); // Conflict
    echo json_encode(['message' => 'You already have a team for the ' . $data->season . ' season.']);
    exit();
}

$teamData = [
    'user_id' => $authenticated_user_data->id,
    'name' => htmlspecialchars(strip_tags($data->name)),
    'season' => $data->season
];

$newTeamId = $fantasyTeam->create($teamData);

if ($newTeamId) {
    http_response_code(201); // Created
    echo json_encode(['message' => 'Fantasy team created successfully.', 'fantasy_team_id' => $newTeamId]);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'Fantasy team could not be created.']);
}
?>