<?php
// Connect to the SQLite database
$db = new SQLite3('./data/.bet_tmdb.db');

// Query to retrieve the API key from the 'api_key' table
$query = "SELECT key FROM api_key LIMIT 1";
$result = $db->querySingle($query);

// Close the database connection
$db->close();

// Check if the API key was retrieved successfully
if ($result) {
    $api_key = $result;
} 
// Common API parameters
$language = "en-US";

// Define the cache folder and file path
$cache_folder = 'cache/';
$cache_file = $cache_folder . 'shows_cache.json';

// Create the cache folder if it doesn't exist
if (!file_exists($cache_folder)) {
    mkdir($cache_folder, 0777, true);
}

// Cache validity duration (15 minutes in seconds)
$cache_duration = 15 * 60;

// Cache validity duration (30 minutes in seconds)
//$cache_duration = 30 * 60;

// Cache validity duration (45 minutes in seconds)
//$cache_duration = 45 * 60;

// Cache validity duration (1 hour in seconds)
//$cache_duration = 1 * 60 * 60;

// Cache validity duration (6 hours in seconds)
//$cache_duration = 6 * 60 * 60;

// Cache validity duration (12 hours in seconds)
//$cache_duration = 12 * 60 * 60;

// Cache validity duration (1 day in seconds)
//$cache_duration = 24 * 60 * 60;

// Cache validity duration (1 week in seconds)
//$cache_duration = 7 * 24 * 60 * 60;

// Check if cached data is still valid
if (file_exists($cache_file) && time() - filemtime($cache_file) < $cache_duration) {
    // Use cached data
    $cached_data = file_get_contents($cache_file);
    $shows = json_decode($cached_data, true);
} else {
    // Fetch shows data using cURL
    $shows_url = "https://api.themoviedb.org/3/trending/tv/week?api_key=$api_key&language=$language";
    $shows_curl = curl_init($shows_url);
    curl_setopt($shows_curl, CURLOPT_RETURNTRANSFER, true);
    $shows_response = curl_exec($shows_curl);
    curl_close($shows_curl);

    $shows_data = json_decode($shows_response, true);

    // Transform tv data to the desired output format
    $shows = [];

    foreach ($shows_data['results'] as $show) {
        $backdrop_path = 'https://image.tmdb.org/t/p/original' . $show['backdrop_path'];
        $poster_path = 'https://image.tmdb.org/t/p/original' . $show['poster_path'];
        $title = $show['name'];
        $subtitle = $show['overview'];
        $url = 'https://www.themoviedb.org/movie/' . $show['id'];

        $shows[] = array(
            "image" => $backdrop_path,
            "artWork" => $poster_path,
            "title" => $title,
            "subtitle" => $subtitle,
            "url" => $url
        );
    }

    // Encode and store data in the cache file without escaping slashes
    $encoded_data = json_encode($shows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    file_put_contents($cache_file, $encoded_data);
}

// Set the appropriate header and echo the transformed shows data as JSON
header("Content-Type: application/json");
echo json_encode($shows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
