<?php
require_once '../../core/bootstrap.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'team_manager') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$teamModel = new Team();
$team = $teamModel->getTeamByManagerId($_SESSION['user_id']);

if (!$team) {
    http_response_code(404);
    echo json_encode(['error' => 'Team not found']);
    exit();
}

$fixtureModel = new Fixture();
// Get the most recent finished match for the team
$recent_matches = $fixtureModel->getRecentResultsForTeam($team->id, 1);

if (empty($recent_matches)) {
    echo json_encode(['error' => 'No previous matches found']);
    exit();
}

$last_match = $recent_matches[0];

$lineupModel = new Lineup();
$lineup = $lineupModel->getLineupForFixture($last_match->id, $team->id);

if (!$lineup) {
    echo json_encode(['error' => 'No lineup found for previous match']);
    exit();
}

echo json_encode($lineup);