<?php
// api/stream.php - Returnerar metadata for en enskild stream.
require __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$id = intval($_GET['id'] ?? 0);
if (!$id) {
    echo json_encode(['ok' => false, 'error' => 'missing id']);
    exit;
}

try {
    $db = new PDO('sqlite:' . DB_PATH);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("
        CREATE TABLE IF NOT EXISTS stream_metadata (
            stream_id INTEGER PRIMARY KEY,
            station_id INTEGER,
            title TEXT,
            artist TEXT,
            raw TEXT,
            fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ");

    $stmt = $db->prepare("
        SELECT st.id AS stream_id, st.station_id, st.url, st.label,
               sm.title, sm.artist, sm.raw, sm.fetched_at
        FROM streams st
        LEFT JOIN stream_metadata sm ON sm.stream_id = st.id
        WHERE st.id = ? AND st.active = 1
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['ok' => false, 'error' => 'not found']);
        exit;
    }

    echo json_encode([
        'ok' => true,
        'stream_id' => (int)$row['stream_id'],
        'station_id' => (int)$row['station_id'],
        'label' => $row['label'] ?? null,
        'title' => $row['title'] ?? null,
        'artist' => $row['artist'] ?? null,
        'raw' => $row['raw'] ?? null,
        'fetched_at' => $row['fetched_at'] ?? null,
        'stream_url' => $row['url'] ?? null,
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
