<?php
// SPANDAMAN TMDBBASE Xtream-compatible M3U wrapper.
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', '300');
require_once __DIR__ . '/config.php';

error_reporting(0);
set_time_limit(0);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Range, Origin, Accept, Content-Type, User-Agent');
header('Access-Control-Expose-Headers: Content-Length, Content-Range, Content-Type, Location');
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$expectedUsername = 'base';
$expectedPassword = 'base';
$username = $_GET['username'] ?? '';
$password = $_GET['password'] ?? '';
if ($username !== $expectedUsername || $password !== $expectedPassword) {
    http_response_code(401);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Invalid username or password";
    exit;
}

function spandaman_tmdbbase_base_url() {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
    if ($dir === '/' || $dir === '.') $dir = '';
    return $scheme . '://' . $host . $dir;
}

function spandaman_tmdbbase_json($path) {
    if (!is_file($path)) return array();
    $data = json_decode(file_get_contents($path), true);
    return is_array($data) ? $data : array();
}

function spandaman_tmdbbase_safe($value) {
    return str_replace(array('"', "\r", "\n"), array("'", ' ', ' '), trim((string)$value));
}

function spandaman_tmdbbase_group($row, $fallback) {
    if (!empty($row['group'])) return (string)$row['group'];
    if (!empty($row['category_name'])) return (string)$row['category_name'];
    if (!empty($row['category_id'])) return $fallback . ' ' . (string)$row['category_id'];
    return $fallback;
}

function spandaman_tmdbbase_category_map($path) {
    $map = array();
    foreach (spandaman_tmdbbase_json($path) as $row) {
        if (isset($row['category_id']) && isset($row['category_name'])) {
            $map[(string)$row['category_id']] = (string)$row['category_name'];
        }
    }
    return $map;
}

function spandaman_tmdbbase_playable_ids($kind) {
    $ids = array();
    $paths = array(__DIR__ . '/spandaman_playable_tmdb_cache.json', __DIR__ . '/channels/spandaman_playable_tmdb_cache.json');
    foreach ($paths as $path) {
        if (!is_file($path)) continue;
        $cache = json_decode(file_get_contents($path), true);
        if (!is_array($cache)) continue;
        foreach ($cache as $key => $entry) {
            if (!is_array($entry)) continue;
            if (($entry['kind'] ?? '') !== $kind) continue;
            $id = preg_replace('/_tmdb_url$/', '', (string)$key);
            if (ctype_digit($id) && !empty($entry['url'])) {
                $ids[$id] = true;
            }
        }
        if (!empty($ids)) break;
    }
    return $ids;
}

function spandaman_tmdbbase_verified_adult_ids() {
    $ids = array();
    // Adult host links are short-lived; only expose them in playable-only mode
    // after a fresh verifier writes a marker allowing adult rows for this run.
    if (!is_file(__DIR__ . '/spandaman_allow_verified_adult_playlist.flag')) {
        return $ids;
    }
    $paths = array(__DIR__ . '/spandaman_verified_adult_ids.json', __DIR__ . '/channels/spandaman_verified_adult_ids.json');
    foreach ($paths as $path) {
        if (!is_file($path)) continue;
        $data = json_decode(file_get_contents($path), true);
        if (!is_array($data)) continue;
        $rows = $data['ids'] ?? $data;
        if (!is_array($rows)) continue;
        foreach ($rows as $id) {
            $id = (string)$id;
            if (ctype_digit($id)) {
                $ids[$id] = true;
            }
        }
        if (!empty($ids)) break;
    }
    return $ids;
}

function spandaman_tmdbbase_emit_row($name, $logo, $group, $url) {
    $name = spandaman_tmdbbase_safe($name ?: 'SPANDAMAN');
    $logo = str_replace('"', '%22', trim((string)$logo));
    $group = spandaman_tmdbbase_safe($group ?: 'SPANDAMAN');
    echo '#EXTINF:-1 tvg-id="" tvg-name="' . $name . '" tvg-logo="' . $logo . '" group-title="' . $group . '",' . $name . "\n";
    echo $url . "\n";
}

$base = spandaman_tmdbbase_base_url();
$output = strtolower(trim($_GET['output'] ?? 'ts'));
$liveExt = ($output === 'm3u8' || $output === 'hls') ? 'm3u8' : 'ts';
$playableOnly = !empty($_GET['playable_only']) && $_GET['playable_only'] !== '0';
$playableMovies = $playableOnly ? spandaman_tmdbbase_playable_ids('movie') : array();
$playableSeries = $playableOnly ? spandaman_tmdbbase_playable_ids('series') : array();
$playableAdult = $playableOnly ? spandaman_tmdbbase_verified_adult_ids() : array();

header('Content-Type: audio/x-mpegurl; charset=utf-8');
header('Content-Disposition: inline; filename="tmdbbase.m3u8"');
while (ob_get_level() > 0) {
    @ob_end_clean();
}
echo '#EXTM3U x-tvg-url="' . $base . '/xmltv.php?username=base&password=base" url-tvg="' . $base . '/xmltv.php?username=base&password=base"' . "\n";

$liveCategories = spandaman_tmdbbase_category_map(__DIR__ . '/channels/get_live_categories.json');
foreach (spandaman_tmdbbase_json(__DIR__ . '/channels/live_playlist.json') as $row) {
    $id = intval($row['stream_id'] ?? 0);
    if ($id <= 0) continue;
    $categoryId = (string)($row['category_id'] ?? '');
    spandaman_tmdbbase_emit_row(
        $row['name'] ?? '',
        $row['stream_icon'] ?? '',
        $liveCategories[$categoryId] ?? spandaman_tmdbbase_group($row, 'Live'),
        $base . '/live/base/base/' . $id . '.' . $liveExt
    );
}

foreach (spandaman_tmdbbase_json(__DIR__ . '/playlist.json') as $row) {
    $id = intval($row['stream_id'] ?? 0);
    if ($id <= 0) continue;
    if ($playableOnly && empty($playableMovies[(string)$id])) continue;
    spandaman_tmdbbase_emit_row(
        $row['name'] ?? '',
        $row['stream_icon'] ?? '',
        spandaman_tmdbbase_group($row, 'VOD'),
        $base . '/movie/base/base/' . $id . '.mp4'
    );
}

foreach (spandaman_tmdbbase_json(__DIR__ . '/adult-movies.json') as $row) {
    $id = intval($row['stream_id'] ?? 0);
    if ($id <= 0) continue;
    if ($playableOnly && empty($playableAdult[(string)$id])) continue;
    spandaman_tmdbbase_emit_row(
        $row['name'] ?? '',
        $row['stream_icon'] ?? '',
        'XXX Adult Movies',
        $base . '/movie/base/base/' . $id . '.mp4'
    );
}

foreach (spandaman_tmdbbase_json(__DIR__ . '/tv_playlist.json') as $row) {
    $id = intval($row['series_id'] ?? ($row['stream_id'] ?? 0));
    if ($id <= 0) continue;
    if ($playableOnly && empty($playableSeries[(string)$id])) continue;
    $encoded = base64_encode('tt0000000:' . $id . '/season/1/episode/1');
    spandaman_tmdbbase_emit_row(
        ($row['name'] ?? 'Series') . ' S01E01',
        $row['cover'] ?? ($row['stream_icon'] ?? ''),
        spandaman_tmdbbase_group($row, 'Series'),
        $base . '/series/base/base/' . $id . '.' . $encoded
    );
}
?>
