<?php
/**
 * RadioWebSystem - Stream Proxy
 * Řeší problém s Mixed Content (HTTP stream na HTTPS webu).
 */

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("X-Accel-Buffering: no"); // Zabránění cachování případných proxy serverů (např. Nginx)
set_time_limit(0);

require_once __DIR__ . '/JsonDB.php';

$settingsDb = new JsonDB('settings');
$streamUrl = '';
$streams = [];
foreach ($settingsDb->getAll() as $row) {
    if (isset($row['key']) && $row['key'] === 'stream_url') { $streamUrl = $row['value']; }
    if (isset($row['key']) && $row['key'] === 'streams') { $streams = $row['value']; }
}

$requestedStream = $_GET['stream'] ?? '';
if (!empty($requestedStream)) {
    $valid = false;
    if ($requestedStream === $streamUrl) $valid = true;
    if (is_array($streams)) {
        foreach ($streams as $s) {
            if (($s['listen_url'] ?? '') === $requestedStream) { $valid = true; break; }
        }
    }
    if ($valid) $streamUrl = $requestedStream;
}

if (empty($streamUrl)) {
    header("HTTP/1.1 404 Not Found");
    exit('Stream URL is not configured.');
}

header('Content-Type: audio/mpeg');
header('Connection: keep-alive');

$ctx = stream_context_create(['http' => ['method' => 'GET', 'header' => "Icy-MetaData: 0\r\n", 'timeout' => 5]]);
$handle = @fopen($streamUrl, 'rb', false, $ctx);

if (!$handle) {
    header("HTTP/1.1 502 Bad Gateway");
    exit('Unable to connect to the audio stream.');
}

while (!feof($handle)) { echo fread($handle, 8192); ob_flush(); flush(); if (connection_aborted()) break; }
fclose($handle);
exit;