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

$username = isset($_GET['username']) ? $_GET['username'] : 'vod';
$password = isset($_GET['password']) ? $_GET['password'] : 'vod';
$output = isset($_GET['output']) ? strtolower($_GET['output']) : 'm3u8';

function spandaman_vod_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_vod_load_rows() {
    $file = __DIR__ . '/playlist.json';
    $body = (is_file($file) && filesize($file) > 8) ? file_get_contents($file) : '';
    $rows = json_decode((string)$body, true);
    if (is_array($rows) && count($rows) > 0) {
        return $rows;
    }

    $remote = @file_get_contents('https://raw.githubusercontent.com/gogetta69/public-files/main/playlist.json');
    $rows = json_decode((string)$remote, true);
    if (is_array($rows) && count($rows) > 0) {
        $base = spandaman_vod_base_url();
        $remote = str_replace('[[SERVER_URL]]', $base, (string)$remote);
        @file_put_contents($file, $remote);
        @chmod($file, 0777);
        return json_decode($remote, true);
    }
    return [];
}

function spandaman_vod_attr($value) {
    return str_replace('"', "'", str_replace(["\r", "\n"], ' ', (string)$value));
}

$rows = spandaman_vod_load_rows();
if (!is_array($rows) || count($rows) === 0) {
    http_response_code(404);
    echo "#EXTM3U\n# No VOD playlist generated yet\n";
    exit;
}

$base = spandaman_vod_base_url();
header('Content-Type: audio/x-mpegurl; charset=utf-8');
echo "#EXTM3U\n";
foreach ($rows as $row) {
    if (!is_array($row)) {
        continue;
    }
    $sid = (string)($row['stream_id'] ?? '');
    if ($sid === '') {
        continue;
    }
    $name = spandaman_vod_attr($row['name'] ?? 'Movie');
    $logo = spandaman_vod_attr($row['stream_icon'] ?? ($row['cover'] ?? ''));
    $group = spandaman_vod_attr($row['group'] ?? 'Movies');
    $ext = preg_replace('/[^a-z0-9]/i', '', (string)($row['container_extension'] ?? 'mp4'));
    if ($ext === '') {
        $ext = ($output === 'ts') ? 'ts' : 'mp4';
    }
    echo '#EXTINF:-1 tvg-id="" tvg-name="' . $name . '" tvg-logo="' . $logo . '" group-title="' . $group . '",' . $name . "\n";
    echo $base . '/movie/' . rawurlencode($username) . '/' . rawurlencode($password) . '/' . rawurlencode($sid) . '.' . $ext . "\n";
}
?>
