<?php
include ('APIkey.php');
include(__DIR__ . '/../includes/functions.php');
global $db; 

$apie_key = getApiKey();
if (isset($_GET['id'])) {
    // Sanitize the 'id' parameter
    $id = htmlspecialchars($_GET['id']);
    
    
    
    // Build the API URL
    $url = "https://www.thesportsdb.com/api/v1/json/$apie_key/lookuptv.php?id=$id";

    // Debug: Show the URL for troubleshooting
    error_log("Fetching data from URL: $url");

    // Use file_get_contents to fetch the response
    $response = file_get_contents($url);

    // Check if the request was successful
    if ($response !== false) {
        // Debug: Show the raw response
        error_log("Raw API response: " . $response);

        // Decode the JSON response to check its validity
        $data = json_decode($response, true);

        if (json_last_error() === JSON_ERROR_NONE) {
            if (isset($data['tvevent']) && !empty($data['tvevent'])) {
                // Return the valid response in JSON format
                header('Content-Type: application/json');
                echo json_encode($data);
            } else {
                // No `tvevent` data found in the response
                $error = array(
                    'status' => 'error',
                    'message' => 'No tvevent data available for the provided ID.'
                );
                header('Content-Type: application/json');
                echo json_encode($error);
            }
        } else {
            // Handle cases where the JSON response is invalid
            $error = array(
                'status' => 'error',
                'message' => 'Invalid JSON data received from the API.'
            );
            header('Content-Type: application/json');
            echo json_encode($error);
        }
    } else {
        // Failed to fetch the data, output error message
        $error = array(
            'status' => 'error',
            'message' => 'Failed to fetch data from the URL.'
        );
        header('Content-Type: application/json');
        echo json_encode($error);
    }
} else {
    // If 'id' is not set, return an error message
    $error = array(
        'status' => 'error',
        'message' => 'No ID provided'
    );
    header('Content-Type: application/json');
    echo json_encode($error);
}
?>
