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

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

$fixture_id = filter_input(INPUT_GET, 'fixture_id', FILTER_VALIDATE_INT);

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

$fixtureModel = new Fixture();
$eventModel = new MatchEvent();

try {
    // Fetch the latest fixture data (score, status, etc.)
    $fixtureDetails = $fixtureModel->findById($fixture_id);
    if (!$fixtureDetails) {
        http_response_code(404);
        echo json_encode(['message' => 'Fixture not found.']);
        exit();
    }

    // Fetch all events for the fixture
    $events = $eventModel->getEventsByFixtureId($fixture_id);

    $response = [
        'fixture' => $fixtureDetails,
        'events' => $events
    ];

    http_response_code(200);
    echo json_encode($response);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while fetching match updates.']);
}
?>