<?php
// api/stations.php – Returnerar alla aktiva stationer som JSON
require __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

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
        )
    ");

    $genre  = $_GET['genre']  ?? '';
    $search = $_GET['search'] ?? '';

    $sql = "
        SELECT s.id, s.name, s.slug, s.genre, s.description, s.logo, s.website,
               (SELECT id FROM streams WHERE station_id=s.id AND active=1 ORDER BY priority LIMIT 1) AS stream_id,
               (SELECT url FROM streams WHERE station_id=s.id AND active=1 ORDER BY priority LIMIT 1) AS stream_url,
               (SELECT online FROM stream_status ss
                JOIN streams st ON st.id=ss.stream_id
                WHERE st.station_id=s.id AND st.active=1 ORDER BY st.priority LIMIT 1) AS is_online,
               COALESCE(
                   (SELECT sm.title FROM stream_metadata sm
                    JOIN streams st2 ON st2.id=sm.stream_id
                    WHERE st2.station_id=s.id AND st2.active=1
                    ORDER BY st2.priority LIMIT 1),
                   m.title
               ) AS meta_title,
               COALESCE(
                   (SELECT sm.artist FROM stream_metadata sm
                    JOIN streams st2 ON st2.id=sm.stream_id
                    WHERE st2.station_id=s.id AND st2.active=1
                    ORDER BY st2.priority LIMIT 1),
                   m.artist
               ) AS meta_artist,
               COALESCE(
                   (SELECT sm.raw FROM stream_metadata sm
                    JOIN streams st2 ON st2.id=sm.stream_id
                    WHERE st2.station_id=s.id AND st2.active=1
                    ORDER BY st2.priority LIMIT 1),
                   m.raw
               ) AS meta_raw,
               COALESCE(
                   (SELECT sm.fetched_at FROM stream_metadata sm
                    JOIN streams st2 ON st2.id=sm.stream_id
                    WHERE st2.station_id=s.id AND st2.active=1
                    ORDER BY st2.priority LIMIT 1),
                   m.fetched_at
               ) AS meta_fetched_at
        FROM stations s
        LEFT JOIN metadata m ON m.station_id=s.id
        WHERE s.active=1
    ";
    $params = [];

    if ($genre) {
        $sql .= " AND s.genre = ?";
        $params[] = $genre;
    }
    if ($search) {
        $sql .= " AND (s.name LIKE ? OR s.description LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $sql .= " ORDER BY s.sort_order, s.name";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['ok' => true, 'stations' => $rows, 'count' => count($rows)]);

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