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

require_once '../../../core/bootstrap.php';
require_once '../middleware/validate_token.php';

// Ensure the user is a team manager
if ($authenticated_user_data->role !== 'team_manager') {
    http_response_code(403);
    echo json_encode(['message' => 'Forbidden: You are not a team manager.']);
    exit();
}

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

if (empty($data->fixture_id) || !isset($data->starters) || count($data->starters) !== 11) {
    http_response_code(400);
    echo json_encode(['message' => 'Fixture ID and exactly 11 starters are required.']);
    exit();
}

$teamModel = new Team();
$lineupModel = new Lineup();

// Get the manager's team to ensure they are submitting for their own team
$team = $teamModel->getTeamByManagerId($authenticated_user_data->id);
if (!$team) {
    http_response_code(403);
    echo json_encode(['message' => 'You are not assigned to a team.']);
    exit();
}

try {
    if ($lineupModel->submitLineup($data->fixture_id, $team->id, $data->starters, [])) {
        http_response_code(200);
        echo json_encode(['message' => 'Lineup submitted successfully!']);
    } else {
        throw new Exception('Failed to submit lineup.');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['message' => $e->getMessage()]);
}
?>