<h2 class="page-title">Crear Usuario Comunidad</h2>
<p class="text-muted">Verifique si el usuario ya se encuentra registrado ingresando su DNI.</p>

<div class="row">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">Formulario</strong>
            </div>
            <div class="card-body">
                <form action="<?= BASE_ACTION ?>comunity-users" method="POST">
                    
                    <input type="hidden" name="role" value="COMUNITY">

                    <h5 class="mb-3">Documento de Identidad</h5>
                    <div class="form-group">
                        <label for="dni">DNI/RUC</label>
                        <div class="input-group">
                            <input type="text" name="dni" class="form-control" id="dni">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-info" id="btnBuscarDni">Buscar</button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="formContainer" style="display: none;">

                        <h5 class="mb-3 mt-4">Tipo</h5>
                        <div class="form-group">
                            <label for="person_type">Tipo de Persona</label>
                            <div>
                                <?php foreach ($personTypes as $personType): ?>
                                    <div class="form-check">
                                        <input type="checkbox" name="person_types[]" value="<?= htmlspecialchars($personType->id) ?>" class="form-check-input" id="person_type_<?= $personType->id ?>">
                                        <label class="form-check-label" for="person_type_<?= $personType->id ?>">
                                            <?= htmlspecialchars($personType->description) ?>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <h5 class="mb-3 mt-4">Datos Personales</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="paternal_surname">Apellido Paterno</label>
                                    <input type="text" name="paternal_surname" class="form-control" id="paternal_surname">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="maternal_surname">Apellido Materno</label>
                                    <input type="text" name="maternal_surname" class="form-control" id="maternal_surname">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="name">Nombre</label>
                            <input type="text" name="name" class="form-control" id="name">
                        </div>

                        <div class="form-group">
                            <label for="company_name">Razón Social</label>
                            <input type="text" name="company_name" class="form-control" id="company_name">
                        </div>
                        <!-- <div class="form-group">
                            <label for="ruc">RUC</label>
                            <input type="text" name="ruc" class="form-control" id="ruc">
                        </div> -->
                        <div class="form-group">
                            <label for="phone">Teléfono</label>
                            <input type="text" name="phone" class="form-control" id="phone" required>
                            <div class="form-text text-muted">Ingrese solo el número sin el código de país. Ejemplo: 987654321</div>
                        </div>
                        <div class="form-group">
                            <label for="email">Correo</label>
                            <input type="email" name="email" class="form-control" id="email" required>
                        </div>
                        <div class="form-group">
                            <label for="address">Dirección</label>
                            <textarea name="address" class="form-control" id="address" rows="2"></textarea>
                        </div>
                        <div class="mb-3 d-none" id="school_name_container">
                            <label for="school_name" class="form-label">Nombre de la Institución Educativa</label>
                            <input type="text" name="school_name" id="school_name" class="form-control">
                        </div>

                        <h5 class="mb-3 mt-4">Credenciales</h5>
                        <div id="credentialsContainer" style="display: none;">
                            <div class="form-group">
                                <label for="username">Usuario</label>
                                <input type="text" name="username" class="form-control" id="username" required>
                            </div>
                            <div class="form-group">
                                <label for="password">Contraseña</label>
                                <input type="password" name="password" class="form-control" id="password" required>
                                <div id="password_requirements" class="mt-2 text-muted small">
                                    <div id="req-length">✘ Mínimo 8 caracteres</div>
                                    <div id="req-alphanumeric">✘ Contener letras y números</div>
                                    <div id="req-no-special">✘ Sin caracteres especiales</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-start">
                            <a href="<?= BASE_HREF ?>comunity-users" class="btn btn-secondary mr-2">Cancelar</a>
                            <button type="submit" class="btn btn-primary">Guardar</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const dni = document.getElementById('dni');
    const paternalSurname = document.getElementById('paternal_surname');
    const maternalSurname = document.getElementById('maternal_surname');
    const name = document.getElementById('name');
    // const ruc = document.getElementById('ruc');
    const companyName = document.getElementById('company_name');
    const schoolNameContainer = document.getElementById('school_name_container');
    const schoolName = document.getElementById('school_name');
    const phone = document.getElementById('phone');
    const address = document.getElementById('address');
    const username = document.getElementById('username');
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirm_password');

    const reqLength = document.getElementById("req-length");
    const reqAlphanumeric = document.getElementById("req-alphanumeric");
    const reqNoSpecial = document.getElementById("req-no-special");

    const personTypeCheckboxes = document.querySelectorAll('input[name="person_types[]"]');

    document.querySelectorAll("input[required], select[required], textarea[required]").forEach(function (input) {
      let label = document.querySelector(`label[for="${input.id}"]`);
      if (label && !label.innerHTML.includes("*")) {
        label.innerHTML += ' <span class="text-danger">*</span>';
      }
    });

    function updatePasswordRequirements() {
      const value = password ? password.value : "";
      const hasMinLength = value.length >= 8;
      const hasLetters = /[a-zA-Z]/.test(value);
      const hasNumbers = /\d/.test(value);
      const onlyAlphanumeric = /^[a-zA-Z0-9]*$/.test(value);

      updateRequirement(reqLength, hasMinLength);
      updateRequirement(reqAlphanumeric, hasLetters && hasNumbers);
      updateRequirement(reqNoSpecial, onlyAlphanumeric);
    }

    function updateRequirement(element, condition) {
      if (!element) return;
      element.textContent = element.textContent.replace(/^(✔|✘)/, condition ? "✔" : "✘");
      element.classList.toggle("text-success", condition);
      element.classList.toggle("text-danger", !condition);
    }

    if (password) {
      password.addEventListener("input", updatePasswordRequirements);
      password.dispatchEvent(new Event("input"));
    }

    [username, password, confirmPassword, name, paternalSurname, maternalSurname, companyName, address, schoolName].forEach(el => {
      if (el) {
        el.addEventListener('input', e => {
          e.target.value = e.target.value.toUpperCase();
        });
      }
    });

    // if (dni) {
    //   dni.addEventListener('input', () => {
    //     dni.value = dni.value.replace(/\D/g, '').slice(0, 8);
    //   });
    // }

    // if (ruc) {
    //   ruc.addEventListener('input', () => {
    //     ruc.value = ruc.value.replace(/\D/g, '').slice(0, 20);
    //   });
    // }

    if (phone) {
      phone.addEventListener('input', () => {
        phone.value = phone.value.replace(/\D/g, '').slice(0, 9);
      });
    }

    function updateFieldRequirements() {
      const selectedTypes = Array.from(personTypeCheckboxes)
        .filter(cb => cb.checked)
        .map(cb => cb.nextElementSibling.textContent.trim().toLowerCase());

      const isNaturalOrDocente = selectedTypes.includes('natural') || selectedTypes.includes('docente');
      const isJuridica = selectedTypes.includes('jurídica') || selectedTypes.includes('juridica');
      const isDirector = selectedTypes.includes('director');

      if (dni) dni.required = isNaturalOrDocente || isDirector;
      if (paternalSurname) paternalSurname.required = isNaturalOrDocente || isDirector;
      if (maternalSurname) maternalSurname.required = isNaturalOrDocente || isDirector;
      if (name) name.required = isNaturalOrDocente || isDirector;
    //   if (ruc) ruc.required = isJuridica;
      if (companyName) companyName.required = isJuridica;

      if (paternalSurname) paternalSurname.disabled = isJuridica;
      if (maternalSurname) maternalSurname.disabled = isJuridica;
      if (name) name.disabled = isJuridica;


      if (schoolNameContainer && schoolName) {
        if (isDirector) {
          schoolNameContainer.classList.remove('d-none');
          schoolName.required = true;
        } else {
          schoolNameContainer.classList.add('d-none');
          schoolName.required = false;
          schoolName.value = '';
        }
      }
    }

    personTypeCheckboxes.forEach(cb => {
      cb.addEventListener('change', updateFieldRequirements);
    });

    updateFieldRequirements();
  });
