<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

require_once '../config/config.php';
require_once '../config/database.php';

while (true) {
    $database = new Database();
    $db = $database->getConnection();
    
    $query = "SELECT 
                f.id,
                p.nome as paciente_nome,
                c.descricao as consultorio_descricao,
                u.nome as medico_nome,
                m.foto as medico_foto,
                f.called_at
              FROM fila_atendimento f
              JOIN pacientes p ON f.paciente_id = p.id
              JOIN medicos m ON f.medico_id = m.id
              JOIN usuarios u ON m.usuario_id = u.id
              JOIN consultorios c ON f.consultorio_id = c.id
              WHERE f.status = 'chamado'
              AND DATE(f.called_at) = CURDATE()
              ORDER BY f.called_at DESC
              LIMIT 10";

    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $chamadas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $response = [
        'novas_chamadas' => !empty($chamadas),
        'chamada_atual' => empty($chamadas) ? null : $chamadas[0],
        'ultimas_chamadas' => array_slice($chamadas, 1)
    ];
    
    echo "data: " . json_encode($response) . "\n\n";
    ob_flush();
    flush();
    
    sleep(1);
} 