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

// Verificar login e permissões de médico
if (!isLoggedIn() || $_SESSION['user']['type'] !== 'doctor') {
    header("Location: ../index.php");
    exit();
}

// Habilitar exibição de erros para debug
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    $doctor_id = $_SESSION['user']['id'];
    $office_id = $_SESSION['user']['office_id'];

    // Buscar dados do médico
    $doctor = getDoctorById($doctor_id);
    if (!$doctor) {
        throw new Exception('Médico não encontrado');
    }

    // Buscar pacientes aguardando
    $waiting_patients = getWaitingPatients($office_id);

    // Buscar pacientes chamados
    $called_patients = getCalledPatients($office_id);

    // Processar chamada de paciente
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['call_patient_id'])) {
        if (callPatient($_POST['call_patient_id'])) {
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        }
    }
} catch (Exception $e) {
    error_log("Erro na página do médico: " . $e->getMessage());
    die("Ocorreu um erro ao carregar os dados. Por favor, tente novamente mais tarde.");
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel do Médico</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">
            <div>
                <h1 class="text-3xl font-bold mb-2">
                    Dr<?= $doctor['name'] ? ($doctor['name'] ? '(a)' : '') : '' ?> <?= htmlspecialchars($doctor['name']) ?>
                </h1>
                <p class="text-gray-600">
                    <?= htmlspecialchars($doctor['specialty_name']) ?> - 
                    <?= htmlspecialchars($doctor['office_name']) ?>
                </p>
            </div>
            <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">
                Sair
            </a>
        </div>

        <!-- Pacientes Aguardando -->
        <div class="bg-white shadow rounded-lg p-6 mb-6">
            <h2 class="text-2xl font-bold mb-4">Pacientes Aguardando</h2>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="px-4 py-2 text-left">Nome</th>
                            <th class="px-4 py-2 text-left">Chegada</th>
                            <th class="px-4 py-2 text-left">Tipo</th>
                            <th class="px-4 py-2 text-left">Procedimento</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"><?= $patient['arrival_time'] ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['attendance_type']) ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['procedure_name'] ?? '-') ?></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'] ?>">
                                        <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="6" class="text-center py-4 text-gray-500">
                                    Nenhum paciente aguardando
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pacientes Chamados Hoje -->
        <div class="bg-white shadow rounded-lg p-6">
            <h2 class="text-2xl font-bold mb-4">Atendimentos de Hoje</h2>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="px-4 py-2 text-left">Nome</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>
                            <th class="px-4 py-2 text-left">Tipo</th>
                            <th class="px-4 py-2 text-left">Procedimento</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"><?= $patient['arrival_time'] ?></td>
                                <td class="px-4 py-2"><?= $patient['called_time'] ?></td>
                                <td class="px-4 py-2"><?= $patient['waiting_time'] ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['attendance_type']) ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($patient['procedure_name'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($called_patients)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-gray-500">
                                    Nenhum paciente chamado hoje
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // Atualizar a página a cada 30 segundos
        setInterval(function() {
            window.location.reload();
        }, 30000);
    </script>
</body>
</html>