<?php

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

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

$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
    ORDER BY stations.name
")->fetchAll(PDO::FETCH_ASSOC);


foreach ($streams as $s) {

    echo "\n====================================\n";
    echo $s['name'] . "\n";
    echo $s['url'] . "\n";

    $start = microtime(true);

    $ch = curl_init();

    $bytes = 0;

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 => 'Mozilla/5.0',

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

        $bytes += strlen($data);

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

        return strlen($data);
    }
]);

curl_exec($ch);

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$time = round(microtime(true) - $start, 2);
$error = curl_error($ch);

curl_close($ch);

if ($bytes > 0) {
    echo "✓ ONLINE\n";
    echo "HTTP: $code\n";
    echo "Bytes: $bytes\n";
    echo "Tid: {$time}s\n";
} else {
    echo "✗ OFFLINE\n";
    echo "Fel: $error\n";
}
}