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

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

    // Inicializar variáveis
    $edit_mode = isset($_GET['id']);
    $doctor = ['name' => '', 'username' => ''];  // Voltando à versão anterior
    $message = '';
    $messageType = '';

    // Carregar dados do médico se estiver no modo de edição
    if ($edit_mode) {
        $doctor = getDoctorById($_GET['id']) ?: $doctor;
    }

    // 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 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();
            $message = "Erro ao excluir médico: " . $e->getMessage();
        }
    }

    // Processar formulário de cadastro/edição
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {
        if (isset($_POST['name'], $_POST['specialty_id'], $_POST['office_id'], $_POST['username'])) {
            $id = $edit_mode ? $_GET['id'] : null;
            
            // Dados do usuário
            $userData = [
                'id' => $id,
                'username' => htmlspecialchars(trim($_POST['username'])),
                'name' => htmlspecialchars(trim($_POST['name'])),
                'type' => 'doctor',
                'office_id' => htmlspecialchars(trim($_POST['office_id']))
            ];
            
            // Adicionar senha apenas se fornecida
            if (!empty($_POST['password'])) {
                $userData['password'] = $_POST['password'];
            }
            
            // Dados do médico
            $doctorData = [
                'id' => $id,
                'name' => htmlspecialchars(trim($_POST['name'])),
                'specialty_id' => htmlspecialchars(trim($_POST['specialty_id'])),
                'whatsapp' => preg_replace('/[^0-9]/', '', $_POST['whatsapp']),
                'email' => htmlspecialchars(trim($_POST['email'])),
                'office_id' => htmlspecialchars(trim($_POST['office_id'])),
                'procedures' => isset($_POST['procedures']) ? $_POST['procedures'] : [],
                'consultation_value' => cleanMonetaryValue($_POST['consultation_value']),
                'consultation_commission' => cleanMonetaryValue($_POST['consultation_commission'])
            ];

            // Validação
            if (empty($userData['name']) || empty($userData['office_id']) || empty($userData['username'])) {
                $message = "Por favor, preencha todos os campos obrigatórios.";
                $messageType = "error";
            } else {
                $result = saveDoctor($doctorData, $userData);
                if ($result['success']) {
                    header("Location: " . $_SERVER['PHP_SELF'] . "?updated=true");
                    exit;
                } else {
                    $message = $result['message'];
                    $messageType = "error";
                    // Se houver dados retornados, usar eles para manter o formulário preenchido
                    if (isset($result['data'])) {
                        $doctor = array_merge($doctor, $result['data']);
                    }
                }
            }
        }
    }

    // Carregar dados para os selects
    $offices = getOffices();
    $procedures = getProcedures();
    $specialties = getSpecialties();
    $doctors = getAllDoctors();

    // Funções de formatação
    function formatWhatsApp($number) {
        $number = preg_replace('/[^0-9]/', '', $number);
        if (strlen($number) === 11) {
            return sprintf('(%s) %s-%s',
                substr($number, 0, 2),
                substr($number, 2, 5),
                substr($number, 7)
            );
        }
        return $number;
    }

