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

// Verificar login
if (!isLoggedIn()) {
    header("Location: index.php");
    exit();
}

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

// Processar requisições
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Adicionar novo paciente
    if (isset($_POST['patient_name'])) {
        $data = [
            'id' => uniqid(),
            'name' => $_POST['patient_name'],
            'office_id' => $_POST['office_id'],
            'priority' => $_POST['priority'] ?? 'Padrao',
            'arrival_time' => date('H:i:s'),
            'called' => 0,
            'displayed' => 0
        ];
        
        try {
            $db->insert('patients', $data);
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        } catch (Exception $e) {
            $error = "Erro ao adicionar paciente";
        }
    }

    // Chamar paciente
    if (isset($_POST['call_patient_id'])) {
        try {
            $db->update('patients', 
                [
                    'called' => 1,
                    'called_time' => date('H:i:s'),
                    'waiting_time' => calculateWaitingTime($_POST['arrival_time'], date('H:i:s'))
                ],
                ['id' => $_POST['call_patient_id']]
            );
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        } catch (Exception $e) {
            $error = "Erro ao chamar paciente";
        }
    }

    // Limpar pacientes chamados
    if (isset($_POST['clear_called'])) {
        try {
            $db->query("DELETE FROM patients WHERE called = 1");
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        } catch (Exception $e) {
            $error = "Erro ao limpar pacientes";
        }
    }
}

// Buscar consultórios
$offices = getOffices();

// Buscar pacientes aguardando
$stmt = $db->query("
    SELECT p.*, o.name as office_name 
    FROM patients p
    LEFT JOIN offices o ON o.id = p.office_id
    WHERE p.called = 0
    ORDER BY 
        CASE p.priority 
            WHEN 'Alta' THEN 1 
            WHEN 'Media' THEN 2 
            ELSE 3 
        END,
        p.arrival_time ASC
");
$waiting_patients = $stmt->fetchAll();

// Buscar pacientes chamados
$stmt = $db->query("
    SELECT p.*, o.name as office_name 
    FROM patients p
    LEFT JOIN offices o ON o.id = p.office_id
    WHERE p.called = 1
    ORDER BY p.called_time DESC
");
$called_patients = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Chamada de Pacientes</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold">Painel de Chamada</h1>
            <a href="logout.php" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">
                Sair
            </a>
        </div>

        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <!-- Formulário para adicionar paciente -->
        <div class="bg-white shadow rounded-lg p-6 mb-8">
            <h2 class="text-xl font-bold mb-4">Adicionar Paciente</h2>
            <form method="post" class="space-y-4">
                <div class="grid md:grid-cols-3 gap-4">
                    <div>
                        <label class="block mb-2">Nome do Paciente</label>
                        <input type="text" name="patient_name" required
                               class="w-full border rounded py-2 px-3">
                    </div>
                    <div>
                        <label class="block mb-2">Consultório</label>
                        <select name="office_id" required
                                class="w-full border rounded py-2 px-3">
                            <?php foreach ($offices as $office): ?>
                                <option value="<?= $office['id'] ?>">
                                    <?= htmlspecialchars($office['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block mb-2">Prioridade</label>
                        <select name="priority" class="w-full border rounded py-2 px-3">
                            <option value="Padrao">Padrão</option>
                            <option value="Media">Média</option>
                            <option value="Alta">Alta</option>
                        </select>
                    </div>
                </div>
                <button type="submit" 
                        class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                    Adicionar Paciente
                </button>
            </form>
        </div>

        <!-- Lista de pacientes aguardando -->
        <div class="bg-white shadow rounded-lg p-6 mb-8">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold">Fila de Espera</h2>
                <form method="post" class="inline">
                    <input type="hidden" name="clear_called" value="1">
                    <button type="submit" 
                            class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">
                        Limpar Chamados
                    </button>
                </form>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-4 py-2 text-left">Nome</th>
                            <th class="px-4 py-2 text-left">Consultório</th>
                            <th class="px-4 py-2 text-left">Chegada</th>
                            <th class="px-4 py-2 text-left">Prioridade</th>
                            <th class="px-4 py-2 text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($waiting_patients as $patient): ?>
                            <tr class="border-t">
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['office_name']) ?></td>
                                <td class="px-4 py-2"><?= $patient['arrival_time'] ?></td>
                                <td class="px-4 py-2">
                                    <span class="<?= getPriorityClass($patient['priority']) ?>">
                                        <?= $patient['priority'] ?>
                                    </span>
                                </td>
                                <td class="px-4 py-2 text-center">
                                    <form method="post" class="inline">
                                        <input type="hidden" name="call_patient_id" 
                                               value="<?= $patient['id'] ?>">
                                        <input type="hidden" name="arrival_time" 
                                               value="<?= $patient['arrival_time'] ?>">
                                        <button type="submit" 
                                                class="bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-3 rounded">
                                            Chamar
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($waiting_patients)): ?>
                            <tr>
                                <td colspan="5" class="px-4 py-4 text-center text-gray-500">
                                    Nenhum paciente aguardando
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Lista de pacientes chamados -->
        <div class="bg-white shadow rounded-lg p-6">
            <h2 class="text-xl font-bold mb-4">Pacientes Chamados</h2>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-4 py-2 text-left">Nome</th>
                            <th class="px-4 py-2 text-left">Consultório</th>
                            <th class="px-4 py-2 text-left">Chegada</th>
                            <th class="px-4 py-2 text-left">Chamada</th>
                            <th class="px-4 py-2 text-left">Espera</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($called_patients as $patient): ?>
                            <tr class="border-t">
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['office_name']) ?></td>
                                <td class="px-4 py-2"><?= $patient['arrival_time'] ?></td>
                                <td class="px-4 py-2"><?= $patient['called_time'] ?></td>
                                <td class="px-4 py-2"><?= $patient['waiting_time'] ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($called_patients)): ?>
                            <tr>
                                <td colspan="5" class="px-4 py-4 text-center text-gray-500">
                                    Nenhum paciente chamado
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <?php
    function getPriorityClass($priority) {
        switch ($priority) {
            case 'Alta':
                return 'text-red-600 font-bold';
            case 'Media':
                return 'text-yellow-600';
            default:
                return 'text-green-600';
        }
    }
    ?>
</body>
</html>