<?php
require __DIR__ . '/config/config.php';

$streamId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($streamId <= 0) {
    http_response_code(400);
    exit('Missing stream id');
}

try {
    $db = new PDO('sqlite:' . DB_PATH);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $db->prepare("
        SELECT streams.url, streams.format
        FROM streams
        JOIN stations ON stations.id = streams.station_id
        WHERE streams.id = :id
          AND streams.active = 1
          AND stations.active = 1
        LIMIT 1
    ");
    $stmt->execute([':id' => $streamId]);
    $stream = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    http_response_code(500);
    exit('Stream lookup failed');
}

if (!$stream || empty($stream['url'])) {
    http_response_code(404);
    exit('Stream not found');
}

$url = $stream['url'];
if (!preg_match('#^https?://#i', $url)) {
    http_response_code(400);
    exit('Invalid stream URL');
}

ignore_user_abort(true);
set_time_limit(0);

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

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('X-Accel-Buffering: no');
header('Access-Control-Allow-Origin: *');

$sentContentType = false;
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_BUFFERSIZE => 16384,
    CURLOPT_USERAGENT => 'Stellan Radio Stream Proxy/1.0',
    CURLOPT_HEADERFUNCTION => function ($curl, string $header) use (&$sentContentType, $stream): int {
        $len = strlen($header);
        if (stripos($header, 'Content-Type:') === 0) {
            $value = trim(substr($header, 13));
            if ($value !== '') {
                header('Content-Type: ' . $value);
                $sentContentType = true;
            }
        }
        return $len;
    },
    CURLOPT_WRITEFUNCTION => function ($curl, string $chunk): int {
        echo $chunk;
        flush();
        return connection_aborted() ? 0 : strlen($chunk);
    },
]);

if (!$sentContentType) {
    $format = strtolower((string)($stream['format'] ?? ''));
    if ($format === 'aac' || $format === 'aac+') {
        header('Content-Type: audio/aac');
    } elseif ($format === 'ogg' || $format === 'vorbis') {
        header('Content-Type: audio/ogg');
    } else {
        header('Content-Type: audio/mpeg');
    }
}

curl_exec($ch);
$errNo = curl_errno($ch);
curl_close($ch);

if ($errNo && !headers_sent()) {
    http_response_code(502);
}
