<?php
// workers/status.php
// Visar radiokanaler med status (✓ online / ✗ offline)

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

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

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


// Hämta aktiva streams med stationsnamn
$streams = $db->query("
    SELECT
        streams.id,
        stations.name,
        streams.url
    FROM streams
    INNER JOIN stations
        ON stations.id = streams.station_id
    WHERE streams.active = 1
      AND stations.active = 1
    ORDER BY stations.name
")->fetchAll(PDO::FETCH_ASSOC);


// Förbered databasskrivning
$stmt = $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
");


$results = [];
$onlineCount = 0;


// Testa en kanal i taget
foreach ($streams as $s) {

    $bytes = 0;
    $error = null;
    $start = microtime(true);


    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $s['url'],
        CURLOPT_RETURNTRANSFER => false,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'RadioUltra-Probe/1.0',

        CURLOPT_WRITEFUNCTION => function($curl, $data) use (&$bytes) {

            $bytes += strlen($data);

            // Vi har fått ljuddata
            if ($bytes >= 4096) {
                return -1;
            }

            return strlen($data);
        }
    ]);


    curl_exec($ch);


    $curlError = curl_error($ch);
    $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);


    // Streamen är online om vi fått ljuddata
    $online = ($bytes > 0);


    if ($online) {
        $onlineCount++;
    }


    $results[$s['id']] = [
        'online' => $online,
        'error'  => $online ? null : ($curlError ?: 'Ingen data')
    ];


    // Spara status
    $stmt->execute([
        $s['id'],
        $online ? 1 : 0,
        $online ? null : ($curlError ?: 'Ingen data')
    ]);
}


?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>Radio Ultra – Streamstatus</title>

<style>
body {
    font-family: system-ui, sans-serif;
    background:#111;
    color:#eee;
    padding:2rem;
}

h1 {
    font-size:1.5rem;
}

.summary {
    color:#aaa;
    margin-bottom:1rem;
}

table {
    border-collapse:collapse;
    width:100%;
    max-width:800px;
}

td, th {
    padding:.6rem .8rem;
    text-align:left;
    border-bottom:1px solid #333;
}

.ok {
    color:#2ecc71;
    font-size:1.3rem;
}

.fail {
    color:#e74c3c;
    font-size:1.3rem;
}

.err {
    color:#777;
    font-size:.8rem;
}
</style>

</head>

<body>

<h1>Radio Ultra – Streamstatus</h1>

<p class="summary">
    <?= $onlineCount ?> av <?= count($streams) ?> kanaler online ·
    <?= date('Y-m-d H:i:s') ?>
</p>


<table>

<tr>
    <th>Kanal</th>
    <th>Status</th>
</tr>


<?php foreach ($streams as $s): 
    $r = $results[$s['id']];
?>

<tr>

<td>
<?= htmlspecialchars($s['name']) ?>
</td>

<td>

<?php if ($r['online']): ?>

<span class="ok">✓ ONLINE</span>

<?php else: ?>

<span class="fail">✗ OFFLINE</span>

<?php if ($r['error']): ?>
<span class="err">
(<?= htmlspecialchars($r['error']) ?>)
</span>
<?php endif; ?>

<?php endif; ?>

</td>

</tr>

<?php endforeach; ?>

</table>

</body>
</html>