<!DOCTYPE html>
<html lang="es">
  <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="Registro de usuario - Paso 1">
      <link rel="icon" type="image/png" href="<?= BASE_HREF ?>assets/favicon.png">
      <title>Registro - Paso 2 | Sistema de Trámite</title>
      <!-- CSS -->
      <link rel="stylesheet" href="<?= BASE_HREF ?>css/simplebar.css">
      <link rel="stylesheet" href="<?= BASE_HREF ?>css/feather.css">
      <link rel="stylesheet" href="<?= BASE_HREF ?>css/daterangepicker.css">
      <link rel="stylesheet" href="<?= BASE_HREF ?>css/app-light.css" id="lightTheme">
      <link rel="stylesheet" href="<?= BASE_HREF ?>css/app-dark.css" id="darkTheme" disabled>
  </head>
  <body class="d-flex align-items-center justify-content-center bg-light" style="min-height: 100vh;">
    <div class="container my-5">

      <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-<?php echo $_SESSION['message_type']; ?>">
            <?php 
                echo $_SESSION['message']; 
                unset($_SESSION['message']);
            ?>
        </div>
      <?php endif; ?>

      <div class="row justify-content-center">
        <div class="col-md-10 col-lg-6">
          <div class="card shadow-lg">
            <div class="card-body p-4">
              <h4 class="text-center mb-4">👤 Completa tu Registro</h4>

              <form action="<?= BASE_ACTION ?>auth/register-step2" method="POST">
                <input type="hidden" name="email" value="<?= htmlspecialchars($email) ?>">
                <input type="hidden" name="role" value="COMUNITY">

                <h5 class="mb-3">Tipo de Persona</h5>
                <div class="mb-3">
                  <?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>

                <h5 class="mb-3 mt-4">Datos Personales</h5>

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

                <div class="mb-3">
                  <label for="name" class="form-label">Nombre</label>
                  <input type="text" name="name" class="form-control" id="name">
                </div>

                <div class="mb-3">
                  <label for="dni" class="form-label">DNI/RUC</label>
                  <input type="text" name="dni" class="form-control" id="dni">
                </div>

                <div class="mb-3">
                  <label for="company_name" class="form-label">Razón Social</label>
                  <input type="text" name="company_name" class="form-control" id="company_name">
                </div>

                <!-- <div class="mb-3">
                  <label for="ruc" class="form-label">RUC</label>
                  <input type="text" name="ruc" class="form-control" id="ruc">
                </div> -->

                <div class="mb-3">
                  <label for="phone" class="form-label">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="mb-3">
                  <label for="address" class="form-label">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 class="mb-3">
                  <label for="username" class="form-label">Usuario</label>
                  <input type="text" name="username" class="form-control" id="username" required>
                </div>

                <div class="mb-3">
                  <label for="password" class="form-label">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 class="mb-3">
                  <label for="confirm_password" class="form-label">Confirmar Contraseña</label>
                  <input type="password" name="confirm_password" class="form-control" id="confirm_password" required>
                  <div id="password_feedback" class="form-text mt-1"></div>
                </div>

                <div class="form-check mt-4 mb-3">
                  <input class="form-check-input" type="checkbox" id="declaration" name="declaration" required>
                  <label class="form-check-label" for="declaration">
                      Declaro bajo juramento que la información proporcionada es verídica y autorizo el uso de mis datos conforme a las políticas del sistema. Estoy consciente de que el registro implica responsabilidad sobre el uso de la plataforma.
                  </label>
                  </div>


                <div class="d-grid mt-4">
                  <button type="submit" class="btn btn-primary btn-block">Registrar</button>
                </div>
              </form>

            </div>
          </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 passwordFeedback = document.getElementById("password_feedback");

        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.addEventListener("DOMContentLoaded", function () {
            const newPassword = document.getElementById("password");
            const confirmPassword = document.getElementById("confirm_password");
            const passwordFeedback = document.getElementById("password_feedback");
            const minLength = 8;

            function validatePassword() {
                if (newPassword.value.length < minLength) {
                    passwordFeedback.textContent = `La contraseña debe tener al menos ${minLength} caracteres`;
                    passwordFeedback.classList.add("text-danger");
                    passwordFeedback.classList.remove("text-success");
                    return;
                } 

                if (newPassword.value !== confirmPassword.value) {
                    passwordFeedback.textContent = "Las contraseñas no coinciden";
                    passwordFeedback.classList.add("text-danger");
                    passwordFeedback.classList.remove("text-success");
                } else {
                    passwordFeedback.textContent = "Las contraseñas coinciden";
                    passwordFeedback.classList.add("text-success");
                    passwordFeedback.classList.remove("text-danger");
                }
            }

            if (newPassword && confirmPassword) {
                newPassword.addEventListener("input", validatePassword);
                confirmPassword.addEventListener("input", validatePassword);
            }
        });
    </script>
  </body>
</html>