<?php
// api/station.php – Returnerar metadata (Nu spelas) för en kanal
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);

    // Hämta metadata
    $meta = $db->prepare("SELECT title, artist, fetched_at FROM metadata WHERE station_id=?");
    $meta->execute([$id]);
    $row = $meta->fetch(PDO::FETCH_ASSOC);

    // Hämta bästa aktiva stream
    $stream = $db->prepare("
        SELECT st.url, ss.online
        FROM streams st
        LEFT JOIN stream_status ss ON ss.stream_id=st.id
        WHERE st.station_id=? AND st.active=1
        ORDER BY ss.online DESC, st.priority
        LIMIT 1
    ");
    $stream->execute([$id]);
    $st = $stream->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'         => true,
        'station_id' => $id,
        'title'      => $row['title']  ?? null,
        'artist'     => $row['artist'] ?? null,
        'fetched_at' => $row['fetched_at'] ?? null,
        'stream_url' => $st['url']    ?? null,
        'online'     => (bool)($st['online'] ?? false),
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
