<?php
// Generated by SPANDAMAN. Fast public publish/status refresh for shared hosts.
error_reporting(0);
set_time_limit(30);
header('Content-Type: application/json; charset=utf-8');
$channels = __DIR__ . '/channels';
if (!is_dir($channels)) mkdir($channels, 0755, true);
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
if (strtolower($host) === 'www.apps.spandaman.co.uk') $host = 'apps.spandaman.co.uk';
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
if ($dir === '/' || $dir === '.') $dir = '';
$base = $scheme . '://' . $host . $dir;
$countNeedle = function($path, $needle) {
    if (!is_file($path)) return 0;
    $count = 0;
    $handle = fopen($path, 'rb');
    if (!$handle) return 0;
    while (!feof($handle)) {
        $chunk = fread($handle, 1048576);
        if ($chunk === false || $chunk === '') continue;
        $count += substr_count($chunk, $needle);
    }
    fclose($handle);
    return $count;
};
$merged = fopen(__DIR__ . '/spandaman_playlist.m3u8', 'wb');
fwrite($merged, '#EXTM3U x-tvg-url="' . $base . '/spandaman_epg.xml.gz" url-tvg="' . $base . '/spandaman_epg.xml.gz"' . "\n");
foreach (array($channels . '/spandaman_xtream_all.m3u8', $channels . '/spandaman_tmdb_vod.m3u8') as $path) {
    if (!is_file($path)) continue;
    $handle = fopen($path, 'rb');
    if (!$handle) continue;
    while (($line = fgets($handle)) !== false) {
        if (stripos(trim($line), '#EXTM3U') === 0) continue;
        fwrite($merged, str_replace('[[SERVER_URL]]', $base, $line));
    }
    fclose($handle);
}
fclose($merged);
copy(__DIR__ . '/spandaman_playlist.m3u8', __DIR__ . '/spandaman_playlist.m3u');
$liveCount = $countNeedle($channels . '/spandaman_xtream_live_streams.json', '"stream_id"');
$vodCount = $countNeedle($channels . '/spandaman_xtream_vod_streams.json', '"stream_id"') + $countNeedle($channels . '/spandaman_tmdb_vod_streams.json', '"stream_id"');
$seriesCount = $countNeedle($channels . '/spandaman_xtream_series_streams.json', '"series_id"');
$status = array(
    'ok' => true,
    'fast' => true,
    'updated_at' => gmdate('c'),
    'live' => $liveCount,
    'vod' => $vodCount,
    'series' => $seriesCount,
    'adult_enabled' => true,
    'public_counts' => array('live' => $liveCount, 'vod' => $vodCount, 'series' => $seriesCount),
    'playlist' => $base . '/get.php?username=anything&password=anything&type=m3u_plus&output=ts',
    'player_api' => $base . '/player_api.php?username=anything&password=anything',
);
file_put_contents($channels . '/spandaman_tmdb_status.json', json_encode($status, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo json_encode($status, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>