<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

$db = Database::getInstance()->getConnection();

// Buscar próximo paciente chamado não exibido
$stmt = $db->query("
    SELECT p.*, o.name as office_name
    FROM patients p
    JOIN offices o ON o.id = p.office_id
    WHERE p.called = 1 
    AND p.displayed = 0
    ORDER BY p.called_time DESC
    LIMIT 1
");
$next_patient = $stmt->fetch();

// Buscar contagem de pacientes aguardando por consultório
$stmt = $db->query("
    SELECT o.name as office_name, COUNT(*) as waiting
    FROM patients p
    JOIN offices o ON o.id = p.office_id
    WHERE p.called = 0
    GROUP BY p.office_id, o.name
    ORDER BY o.name
");
$waiting_counts = $stmt->fetchAll();

// Marcar paciente como exibido
if ($next_patient) {
    $stmt = $db->prepare("UPDATE patients SET displayed = 1 WHERE id = :id");
    $stmt->execute([':id' => $next_patient['id']]);
}

echo json_encode([
    'next_patient' => $next_patient,
    'waiting_counts' => $waiting_counts
]); 