<?php
// workers/probe.php – Kontrollerar om streams är online
// Kör via cron var 5:e minut:
//   */5 * * * * php /var/www/radio/workers/probe.php >> /var/log/radio_probe.log 2>&1

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$streams = $db->query("SELECT id, url FROM streams WHERE active=1")->fetchAll(PDO::FETCH_ASSOC);

$checked = 0;
$online  = 0;

foreach ($streams as $stream) {
    $result = probeStream($stream['url']);

    $db->prepare("
        INSERT INTO stream_status (stream_id, online, last_check, error_msg)
        VALUES (?, ?, CURRENT_TIMESTAMP, ?)
        ON CONFLICT(stream_id) DO UPDATE SET
            online=excluded.online,
            last_check=excluded.last_check,
            error_msg=excluded.error_msg
    ")->execute([$stream['id'], $result['online'] ? 1 : 0, $result['error']]);

    $checked++;
    if ($result['online']) $online++;

    echo date('H:i:s') . " Stream #{$stream['id']}: " . ($result['online'] ? '✓ ONLINE' : '✗ offline - ' . $result['error']) . "\n";
}

echo date('H:i:s') . " Klar: $checked kontrollerade, $online online\n";

// ── Probe-funktion ───────────────────────────────────────────────────────────
function probeStream(string $url): array
{
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => PROBE_TIMEOUT,
        CURLOPT_TIMEOUT        => PROBE_TIMEOUT + 2,
        CURLOPT_NOBODY         => true,          // HEAD-liknande
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT      => 'RadioUltra-Probe/1.0',
        // Begär bara ett fåtal bytes
        CURLOPT_RANGE          => '0-1023',
    ]);

    curl_exec($ch);
    $code  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    // 200, 206 (partial) eller 301/302-kedjor räknas som online
    $isOnline = in_array($code, [200, 206, 301, 302, 307, 308]) && !$error;

    return [
        'online' => $isOnline,
        'code'   => $code,
        'error'  => $error ?: null,
    ];
}
