<?php

set_time_limit(0);

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');

require_once '../../db_connection.php';

$last_event_id = isset($_SERVER['HTTP_LAST_EVENT_ID']) ? intval($_SERVER['HTTP_LAST_EVENT_ID']) : 0;

if ($last_event_id == 0 && isset($_GET['lastEventId'])) {
    $last_event_id = intval($_GET['lastEventId']);
}

$loop_count = 0;
while (true) {
    if (connection_aborted()) {
        break;
    }

    try {
        $sql = "SELECT id, evento_tipo, producto_id, payload, fecha_creacion
                FROM sistema_eventos
                WHERE id > :last_id
                ORDER BY id ASC LIMIT 50";

        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':last_id', $last_event_id, PDO::PARAM_INT);
        $stmt->execute();
        $eventos = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (count($eventos) > 0) {
            foreach ($eventos as $evento) {
                $last_event_id = $evento['id'];

                $data = [
                    'id' => $evento['id'],
                    'tipo' => $evento['evento_tipo'],
                    'producto_id' => $evento['producto_id'],
                    'payload' => $evento['payload'] ? json_decode($evento['payload'], true) : null,
                    'fecha' => $evento['fecha_creacion']
                ];

                echo "id: " . $evento['id'] . "\n";
                echo "event: " . $evento['evento_tipo'] . "\n";
                echo "data: " . json_encode($data) . "\n\n";
            }

            ob_flush();
            flush();
        } else {
            echo ": heartbeat\n\n";
            ob_flush();
            flush();
        }

    } catch (Exception $e) {
        error_log("Error en SSE: " . $e->getMessage());
        sleep(5);
    }

    $loop_count++;
    if ($loop_count % 60 === 0) {
        $lockFile = sys_get_temp_dir() . '/sufarma_mantenimiento.lock';
        $fp = fopen($lockFile, 'c+');

        if (flock($fp, LOCK_EX | LOCK_NB)) {
            $lastMaint = (int)fgets($fp);
            if (time() - $lastMaint > 60) {
                try {
                    $pdo->exec("DELETE FROM sistema_eventos WHERE fecha_creacion < NOW() - INTERVAL 24 HOUR");
                    $pdo->exec("DELETE FROM logs WHERE fecha < NOW() - INTERVAL 30 DAY");

                    ftruncate($fp, 0);
                    rewind($fp);
                    fwrite($fp, time());
                } catch (Exception $e) {
                    error_log("Error en mantenimiento SSE: " . $e->getMessage());
                }
            }
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

    sleep(2);
}
