<?php
require_once __DIR__ . '/includes/bootstrap.php';
if (function_exists('session_write_close') && session_status() === PHP_SESSION_ACTIVE) { session_write_close(); }
if (function_exists('apache_setenv')) {
    @apache_setenv('no-gzip', '1');
}
@ini_set('zlib.output_compression', '0');
@ini_set('output_buffering', '0');
while (ob_get_level() > 0) { @ob_end_flush(); }
ob_implicit_flush(true);
$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: *');
header('X-Accel-Buffering: no');

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 => 16384,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TCP_KEEPALIVE => 1,
        CURLOPT_HTTPHEADER => ['Icy-MetaData: 1'],
        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 (in_array($name, ['content-type', 'icy-metaint'], true) && $value !== '' && !headers_sent()) {
                    header(($name === 'content-type' ? 'Content-Type' : 'icy-metaint') . ': ' . $value);
                }
            }
            return $len;
        },
        CURLOPT_WRITEFUNCTION => function($ch, $data) {
            echo $data;
            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, 'header' => "Icy-MetaData: 1\r\n"]]);
$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;
}
stream_set_timeout($in, 0);
while (!feof($in)) {
    $chunk = fread($in, 16384);
    if ($chunk === false) { break; }
    echo $chunk;
    flush();
}
fclose($in);
