<?php
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();

$url = trim($_GET['url'] ?? '');

if ($url === '' || !filter_var($url, FILTER_VALIDATE_URL)) {
    json_response(['ok' => false, 'error' => 'Valid url parameter is required'], 422);
}

$scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? '');
if (!in_array($scheme, ['http', 'https'], true)) {
    json_response(['ok' => false, 'error' => 'Only http and https URLs are allowed'], 422);
}

function fetch_iptv_text(string $url)
{
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 35,
            CURLOPT_USERAGENT => 'NexoPlayer/1.0',
            CURLOPT_HTTPHEADER => [
                'Accept: application/x-mpegURL, application/vnd.apple.mpegurl, text/plain, */*',
            ],
        ];
        if (!ini_get('open_basedir')) {
            $options[CURLOPT_FOLLOWLOCATION] = true;
        }
        curl_setopt_array($ch, $options);
        $body = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($body !== false && $status >= 200 && $status < 400) {
            return $body;
        }
    }

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 35,
            'ignore_errors' => true,
            'header' => "User-Agent: NexoPlayer/1.0\r\nAccept: application/x-mpegURL, application/vnd.apple.mpegurl, text/plain, */*\r\n",
        ],
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
        ],
    ]);

    $body = @file_get_contents($url, false, $context);
    $status = 0;
    foreach (($http_response_header ?? []) as $header) {
        if (preg_match('/^HTTP\/\S+\s+(\d+)/', $header, $match)) {
            $status = (int) $match[1];
        }
    }

    if ($body !== false && ($status === 0 || ($status >= 200 && $status < 400))) {
        return $body;
    }

    return false;
}

$body = fetch_iptv_text($url);

if ($body === false || $body === '') {
    json_response(['ok' => false, 'error' => 'Could not fetch remote URL'], 502);
}

header('Content-Type: text/plain; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, OPTIONS');
http_response_code(200);
echo $body;