?>
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= $edit_mode ? 'Editar' : 'Cadastrar' ?> 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-6">
                <h1 class="text-3xl font-bold"><?= $edit_mode ? 'Editar' : 'Cadastrar' ?> Médico</h1>
                <a href="index.php" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded">
                    Voltar
                </a>
            </div>
            
            <?php if (isset($_GET['updated']) && $_GET['updated'] === 'true'): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                    <strong class="font-bold">Sucesso!</strong>
                    <span class="block sm:inline"> Médico <?= $edit_mode ? 'atualizado' : 'cadastrado' ?> com sucesso!</span>
                </div>
            <?php endif; ?>

            <?php if (!empty($message)): ?>
                <div class="<?= $messageType === 'error' ? 'bg-red-100 border-red-400 text-red-700' : 'bg-green-100 border-green-400 text-green-700' ?> px-4 py-3 rounded relative mb-4" role="alert">
                    <span class="block sm:inline"><?= $message ?></span>
                </div>
            <?php endif; ?>

            <!-- Formulário de Médico -->
            <div class="bg-white shadow rounded-lg p-6 mb-6">
                <h2 class="text-2xl font-bold mb-4">Dados do Médico</h2>
                <form method="post" class="space-y-4">
                    <?php if ($edit_mode): ?>
                        <input type="hidden" name="id" value="<?= $doctor['id'] ?>">
                    <?php endif; ?>

                    <div class="grid md:grid-cols-2 gap-4">
                        <div class="space-y-4">
                            <h2 class="text-xl font-bold mb-4">Dados Pessoais</h2>
                            
                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Nome</label>
                                <input type="text" name="name" 
                                       value="<?= $doctor['name'] ?? '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                       required>
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">WhatsApp</label>
                                <input type="text" name="whatsapp" 
                                       value="<?= $doctor['whatsapp'] ?? '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline phone-mask">
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">E-mail</label>
                                <input type="email" name="email" 
                                       value="<?= $doctor['email'] ?? '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Especialidade</label>
                                <select name="specialty_id" 
                                        class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                                    <option value="">Selecione uma especialidade</option>
                                    <?php foreach ($specialties as $specialty): ?>
                                        <option value="<?= $specialty['id'] ?>" 
                                            <?= ($doctor['specialty_id'] ?? '') === $specialty['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($specialty['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Consultório</label>
                                <select name="office_id" 
                                        class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                        required>
                                    <option value="">Selecione um consultório</option>
                                    <?php foreach ($offices as $office): ?>
                                        <option value="<?= $office['id'] ?>" 
                                            <?= ($doctor['office_id'] ?? '') === $office['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($office['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="space-y-4">
                            <h2 class="text-xl font-bold mb-4">Dados de Acesso</h2>
                            
                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Usuário</label>
                                <input type="text" name="username" 
                                       value="<?= $edit_mode ? ($doctor['username'] ?? '') : '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                       required>
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">
                                    Senha <?= $edit_mode ? '(deixe em branco para manter a atual)' : '' ?>
                                </label>
                                <input type="password" name="password" 
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                       <?= $edit_mode ? '' : 'required' ?>>
                            </div>

                            <h2 class="text-xl font-bold mb-4 mt-8">Dados Financeiros</h2>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Valor da Consulta</label>
                                <input type="text" name="consultation_value" 
                                       value="<?= isset($doctor['consultation_value']) ? formatMoney($doctor['consultation_value']) : '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline money-mask"
                                       required>
                            </div>

                            <div>
                                <label class="block text-gray-700 text-sm font-bold mb-2">Comissão da Consulta</label>
                                <input type="text" name="consultation_commission" 
                                       value="<?= isset($doctor['consultation_commission']) ? formatMoney($doctor['consultation_commission']) : '' ?>"
                                       class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline money-mask"
                                       required>
                            </div>

                            <div class="mb-4">
                                <label class="block text-gray-700 text-sm font-bold mb-2">
                                    Procedimentos
                                </label>
                                <div class="space-y-2 max-h-48 overflow-y-auto p-2 border rounded">
                                    <?php foreach ($procedures as $procedure): ?>
                                        <div class="flex items-center">
                                            <input type="checkbox" 
                                                   name="procedures[]" 
                                                   id="procedure_<?= $procedure['id'] ?>" 
                                                   value="<?= $procedure['id'] ?>"
                                                   class="mr-2"
                                                   <?= isset($doctor['procedures']) && in_array($procedure['id'], $doctor['procedures']) ? 'checked' : '' ?>>
                                            <label for="procedure_<?= $procedure['id'] ?>" class="text-sm">
                                                <?= htmlspecialchars($procedure['name']) ?>
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex justify-end space-x-4 mt-6">
                        <a href="cadastro_medico.php" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded">
                            Cancelar
                        </a>
                        <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                            <?= $edit_mode ? 'Atualizar' : 'Cadastrar' ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Lista de Médicos -->
            <div class="bg-white shadow rounded-lg p-6">
                <h2 class="text-2xl font-bold mb-4">Médicos Cadastrados</h2>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-100">
                                <th class="px-4 py-2 text-left w-1/6">Nome</th>
                                <th class="px-4 py-2 text-left w-1/8">Especialidade</th>
                                <th class="px-4 py-2 text-left w-1/8">Consultório</th>
                                <th class="px-4 py-2 text-left w-1/6">Procedimentos</th>
                                <th class="px-4 py-2 text-left w-1/8">Valor Consulta</th>
                                <th class="px-4 py-2 text-left w-1/8">Comissão</th>
                                <th class="px-4 py-2 text-left w-1/8">WhatsApp</th>
                                <th class="px-4 py-2 text-center w-1/8">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($doctors as $doc): ?>
                                <tr class="border-t hover:bg-gray-50">
                                    <td class="px-4 py-2"><?= htmlspecialchars($doc['name']) ?></td>
                                    <td class="px-4 py-2"><?= htmlspecialchars($doc['specialty_name'] ?? '') ?></td>
                                    <td class="px-4 py-2"><?= htmlspecialchars($doc['office_name'] ?? '') ?></td>
                                    <td class="px-4 py-2"><?= htmlspecialchars($doc['procedures_list'] ?? '') ?></td>
                                    <td class="px-4 py-2"><?= isset($doc['consultation_value']) ? formatMoney($doc['consultation_value']) : 'R$ 0,00' ?></td>
                                    <td class="px-4 py-2"><?= isset($doc['consultation_commission']) ? formatMoney($doc['consultation_commission']) : 'R$ 0,00' ?></td>
                                    <td class="px-4 py-2"><?= isset($doc['whatsapp']) ? htmlspecialchars(formatWhatsApp($doc['whatsapp'])) : '' ?></td>
                                    <td class="px-4 py-2 text-center">
                                        <a href="?id=<?= $doc['id'] ?>" 
                                           class="inline-block bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-3 rounded mr-2">
                                            Editar
                                        </a>
                                        <button onclick="deleteDoctor('<?= $doc['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; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script>
            // Máscara para WhatsApp
            document.querySelectorAll('.phone-mask').forEach(input => {
                input.addEventListener('input', function(e) {
                    let value = e.target.value.replace(/\D/g, '');
                    if (value.length > 11) value = value.slice(0, 11);
                    
                    if (value.length > 0) {
                        value = '(' + value;
                        if (value.length > 3) {
                            value = value.slice(0, 3) + ') ' + value.slice(3);
                        }
                        if (value.length > 10) {
                            value = value.slice(0, 10) + '-' + value.slice(10);
                        }
                    }
                    e.target.value = value;
                });

                // Aplicar máscara inicial se já tiver valor
                if (input.value) {
                    input.dispatchEvent(new Event('input'));
                }
            });

            // Máscara para valores monetários
            document.querySelectorAll('.money-mask').forEach(input => {
                input.addEventListener('input', function(e) {
                    let value = e.target.value.replace(/\D/g, '');
                    
                    // Converter para centavos
                    value = parseInt(value);
                    
                    // Se não for um número válido, zerar
                    if (isNaN(value)) value = 0;
                    
                    // Converter para reais (divisão por 100)
                    value = (value / 100).toFixed(2);
                    
                    // Formatar com pontos e vírgulas
                    value = value.replace('.', ',');
                    value = value.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
                    
                    e.target.value = 'R$ ' + value;
                });

                // Aplicar máscara inicial se já tiver valor
                if (input.value) {
                    input.dispatchEvent(new Event('input'));
                }
            });

            // Função existente de deleteDoctor permanece igual
            function deleteDoctor(id) {
                if (confirm('Tem certeza que deseja excluir este médico?')) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `<input type="hidden" name="delete_doctor" value="${id}">`;
                    document.body.appendChild(form);
                    form.submit();
                }
            }
        </script>
    </body>
    </html>