<?php
require_once 'db_pdo.php';

// Ajustes para streaming continuo
@ini_set('max_execution_time', 0);
@ini_set('zlib.output_compression', 0);
@ini_set('output_buffering', 0);
@ini_set('implicit_flush', 1);
ignore_user_abort(true);
while (ob_get_level() > 0) {
    ob_end_flush();
}
ob_implicit_flush(1);

// Headers SSE
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

// Si usás sesiones en otras páginas, cerralas acá
if (session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

$eleccion_id = (int)($_GET['eleccion_id'] ?? 1);
$cargo_id    = (int)($_GET['cargo_id'] ?? 1);
$lastSent = 0;

function sendEvent($type, $data)
{
    echo "event: {$type}\n";
    echo 'data: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
    echo str_repeat(' ', 1024) . "\n"; // padding contra buffers
    @flush();
    @ob_flush();
}

while (true) {
    try {
        $stmt = $GLOBALS['pdo']->prepare("SELECT MAX(id) FROM resultado_partido_mesa WHERE eleccion_id=:e AND cargo_id=:c");
        $stmt->execute([':e' => $eleccion_id, ':c' => $cargo_id]);
        $last = (int)$stmt->fetchColumn();

        if ($last > $lastSent) {
            $lastSent = $last;
            sendEvent('ping', ['last_id' => $last]);
        } else {
            sendEvent('heartbeat', ['ts' => time()]);
        }
    } catch (Throwable $e) {
        sendEvent('error', ['msg' => 'SSE error', 'detail' => $e->getMessage()]);
    }

    sleep(3);
    if (connection_aborted()) break;
}
