<?php

error_reporting(E_ALL);
ini_set('display_errors', 0);

$SLIV_FILE = __DIR__ . '/livs/sliv.json';
$COOKIE_URL = 'https://raw.githubusercontent.com/Sarcastic-GOD/m3u-stuff/refs/heads/main/Sony247.txt';


function fetch_url($url, $timeout = 6) {

    $opts = [
        'http' => [
            'method'  => 'GET',
            'timeout' => $timeout,
            'header'  => "User-Agent: Mozilla/5.0 (compatible; stream.php)\r\n"
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    $ctx = stream_context_create($opts);
    $result = @file_get_contents($url, false, $ctx);
    if ($result !== false) return $result;


    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; stream.php)');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out === false ? null : $out;
    }

    return null;
}

$id = isset($_GET['id']) ? trim($_GET['id']) : '';
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';

if ($id === '') {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Missing id parameter.";
    exit;
}


if (!file_exists($SLIV_FILE)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "sliv.json not found on server.";
    exit;
}

$raw = @file_get_contents($SLIV_FILE);
if ($raw === false) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Failed to read sliv.json.";
    exit;
}

$entries = json_decode($raw, true);
if (!is_array($entries)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Invalid JSON in sliv.json.";
    exit;
}


$entry = null;
foreach ($entries as $e) {
    if (isset($e['id']) && $e['id'] === $id) {
        $entry = $e;
        break;
    }
}

if (!$entry) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Channel id not found: " . htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
    exit;
}

if (empty($entry['s247_link'])) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "s247_link missing for id: " . htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
    exit;
}

$s247 = trim($entry['s247_link']);


$cookie_text = fetch_url($COOKIE_URL);

if ($cookie_text === null) {

    $cookie_text = '';
} else {

    $cookie_text = trim($cookie_text);

    if (strpos($cookie_text, "\n") !== false) {
        $lines = preg_split("/\r\n|\n|\r/", $cookie_text);
        foreach ($lines as $ln) {
            $ln = trim($ln);
            if ($ln !== '') {
                $cookie_text = $ln;
                break;
            }
        }
    }
}


$cookie_text = trim($cookie_text);


$final_url = $s247;

if ($cookie_text !== '') {
    // cookie may start with '?' or not, and s247 may already include query
    $cookie_clean = $cookie_text;
    if (strpos($cookie_clean, '?') === 0) $cookie_clean = substr($cookie_clean, 1);

    $has_query = (parse_url($s247, PHP_URL_QUERY) !== null);
    $sep = $has_query ? '&' : '?';
    $final_url = $s247 . $sep . $cookie_clean;
}


if ($debug) {
    header('Content-Type: text/plain; charset=utf-8');
    echo $final_url . PHP_EOL;
    exit;
}


header('Location: ' . $final_url, true, 302);
exit;
