<?php
// Xtream-compatible split get.php wrapper.
require_once __DIR__ . '/config.php';
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$output = isset($_GET['output']) ? strtolower($_GET['output']) : 'm3u8';
$mode = isset($GLOBALS['spandamanSplitMode']) ? strtolower((string)$GLOBALS['spandamanSplitMode']) : '';

function spandaman_abs_url($path) {
    if (preg_match('#^https?://#i', (string)$path)) {
        return (string)$path;
    }
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
    return $scheme . '://' . $host . $base . '/' . ltrim((string)$path, '/');
}

if ($mode === 'adult') {
    $json = @file_get_contents(__DIR__ . '/adult-movies.json');
    $rows = json_decode((string)$json, true);
    if (!is_array($rows)) {
        http_response_code(404);
        echo "#EXTM3U\n# No adult playlist generated yet\n";
        exit;
    }
    header('Content-Type: audio/x-mpegurl; charset=utf-8');
    echo "#EXTM3U\n";
    foreach ($rows as $row) {
        if (!is_array($row)) {
            continue;
        }
        $name = str_replace('"', "'", (string)($row['name'] ?? 'Adult Movie'));
        $logo = str_replace('"', '%22', (string)($row['stream_icon'] ?? ''));
        $group = str_replace('"', "'", (string)($row['group'] ?? 'Adult Movies'));
        $sid = (string)($row['stream_id'] ?? '');
        if ($sid === '') {
            continue;
        }
        $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 spandaman_abs_url('movie/' . rawurlencode($username) . '/' . rawurlencode($password) . '/' . rawurlencode($sid) . '.' . $ext) . "\n";
    }
    exit;
}

$file = ($output === 'ts') ? 'spandaman_playlist_ts.m3u' : 'spandaman_playlist.m3u8';
if (!file_exists(__DIR__ . '/' . $file)) {
    $file = 'movies.m3u8';
}
if (!file_exists(__DIR__ . '/' . $file)) {
    http_response_code(404);
    echo "#EXTM3U\n# No playlist generated yet\n";
    exit;
}
header('Content-Type: audio/x-mpegurl; charset=utf-8');
readfile(__DIR__ . '/' . $file);
?>
