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

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

// Se tiver ID, buscar dados do paciente
if (isset($_GET['id'])) {
    $patient = getPatientById($_GET['id']);
    if (!$patient) {
        $message = "Paciente não encontrado.";
    }
}

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient = [
        'id' => $_POST['id'] ?? null, // Incluir ID se for edição
        'name' => $_POST['name'],
        'cpf' => $_POST['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 (savePatientData($patient)) {
        header("Location: lista_pacientes.php?success=1");
        exit();
    } else {
        $message = "Erro ao salvar 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">
    <!-- Ajustar CSP para permitir conexão com ViaCEP -->
    <meta http-equiv="Content-Security-Policy" 
          content="default-src 'self' https://cdn.jsdelivr.net; 
                   connect-src 'self' https://viacep.com.br;
                   script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;
                   style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net">
    <title>Cadastro de 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">Cadastro de Paciente</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['success'])): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4">
                <strong class="font-bold">Sucesso!</strong>
                <span class="block sm:inline"> Paciente cadastrado com sucesso!</span>
            </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" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
            <?php if (isset($patient['id'])): ?>
                <input type="hidden" name="id" value="<?= htmlspecialchars($patient['id']) ?>">
            <?php endif; ?>

            <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">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">CPF</label>
                    <input type="text" name="cpf" tabindex="2"
                           value="<?= htmlspecialchars($patient['cpf'] ?? '') ?>"
                           class="cpf-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">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">
                </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">
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Sexo</label>
                    <select name="gender" tabindex="5"
                            value="<?= htmlspecialchars($patient['gender'] ?? '') ?>"
                            class="shadow appearance-none border rounded w-full py-2 px-3">
                        <option value="">Selecione</option>
                        <option value="M">Masculino</option>
                        <option value="F">Feminino</option>
                        <option value="O">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">
                </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">
                </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">
                </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">
                </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">
                    <div id="cep-loading" class="hidden absolute right-2 top-8">
                        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                    </div>
                </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" readonly
                           value="<?= htmlspecialchars($patient['street'] ?? '') ?>"
                           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">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">
                </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">
                </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" readonly
                           value="<?= htmlspecialchars($patient['neighborhood'] ?? '') ?>"
                           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">Cidade</label>
                    <input type="text" name="city" id="city" tabindex="15" readonly
                           value="<?= htmlspecialchars($patient['city'] ?? '') ?>"
                           class="bg-gray-100 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">UF</label>
                    <input type="text" name="state" id="state" tabindex="16" readonly
                           value="<?= htmlspecialchars($patient['state'] ?? '') ?>"
                           class="bg-gray-100 shadow appearance-none border rounded w-full py-2 px-3">
                </div>
                <div class="col-span-2">
                    <label class="block text-gray-700 text-sm font-bold mb-2">Observações</label>
                    <textarea name="notes" rows="1" tabindex="17"
                              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" tabindex="18"
                        value="<?= htmlspecialchars($patient['status'] ?? '') ?>"
                        class="shadow appearance-none border rounded py-2 px-4">
                    <option value="Ativo">Ativo</option>
                    <option value="Inativo">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">
                    Cadastrar
                </button>
            </div>
        </form>
    </div>

    <script>
        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) {
            //Nova variável "cep" somente com dígitos.
            var cep = valor.replace(/\D/g, '');

            //Verifica se campo cep possui valor informado.
            if (cep != "") {
                //Expressão regular para validar o CEP.
                var validacep = /^[0-9]{8}$/;

                //Valida o formato do CEP.
                if(validacep.test(cep)) {
                    //Preenche os campos com "..." enquanto consulta webservice.
                    document.getElementById('street').value = "...";
                    document.getElementById('neighborhood').value = "...";
                    document.getElementById('city').value = "...";
                    document.getElementById('state').value = "...";
                    document.getElementById('complement').value = "...";

                    // Fazer a requisição para nosso endpoint local
                    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;
                                
                                // Foco no número após preencher o endereço
                                document.querySelector('input[name="number"]').focus();
                            } else {
                                limpa_formulario_cep();
                                alert("CEP não encontrado.");
                            }
                        })
                        .catch(error => {
                            limpa_formulario_cep();
                            alert("Erro ao buscar CEP. Tente novamente.");
                        });

                } else {
                    //cep é inválido.
                    limpa_formulario_cep();
                    alert("Formato de CEP inválido.");
                }
            } else {
                //cep sem valor, limpa formulário.
                limpa_formulario_cep();
            }
        }

        // No input do CEP, adicionar o evento onblur
        document.getElementById('cep').addEventListener('blur', function() {
            pesquisacep(this.value);
        });

        // Ajustar apenas a máscara do telefone fixo (phone2)
        document.querySelector('input[name="phone2"]').addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length > 10) value = value.slice(0, 10); // Limita a 10 dígitos
            
            if (value.length > 0) {
                value = '(' + value;
                if (value.length > 3) {
                    value = value.slice(0, 3) + ') ' + value.slice(3);
                }
                if (value.length > 9) {
                    value = value.slice(0, 9) + '-' + value.slice(9);
                }
            }
            e.target.value = value;
        });

        // Manter a máscara original para WhatsApp e Celular (11 dígitos)
        document.querySelectorAll('input[name="whatsapp"], input[name="phone"]').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;
            });
        });

        document.querySelectorAll('.cpf-mask').forEach(input => {
            // Máscara do CPF
            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 > 3) {
                    value = value.slice(0, 3) + '.' + value.slice(3);
                }
                if (value.length > 7) {
                    value = value.slice(0, 7) + '.' + value.slice(7);
                }
                if (value.length > 11) {
                    value = value.slice(0, 11) + '-' + value.slice(11);
                }
                e.target.value = value;
            });

            // Validação quando sair do campo
            input.addEventListener('blur', async function(e) {
                const cpf = e.target.value;
                if (!cpf) return; // Se estiver vazio, não valida
                
                // Primeiro valida o formato do CPF
                if (!validaCPF(cpf)) {
                    alert('CPF inválido! Por favor, verifique.');
                    e.target.value = '';
                    e.target.focus();
                    return;
                }
                
                // Se o CPF for válido, verifica se já existe
                try {
                    const response = await fetch(`verificar_cpf.php?cpf=${cpf}`);
                    const data = await response.json();
                    
                    if (data.exists) {
                        alert(`CPF já cadastrado para o paciente: ${data.name}`);
                        e.target.value = '';
                        e.target.focus();
                    }
                } catch (error) {
                    console.error('Erro ao verificar CPF:', error);
                }
            });
        });

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

        // Adicionar validação de CPF
        function validaCPF(cpf) {
            cpf = cpf.replace(/[^\d]/g, '');
            
            if (cpf.length !== 11) return false;
            
            // Verifica CPFs com dígitos iguais
            if (/^(\d)\1{10}$/.test(cpf)) return false;
            
            // Validação do primeiro dígito
            let soma = 0;
            for (let i = 0; i < 9; i++) {
                soma += parseInt(cpf.charAt(i)) * (10 - i);
            }
            let resto = 11 - (soma % 11);
            let digitoVerificador1 = resto > 9 ? 0 : resto;
            
            if (digitoVerificador1 !== parseInt(cpf.charAt(9))) return false;
            
            // Validação do segundo dígito
            soma = 0;
            for (let i = 0; i < 10; i++) {
                soma += parseInt(cpf.charAt(i)) * (11 - i);
            }
            resto = 11 - (soma % 11);
            let digitoVerificador2 = resto > 9 ? 0 : resto;
            
            return digitoVerificador2 === parseInt(cpf.charAt(10));
        }
    </script>
</body>
</html> 