<?php
require_once __DIR__ . '/guard.php';
require_login();

// Frigiv session-låsen INDEN vi starter det langkørende SSE-script
if (session_status() === PHP_SESSION_ACTIVE) session_write_close();

ignore_user_abort(true);
set_time_limit(0);

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // undgå proxy-buffering hvis muligt

$log  = dirname(__DIR__) . '/data/bot.log';
$last = '';

while (true) {
    $tail = '';
    if (file_exists($log)) {
        $data = @file($log);
        if ($data) {
            // vis de sidste ~80 linjer
            $tail = implode("", array_slice($data, -80));
        }
    }
    if ($tail !== $last) {
        echo "event: log\n";
        echo "data: " . str_replace("\n", "\\n", $tail) . "\n\n";
        @ob_flush();
        @flush();
        $last = $tail;
    }
    usleep(500000); // 0,5s
}
