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

// Verificar login
if (!isLoggedIn() || $_SESSION['user']['type'] !== 'admin') {
    header("Location: ../index.php");
    exit();
}

// Processar exclusão de médico
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_doctor'])) {
    $doctor_id = $_POST['delete_doctor'];
    
    $db = Database::getInstance()->getConnection();
    try {
        $db->beginTransaction();
        
        // Remover procedimentos do médico
        $stmt = $db->prepare("DELETE FROM doctor_procedures WHERE doctor_id = :id");
        $stmt->execute([':id' => $doctor_id]);
        
        // Remover horários do médico
        $stmt = $db->prepare("DELETE FROM doctor_schedule WHERE doctor_id = :id");
        $stmt->execute([':id' => $doctor_id]);
        
        // Remover médico
        $stmt = $db->prepare("DELETE FROM doctors WHERE id = :id");
        $stmt->execute([':id' => $doctor_id]);
        
        // Remover usuário
        $stmt = $db->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute([':id' => $doctor_id]);
        
        $db->commit();
        header('Location: ' . $_SERVER['PHP_SELF'] . '?message=' . urlencode('Médico excluído com sucesso!'));
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        $error_message = "Erro ao excluir médico: " . $e->getMessage();
    }
}

$doctors = getAllDoctors();
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lista de Médicos</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">
        <?php if (isset($_GET['message'])): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?= htmlspecialchars($_GET['message']) ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?= htmlspecialchars($error_message) ?></span>
            </div>
        <?php endif; ?>
        
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">Lista de Médicos</h1>
            <a href="cadastro_medico.php" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                Novo Médico
            </a>
        </div>

        <div class="bg-white shadow-md rounded-lg overflow-hidden">
            <table class="min-w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Nome
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Especialidade
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Consultório
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Ações
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($doctors)): ?>
                        <tr>
                            <td colspan="4" class="px-6 py-4 text-center text-gray-500">
                                Nenhum médico cadastrado
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($doctors as $doctor): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?= htmlspecialchars($doctor['name']) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?= htmlspecialchars($doctor['specialty_name'] ?? 'Não definida') ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?= htmlspecialchars($doctor['office_name'] ?? 'Não definido') ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap space-x-2">
                                    <a href="cadastro_medico.php?id=<?= $doctor['id'] ?>" 
                                       class="inline-block bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-3 rounded mr-2">
                                        Editar
                                    </a>
                                    <a href="horarios_medico.php?id=<?= $doctor['id'] ?>" 
                                       class="inline-block bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-3 rounded mr-2">
                                        Horários
                                    </a>
                                    <button onclick="deleteDoctor('<?= $doctor['id'] ?>')" 
                                            class="inline-block bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-3 rounded">
                                        Excluir
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
    function deleteDoctor(doctorId) {
        if (confirm('Tem certeza que deseja excluir este médico?')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '<?= $_SERVER['PHP_SELF'] ?>';
            
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'delete_doctor';
            input.value = doctorId;
            
            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }
    </script>
</body>
</html> 