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

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

$message = '';
$patient = [];

// Verificar se recebeu ID
if (!isset($_GET['id'])) {
    header("Location: lista_pacientes.php");
    exit();
}

// Buscar dados do paciente
$patient = getPatientById($_GET['id']);
if (!$patient) {
    header("Location: lista_pacientes.php");
    exit();
}

// Debug para verificar os dados
error_log('Patient data in edit page: ' . print_r($patient, true));

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Debug dos dados do POST
        error_log('POST data: ' . print_r($_POST, true));
        
        $patient = [
            'id' => $_POST['id'],
            'name' => trim($_POST['name']),
            'cpf' => $_POST['cpf'],
            'rg' => $_POST['rg'],
            'birth_date' => $_POST['birth_date'],
            'gender' => $_POST['gender'],
            'email' => trim($_POST['email']),
            'whatsapp' => $_POST['whatsapp'],
            'phone' => $_POST['phone'],
            'phone2' => $_POST['phone2'],
            'cep' => $_POST['cep'],
            'street' => trim($_POST['street']),
            'number' => trim($_POST['number']),
            'complement' => trim($_POST['complement']),
            'neighborhood' => trim($_POST['neighborhood']),
            'city' => trim($_POST['city']),
            'state' => trim($_POST['state']),
            'notes' => trim($_POST['notes']),
            'status' => $_POST['status']
        ];

        if (updatePatient($patient)) {
            header("Location: lista_pacientes.php?success=1");
            exit();
        } else {
            throw new Exception("Erro ao atualizar paciente");
        }
    } catch (Exception $e) {
        error_log("Erro na página de edição: " . $e->getMessage());
        $message = "Erro ao atualizar paciente: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Paciente</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">Editar Paciente</h1>
            <a href="lista_pacientes.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['success'])): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4">
                Paciente atualizado com sucesso!
            </div>
        <?php endif; ?>

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

        <form method="post" id="patientForm" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
            <input type="hidden" name="id" value="<?= htmlspecialchars($patient['id']) ?>">
            <input type="hidden" name="cpf" value="<?= htmlspecialchars($patient['cpf']) ?>">
            
            <div class="grid grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Nome</label>
                    <input type="text" name="name" required
                           value="<?= htmlspecialchars($patient['name']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">CPF</label>
                    <input type="text" disabled
                           value="<?= formatCPF($patient['cpf']) ?>"
                           class="bg-gray-100 shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">RG</label>
                    <input type="text" name="rg"
                           value="<?= htmlspecialchars($patient['rg']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
            </div>

            <div class="grid grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Data de Nascimento</label>
                    <input type="date" name="birth_date" required
                           value="<?= htmlspecialchars($patient['birth_date']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Sexo</label>
                    <select name="gender" required
                            class="shadow appearance-none border rounded w-full py-2 px-3">
                        <option value="">Selecione</option>
                        <option value="M" <?= $patient['gender'] == 'M' ? 'selected' : '' ?>>Masculino</option>
                        <option value="F" <?= $patient['gender'] == 'F' ? 'selected' : '' ?>>Feminino</option>
                        <option value="O" <?= $patient['gender'] == 'O' ? 'selected' : '' ?>>Outro</option>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">E-mail</label>
                    <input type="email" name="email"
                           value="<?= htmlspecialchars($patient['email']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
            </div>

            <div class="grid grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">WhatsApp</label>
                    <input type="text" name="whatsapp"
                           value="<?= htmlspecialchars($patient['whatsapp']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Celular</label>
                    <input type="text" name="phone"
                           value="<?= htmlspecialchars($patient['phone']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Telefone</label>
                    <input type="text" name="phone2"
                           value="<?= htmlspecialchars($patient['phone2']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3">
                </div>
            </div>

            <div class="grid grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">CEP</label>
                    <input type="text" name="cep" id="cep"
                           value="<?= htmlspecialchars($patient['cep']) ?>"
                           class="cep-mask shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Logradouro</label>
                    <input type="text" name="street" id="street"
                           value="<?= htmlspecialchars($patient['street']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Número</label>
                    <input type="text" name="number"
                           value="<?= htmlspecialchars($patient['number']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
            </div>

            <div class="grid grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Complemento</label>
                    <input type="text" name="complement" id="complement"
                           value="<?= htmlspecialchars($patient['complement']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Bairro</label>
                    <input type="text" name="neighborhood" id="neighborhood"
                           value="<?= htmlspecialchars($patient['neighborhood']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Cidade</label>
                    <input type="text" name="city" id="city"
                           value="<?= htmlspecialchars($patient['city']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
            </div>

            <div class="grid grid-cols-2 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">UF</label>
                    <input type="text" name="state" id="state"
                           value="<?= htmlspecialchars($patient['state']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Observações</label>
                    <textarea name="notes" rows="1"
                              class="shadow appearance-none border rounded w-full py-2 px-3"><?= htmlspecialchars($patient['notes']) ?></textarea>
                </div>
            </div>

            <div class="flex justify-end gap-4">
                <select name="status"
                        class="shadow appearance-none border rounded py-2 px-4">
                    <option value="Ativo" <?= $patient['status'] == 'Ativo' ? 'selected' : '' ?>>Ativo</option>
                    <option value="Inativo" <?= $patient['status'] == 'Inativo' ? 'selected' : '' ?>>Inativo</option>
                </select>
                <button type="submit"
                        class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                    Salvar Alterações
                </button>
            </div>
        </form>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-mask-plugin@1.14.16/dist/jquery.mask.min.js"></script>
    <script>
        jQuery(document).ready(function($) {
            // Aplicar máscaras
            $('.phone-mask').mask('(00) 00000-0000');
            $('.cep-mask').mask('00000-000');
            $('input[name="rg"]').mask('00.000.000-0');

            // Variável para controlar mudanças no formulário
            let formChanged = false;
            let isSubmitting = false;

            // Detectar mudanças no formulário
            $('#patientForm').on('change', function() {
                formChanged = true;
            });

            // Detectar submit do formulário
            $('#patientForm').on('submit', function() {
                isSubmitting = true;
            });

            // Confirmar antes de sair
            window.addEventListener('beforeunload', function(e) {
                if (formChanged && !isSubmitting) {
                    e.preventDefault();
                    e.returnValue = '';
                }
            });

            // Busca de CEP
            $('#cep').blur(function() {
                var cep = $(this).val().replace(/\D/g, '');
                if (cep != "") {
                    var validacep = /^[0-9]{8}$/;
                    if(validacep.test(cep)) {
                        $.getJSON("buscar_cep.php?cep=" + cep, function(data) {
                            if (!("erro" in data)) {
                                $('#street').val(data.logradouro);
                                $('#neighborhood').val(data.bairro);
                                $('#city').val(data.localidade);
                                $('#state').val(data.uf);
                                $('#complement').val(data.complemento);
                            } else {
                                limpa_formulario_cep();
                                alert("CEP não encontrado.");
                            }
                        }).fail(function() {
                            limpa_formulario_cep();
                            alert("Erro ao buscar CEP. Tente novamente.");
                        });
                    }
                }
            });

            // Validação do formulário
            $('#patientForm').on('submit', function(e) {
                const name = $('input[name="name"]').val().trim();
                const birthDate = $('input[name="birth_date"]').val();
                const gender = $('select[name="gender"]').val();
                
                let errors = [];
                
                if (name.length < 3) {
                    errors.push("Nome deve ter pelo menos 3 caracteres");
                }
                
                if (!birthDate) {
                    errors.push("Data de nascimento é obrigatória");
                } else {
                    const date = new Date(birthDate);
                    const today = new Date();
                    if (date > today) {
                        errors.push("Data de nascimento não pode ser no futuro");
                    }
                }
                
                if (!gender) {
                    errors.push("Sexo é obrigatório");
                }
                
                if (errors.length > 0) {
                    e.preventDefault();
                    alert("Por favor, corrija os seguintes erros:\n\n" + errors.join("\n"));
                    return false;
                }
                
                formChanged = false;
                return true;
            });
        });

        function limpa_formulario_cep() {
            $('#street').val('');
            $('#neighborhood').val('');
            $('#city').val('');
            $('#state').val('');
            $('#complement').val('');
        }
    </script>
</body>
</html> 