<?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();
}

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient = [
        'id' => $_POST['id'],
        'name' => $_POST['name'],
        'cpf' => $_POST['cpf'], // Mantém o mesmo CPF
        'rg' => $_POST['rg'],
        'birth_date' => $_POST['birth_date'],
        'gender' => $_POST['gender'],
        'email' => $_POST['email'],
        'whatsapp' => $_POST['whatsapp'],
        'phone' => $_POST['phone'],
        'phone2' => $_POST['phone2'],
        'cep' => $_POST['cep'],
        'street' => $_POST['street'],
        'number' => $_POST['number'],
        'complement' => $_POST['complement'],
        'neighborhood' => $_POST['neighborhood'],
        'city' => $_POST['city'],
        'state' => $_POST['state'],
        'notes' => $_POST['notes'],
        'status' => $_POST['status']
    ];

    if (updatePatient($patient)) {
        header("Location: lista_pacientes.php?success=1");
        exit();
    } else {
        $message = "Erro ao atualizar paciente. Por favor, tente novamente.";
    }
}
?>

<!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 ($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" 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 tabindex="1"
                           value="<?= htmlspecialchars($patient['name']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">CPF</label>
                    <input type="text" disabled tabindex="2"
                           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" tabindex="3"
                           value="<?= htmlspecialchars($patient['rg']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </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" tabindex="4"
                           value="<?= htmlspecialchars($patient['birth_date']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Sexo</label>
                    <select name="gender" tabindex="5"
                            class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                        <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" tabindex="6"
                           value="<?= htmlspecialchars($patient['email']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </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" tabindex="7"
                           value="<?= htmlspecialchars($patient['whatsapp']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Celular</label>
                    <input type="text" name="phone" tabindex="8"
                           value="<?= htmlspecialchars($patient['phone']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Telefone</label>
                    <input type="text" name="phone2" tabindex="9"
                           value="<?= htmlspecialchars($patient['phone2']) ?>"
                           class="phone-mask shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
            </div>

            <div class="grid grid-cols-3 gap-4 mb-4">
                <div class="relative">
                    <label class="block text-gray-700 text-sm font-bold mb-2">CEP</label>
                    <input type="text" name="cep" id="cep" tabindex="10"
                           value="<?= htmlspecialchars($patient['cep']) ?>"
                           class="cep-mask shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Logradouro</label>
                    <input type="text" name="street" id="street" tabindex="11"
                           value="<?= htmlspecialchars($patient['street']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Número</label>
                    <input type="text" name="number" tabindex="12"
                           value="<?= htmlspecialchars($patient['number']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </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" tabindex="13"
                           value="<?= htmlspecialchars($patient['complement']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Bairro</label>
                    <input type="text" name="neighborhood" id="neighborhood" tabindex="14"
                           value="<?= htmlspecialchars($patient['neighborhood']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Cidade</label>
                    <input type="text" name="city" id="city" tabindex="15"
                           value="<?= htmlspecialchars($patient['city']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </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">Estado</label>
                    <input type="text" name="state" id="state" tabindex="16"
                           value="<?= htmlspecialchars($patient['state']) ?>"
                           class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>
                <div class="col-span-2">
                    <label class="block text-gray-700 text-sm font-bold mb-2">Observações</label>
                    <textarea name="notes" tabindex="17" rows="3"
                              class="shadow appearance-none border rounded w-full py-2 px-3 focus:ring-2 focus:ring-blue-500 focus:outline-none"><?= htmlspecialchars($patient['notes']) ?></textarea>
                </div>
            </div>

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

    <script>
        // Funções de máscara e CEP
        function limpa_formulario_cep() {
            document.getElementById('street').value = '';
            document.getElementById('neighborhood').value = '';
            document.getElementById('city').value = '';
            document.getElementById('state').value = '';
            document.getElementById('complement').value = '';
        }

        function pesquisacep(valor) {
            var cep = valor.replace(/\D/g, '');
            if (cep != "") {
                var validacep = /^[0-9]{8}$/;
                if(validacep.test(cep)) {
                    fetch(`buscar_cep.php?cep=${cep}`)
                        .then(response => response.json())
                        .then(data => {
                            if (!("erro" in data)) {
                                document.getElementById('street').value = data.logradouro;
                                document.getElementById('neighborhood').value = data.bairro;
                                document.getElementById('city').value = data.localidade;
                                document.getElementById('state').value = data.uf;
                                document.getElementById('complement').value = data.complemento;
                            } else {
                                limpa_formulario_cep();
                                alert("CEP não encontrado.");
                            }
                        })
                        .catch(error => {
                            limpa_formulario_cep();
                            alert("Erro ao buscar CEP. Tente novamente.");
                        });
                }
            }
        }

        document.getElementById('cep').addEventListener('blur', function() {
            pesquisacep(this.value);
        });

        // Máscaras de telefone
        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;
            });
        });

        // Máscara do CEP
        document.querySelectorAll('.cep-mask').forEach(input => {
            input.addEventListener('input', function(e) {
                let value = e.target.value.replace(/\D/g, '');
                if (value.length > 8) value = value.slice(0, 8);
                
                if (value.length > 5) {
                    value = value.slice(0, 5) + '-' + value.slice(5);
                }
                e.target.value = value;
            });
        });
    </script>
</body>
</html> 