<?php
// progress-sse.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');

set_time_limit(0);

$sid = preg_replace('/[^a-zA-Z0-9_-]/', '', $_GET['sid'] ?? uniqid('bulk_'));
$progress_file = __DIR__ . "/progress_{$sid}.json";

function send_sse($event = 'message', $data) {
    echo "event: $event\n";
    echo "data: " . json_encode($data) . "\n\n";
    flush();
}

send_sse('connected', ['message' => 'Terhubung ke stream progress']);

$last_mtime = 0;
while (true) {
    clearstatcache();
    if (file_exists($progress_file)) {
        $current_mtime = filemtime($progress_file);
        if ($current_mtime > $last_mtime) {
            $content = @file_get_contents($progress_file);
            $data = json_decode($content, true) ?: [];
            send_sse('progress', $data);
            $last_mtime = $current_mtime;
        }
    }
    send_sse('heartbeat', ['time' => time()]);
    sleep(1);
}