<?php
require_once __DIR__ . '/includes/bootstrap.php';

if (function_exists('session_write_close') && session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

@set_time_limit(0);
ignore_user_abort(true);

while (ob_get_level() > 0) {
    @ob_end_clean();
}

if (function_exists('apache_setenv')) {
    @apache_setenv('no-gzip', '1');
}

@ini_set('zlib.output_compression', '0');
@ini_set('output_buffering', '0');
@ini_set('implicit_flush', '1');

$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;
}

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: *');
header('X-Accel-Buffering: no');

$sentContentType = false;

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_LOW_SPEED_LIMIT  => 1,
        CURLOPT_LOW_SPEED_TIME   => 20,
        CURLOPT_BUFFERSIZE       => 32768,
        CURLOPT_SSL_VERIFYPEER   => false,
        CURLOPT_SSL_VERIFYHOST   => false,
        CURLOPT_USERAGENT        => 'Mozilla/5.0 UGFXRadioProxy/1.0',
        CURLOPT_HTTPHEADER       => [
            'Accept: */*',
            'Connection: keep-alive',
            'Cache-Control: no-cache',
            'Pragma: no-cache',
        ],
        CURLOPT_HEADERFUNCTION   => function ($ch, $header) use (&$sentContentType) {
            $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 !== '' && !$sentContentType && !headers_sent()) {
                    header('Content-Type: ' . $value);
                    $sentContentType = true;
                }
            }
            return $len;
        },
        CURLOPT_WRITEFUNCTION    => function ($ch, $data) {
            echo $data;
            if (function_exists('ob_flush')) {
                @ob_flush();
            }
            @flush();
            return strlen($data);
        },
    ]);

    $result = curl_exec($ch);
    if ($result === false) {
        $err = curl_error($ch);
        if (!headers_sent()) {
            http_response_code(502);
            header('Content-Type: text/plain; charset=utf-8');
        }
        echo 'Proxy stream unavailable.';
        if ($err !== '') {
            echo ' ' . $err;
        }
    }
    curl_close($ch);
    exit;
}

$context = stream_context_create(['http' => [
    'timeout' => 10,
    'ignore_errors' => true,
    'header' => "Accept: */*
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
",
]]);
$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, 32768);
    @ob_flush();
    @flush();
}
fclose($in);
