<?php
require_once __DIR__ . '/config.php';

function spandaman_series_base_url() {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'apps.spandaman.co.uk';
    if (strtolower($host) === 'www.apps.spandaman.co.uk') {
        $host = 'apps.spandaman.co.uk';
    }
    return $scheme . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
}

function spandaman_series_cache_value($entry) {
    if (is_array($entry) && isset($entry['value'])) {
        $entry = $entry['value'];
    }
    if (!is_string($entry)) {
        return '';
    }
    $value = trim($entry);
    $decoded = json_decode($value, true);
    if (is_string($decoded)) {
        $value = $decoded;
    }
    return trim($value);
}

function spandaman_series_abs_url($url) {
    if (preg_match('#^https?://#i', (string)$url)) {
        return (string)$url;
    }
    return spandaman_series_base_url() . '/' . ltrim((string)$url, '/');
}

$cacheFile = __DIR__ . '/cache.json';
$cache = (is_file($cacheFile) && filesize($cacheFile) > 8) ? json_decode((string)file_get_contents($cacheFile), true) : [];

header('Content-Type: audio/x-mpegurl; charset=utf-8');
echo "#EXTM3U\n";

$count = 0;
if (is_array($cache)) {
    foreach ($cache as $key => $entry) {
        if (!preg_match('/^(\d+)_series_(\d+)_url$/', (string)$key, $match)) {
            continue;
        }
        $url = spandaman_series_cache_value($entry);
        if ($url === '' || stripos($url, 'test-streams.mux.dev') !== false || stripos($url, '_failed_') !== false) {
            continue;
        }
        $seriesId = $match[1];
        $episodeId = $match[2];
        $name = $seriesId . ' episode ' . $episodeId;
        echo '#EXTINF:-1 group-title="Series" tvg-id="' . $key . '",' . $name . "\n";
        echo spandaman_series_abs_url($url) . "\n";
        $count++;
    }
}

if ($count === 0) {
    echo "# No cached series episode streams yet. Run the full series cache update.\n";
}
?>
