<?php
require_once __DIR__ . '/includes/bootstrap.php';
if (function_exists('session_write_close') && session_status() === PHP_SESSION_ACTIVE) { session_write_close(); }
$urls = ugfx_get_player_urls();
$streamUrl = trim((string)($urls['raw'] ?? ''));
if ($streamUrl === '') {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Stream URL not configured.';
    exit;
}
@set_time_limit(0);
ignore_user_abort(true);
header('Content-Type: audio/mpeg');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Origin: *');

if (function_exists('curl_init')) {
    $ch = curl_init($streamUrl);
    curl_setopt_array($ch, [
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_RETURNTRANSFER => false,
        CURLOPT_HEADER => false,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_BUFFERSIZE => 8192,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HEADERFUNCTION => function($ch, $header) {
            $len = strlen($header);
            $parts = explode(':', $header, 2);
            if (count($parts) === 2) {
                $name = strtolower(trim($parts[0]));
                $value = trim($parts[1]);
                if ($name === 'content-type' && $value !== '' && !headers_sent()) {
                    header('Content-Type: ' . $value);
                }
            }
            return $len;
        },
        CURLOPT_WRITEFUNCTION => function($ch, $data) {
            echo $data;
            @ob_flush();
            @flush();
            return strlen($data);
        },
    ]);
    $result = curl_exec($ch);
    if ($result === false) {
        if (!headers_sent()) {
            http_response_code(502);
            header('Content-Type: text/plain; charset=utf-8');
        }
        echo 'Proxy stream unavailable.';
    }
    curl_close($ch);
    exit;
}

$context = stream_context_create(['http' => ['timeout' => 10, 'ignore_errors' => true]]);
$in = @fopen($streamUrl, 'rb', false, $context);
if (!$in) {
    http_response_code(502);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Proxy stream unavailable.';
    exit;
}
while (!feof($in)) {
    echo fread($in, 8192);
    @ob_flush();
    @flush();
}
fclose($in);
