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

$cfg = function_exists('smurf_get_stream_config') ? smurf_get_stream_config() : [];
$streamUrl = trim((string)($cfg['listen_url'] ?? ''));
$settingsFile = __DIR__ . '/data/settings.json';
if (is_file($settingsFile)) {
    $settings = json_decode((string)file_get_contents($settingsFile), true);
    if (is_array($settings) && !empty($settings['stream_url'])) {
        $streamUrl = trim((string)$settings['stream_url']);
    }
}

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: *');

$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 => static 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 => static 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);
