<h2 class="page-title">Editar Usuario Comunidad</h2>
<p class="text-muted">Modifique los datos del usuario Comunidad en el formulario.</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/<?= $userComunity->id ?>/update" method="POST">
                    
                    <input type="hidden" name="_method" value="PUT">
                    <input type="hidden" name="role" value="COMUNITY">

                    <h5 class="mb-3">Tipo</h5>
                    <div class="form-group">
                        <label for="person_type">Tipo de Persona</label>
                        <div>
                            <?php foreach ($personTypes as $personType): ?>
                                <?php 
                                    $checked = in_array($personType->id, $userPersonTypeIds) ? 'checked' : ''; 
                                ?>
                                <div class="form-check">
                                    <input type="checkbox" name="person_types[]" value="<?= htmlspecialchars($personType->id) ?>" 
                                           class="form-check-input" id="person_type_<?= $personType->id ?>" <?= $checked ?>>
                                    <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" value="<?= htmlspecialchars($userComunity->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" value="<?= htmlspecialchars($userComunity->maternal_surname) ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="name">Nombre Completo</label>
                        <input type="text" name="name" class="form-control" id="name" value="<?= htmlspecialchars($userComunity->name) ?>">
                    </div>
                    <div class="form-group">
                        <label for="dni">DNI</label>
                        <input type="text" name="dni" class="form-control" id="dni" value="<?= htmlspecialchars($userComunity->dni) ?>" maxlength="8">
                    </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" value="<?= htmlspecialchars($userComunity->company_name) ?>">
                    </div>
                    <div class="form-group">
                        <label for="ruc">RUC</label>
                        <input type="text" name="ruc" class="form-control" id="ruc" value="<?= htmlspecialchars($userComunity->ruc) ?>">
                    </div>
                    <div class="form-group">
                        <label for="phone">Teléfono</label>
                        <input type="text" name="phone" class="form-control" id="phone" value="<?= htmlspecialchars($userComunity->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" value="<?= htmlspecialchars($userComunity->email) ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="address">Dirección</label>
                        <textarea name="address" class="form-control" id="address" rows="2" required><?= htmlspecialchars($userComunity->address) ?></textarea>
                    </div>
                    <div class="mb-3 <?= isset($directorData) ? '' : '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"
                            value="<?= isset($directorData) ? htmlspecialchars($directorData->school_name) : '' ?>">
                    </div>

                    <h5 class="mb-3 mt-4">Credenciales</h5>
                    <div class="form-group">
                        <label for="username">Usuario</label>
                        <input type="text" name="username" class="form-control" id="username" value="<?= htmlspecialchars($user->username ?? 'SIN CREDENCIALES') ?> " required>
                    </div>
                    <div class="form-group">
                        <label for="password">Nueva Contraseña (Dejar en blanco si no desea cambiarla)</label>
                        <input type="password" name="password" class="form-control" id="password">
                        <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>

                    <h5 class="mb-3 mt-4">Estado</h5>
                    <div class="form-group">
                        <div class="custom-control custom-radio">
                            <input type="radio" id="activo" name="active" class="custom-control-input" value="1" <?= $userComunity->active == 1 ? 'checked' : '' ?>>
                            <label class="custom-control-label" for="activo">Activo</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="inactivo" name="active" class="custom-control-input" value="0" <?= $userComunity->active == 0 ? 'checked' : '' ?>>
                            <label class="custom-control-label" for="inactivo">Inactivo</label>
                        </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">Actualizar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    // Campos del formulario
    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');

    // Requisitos de contraseña
    const reqLength = document.getElementById("req-length");
    const reqAlphanumeric = document.getElementById("req-alphanumeric");
    const reqNoSpecial = document.getElementById("req-no-special");

    // Checkbox de tipo de persona
    const personTypeCheckboxes = document.querySelectorAll('input[name="person_types[]"]');

    // Agrega * a los campos requeridos
    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>';
      }
    });

    // Validación dinámica de requisitos de contraseña
    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")); // Ejecuta al cargar
    }

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

    // Solo dígitos y longitud máxima
    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);
      });
    }

    // Mostrar/ocultar campos según tipo de persona
    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 (dni) dni.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>