</script>

<script>
    document.getElementById('btnBuscarDni').addEventListener('click', buscarDocumento);

    document.getElementById('dni').addEventListener('keydown', function(event) {
        if (event.key === "Enter") {
            event.preventDefault();
            buscarDocumento();
        }
    });


    function buscarDocumento() {
        let numero = document.getElementById('dni').value.trim();
        if (numero.length !== 8 && numero.length !== 11) {
            Swal.fire({
                icon: 'warning',
                title: 'Número de documento inválido',
                text: 'Ingrese un DNI (8 dígitos) o un RUC (11 dígitos) válido.',
            });
            return;
        }

        let tipo = numero.length === 8 ? 'dni' : 'ruc';

        fetch(`${BASE_HREF}search-comunity-user?tipo=${tipo}&numero=${numero}`)
            .then(response => response.json())
            .then(data => {
                if (data.exists) {
                    document.getElementById('name').value = data.name || '';
                    document.getElementById('paternal_surname').value = data.paternal_surname || '';
                    document.getElementById('maternal_surname').value = data.maternal_surname || '';
                    document.getElementById('phone').value = data.phone || '';
                    document.getElementById('email').value = data.email || '';
                    document.getElementById('company_name').value = data.company_name || '';
                    // document.getElementById('ruc').value = data.ruc || '';
                    document.getElementById('address').value = data.address || '';

                    if (data.has_user_id) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Usuario ya registrado',
                            text: 'Este usuario ya tiene una cuenta en el sistema.',
                        });
                        document.getElementById('formContainer').style.display = "none";
                    } else {
                        document.getElementById('formContainer').style.display = "block";
                        document.getElementById('credentialsContainer').style.display = "block";
                        Swal.fire({
                            icon: 'success',
                            title: 'Usuario encontrado',
                            text: 'Complete los datos faltantes para crear su cuenta.',
                        });
                    }
                } else {
                    Swal.fire({
                        icon: 'info',
                        title: 'Usuario no encontrado',
                        text: 'Complete los datos para registrarlo.',
                    });
                    document.getElementById('formContainer').style.display = "block";
                    document.getElementById('credentialsContainer').style.display = "block";

                    ['name', 'paternal_surname', 'maternal_surname', 'phone', 'email', 'company_name', 'address'] //se borro el campo ruc
                        .forEach(id => document.getElementById(id).value = '');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Ocurrió un problema al consultar el documento.',
                });
            });
    }


    // function buscarDni() {
    //     let dni = document.getElementById('dni').value.trim();
    //     if (dni.length < 8) {
    //         Swal.fire({
    //             icon: 'warning',
    //             title: 'Número de documento inválido',
    //             text: 'Ingrese un número de documento válido.',
    //         });
    //         return;
    //     }

    //     fetch(BASE_HREF +'search-comunity-user?dni=' + dni)
    //         .then(response => response.json())
    //         .then(data => {
    //             if (data.exists) {
    //                 document.getElementById('name').value = data.name || '';
    //                 document.getElementById('paternal_surname').value = data.paternal_surname || '';
    //                 document.getElementById('maternal_surname').value = data.maternal_surname || '';
    //                 document.getElementById('phone').value = data.phone || '';
    //                 document.getElementById('email').value = data.email || '';
    //                 document.getElementById('company_name').value = data.company_name || '';
    //                 document.getElementById('ruc').value = data.ruc || '';
    //                 document.getElementById('address').value = data.address || '';

    //                 if (data.has_user_id) {
    //                     Swal.fire({
    //                         icon: 'error',
    //                         title: 'Usuario ya registrado',
    //                         text: 'Este usuario ya tiene una cuenta en el sistema. Puede visualizar su información en la sección de usuarios.',
    //                     });
    //                     document.getElementById('formContainer').style.display = "none";
    //                 } else {
    //                     document.getElementById('formContainer').style.display = "block";
    //                     document.getElementById('credentialsContainer').style.display = "block";
    //                     Swal.fire({
    //                         icon: 'success',
    //                         title: 'Usuario encontrado',
    //                         text: 'Complete los datos faltantes para crear su cuenta en el sistema.',
    //                     });
    //                 }
    //             } else {
    //                 Swal.fire({
    //                     icon: 'info',
    //                     title: 'Usuario no encontrado',
    //                     text: 'Complete los datos para registrarlo.',
    //                 });
    //                 document.getElementById('formContainer').style.display = "block";
    //                 document.getElementById('name').value = '';
    //                 document.getElementById('paternal_surname').value = '';
    //                 document.getElementById('maternal_surname').value = '';
    //                 document.getElementById('phone').value = '';
    //                 document.getElementById('email').value = '';
    //                 document.getElementById('company_name').value = '';
    //                 document.getElementById('ruc').value = '';
    //                 document.getElementById('address').value = '';
    //                 document.getElementById('credentialsContainer').style.display = "block";
    //             }
    //         })
    //         .catch(error => {
    //             console.error('Error:', error);
    //             Swal.fire({
    //                 icon: 'error',
    //                 title: 'Error',
    //                 text: 'Ocurrió un problema al consultar el DNI.',
    //             });
    //         });
    // }
</script>

