<?php
// api/live.php – Loggar uppspelning + returnerar failover-URL om primär är nere
require __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$data = json_decode(file_get_contents('php://input'), true) ?? [];
$id   = intval($data['station_id'] ?? $_GET['id'] ?? 0);

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

try {
    $db = new PDO('sqlite:' . DB_PATH);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Logga (hasha IP för GDPR)
    $ipHash = hash('sha256', $_SERVER['REMOTE_ADDR'] ?? 'unknown');
    $db->prepare("INSERT INTO play_log (station_id, ip_hash) VALUES (?,?)")->execute([$id, $ipHash]);

    // Hämta alla aktiva streams sorterade på online-status + prioritet = automatisk failover
    $stmt = $db->prepare("
        SELECT st.url, st.format, st.bitrate, st.label, COALESCE(ss.online,0) AS 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
    ");
    $stmt->execute([$id]);
    $streams = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $best = $streams[0] ?? null;

    echo json_encode([
        'ok'        => true,
        'stream_url'=> $best['url']    ?? null,
        'format'    => $best['format'] ?? null,
        'online'    => (bool)($best['online'] ?? false),
        'streams'   => $streams,
    ]);

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