<?php
header('Content-Type: application/json');
require_once '../../core/bootstrap.php';

try {
    // 1. Get and validate parameters from the request
    $league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
    $gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT);

    if (!$league_id || !$gameweek) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'A valid league_id and gameweek are required.']);
        exit;
    }

    // 2. Instantiate the model and fetch the data
    $fixtureModel = new Fixture();
    $fixtures = $fixtureModel->getFixturesByGameweek($league_id, $gameweek);

    // 3. Return the response
    if ($fixtures) {
        http_response_code(200); // OK
        echo json_encode($fixtures);
    } else {
        // It's not an error if there are no fixtures, just return an empty array
        http_response_code(200);
        echo json_encode([]);
    }

} catch (Exception $e) {
    // Handle any unexpected errors
    http_response_code(500); // Internal Server Error
    echo json_encode([
        'error' => 'An internal server error occurred.',
        'message' => $e->getMessage() // Optional: for debugging purposes
    ]);
}

?>

