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

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

// Instantiate models
$lineup = new Lineup();
$fixture = new Fixture();

// Get the fixture ID from the URL query string and validate it
$fixture_id = filter_input(INPUT_GET, 'fixture_id', FILTER_VALIDATE_INT);

if (!$fixture_id) {
    http_response_code(400); // Bad Request
    echo json_encode(['message' => 'A valid integer fixture_id is required.']);
    exit();
}

// First, get the fixture details to know home and away team IDs
$fixtureDetails = $fixture->findById($fixture_id);
if (!$fixtureDetails) {
    http_response_code(404);
    echo json_encode(['message' => 'Fixture not found.']);
    exit();
}

// This check is no longer needed here as the model logic is sufficient and this was causing issues with half_time status.
// The original intent was likely to prevent showing lineups before they are submitted, but the frontend now handles this gracefully.
// if ($fixtureDetails->status !== 'live' && $fixtureDetails->status !== 'scheduled') {
//     http_response_code(403);
//     echo json_encode(['message' => 'Lineups can only be viewed for live or scheduled matches.']);
//     exit();
// }

// Fetch the raw lineup data
$lineupData = $lineup->getByFixture($fixture_id);

// Structure the data for the response
$response = [
    'home_team' => [
        'team_id' => (int)$fixtureDetails->home_team_id,
        'starters' => [],
        'substitutes' => []
    ],
    'away_team' => [
        'team_id' => (int)$fixtureDetails->away_team_id,
        'starters' => [],
        'substitutes' => []
    ]
];

foreach ($lineupData as $player) {
    $player_data = [
        'player_id' => (int)$player->player_id,
        'first_name' => $player->first_name,
        'last_name' => $player->last_name,
        'position' => $player->position,
        'squad_number' => (int)$player->squad_number
    ];

    $teamKey = ($player->team_id == $fixtureDetails->home_team_id) ? 'home_team' : 'away_team';
    $statusKey = ($player->status == 'starter') ? 'starters' : 'substitutes';

    $response[$teamKey][$statusKey][] = $player_data;
}

http_response_code(200);
echo json_encode($response);
?>