<h2 class="page-title">Crear Usuario UGEL</h2>
<p class="text-muted">Ingrese los datos del usuario UGEL 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 ?>ugel-users" method="POST">
                    
                    <input type="hidden" name="role" value="UGEL">

                    <h5 class="mb-3">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" required>
                            </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" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="name">Nombre</label>
                        <input type="text" name="name" class="form-control" id="name" required>
                    </div>
                    <div class="form-group">
                        <label for="dni">DNI</label>
                        <input type="text" name="dni" class="form-control" id="dni" maxlength="8" required>
                    </div>
                    <div class="form-group">
                        <label for="birthdate">Fecha de Nacimiento</label>
                        <input type="date" name="birthdate" class="form-control" id="birthdate" required>
                    </div>
                    <div class="form-group">
                        <label for="age">Edad</label>
                        <input type="number" name="age" class="form-control" id="age" required readonly>
                    </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" required></textarea>
                    </div>

                    <h5 class="mb-3 mt-4">Datos Laborales</h5>
                    <div class="form-group">
                        <label for="area">Área</label>
                        <select id="area" name="area_id" class="form-control" required>
                            <option value="">Seleccione un Área</option>
                            <?php foreach ($areas as $area) : ?>
                                <option value="<?= $area->id ?>"><?= $area->description ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="group_type">Tipo de Grupo</label>
                        <select id="group_type" name="group_type_id" class="form-control" disabled required>
                            <option value="">Seleccione un Tipo de Grupo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="group">Grupo</label>
                        <select id="group" name="group_id" class="form-control" disabled required>
                            <option value="">Seleccione un Grupo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="subgroup">Subgrupo</label>
                        <select id="subgroup" name="subgroup_id" class="form-control" disabled>
                            <option value="">Seleccione un Subgrupo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="position">Cargo</label>
                        <input type="text" name="position" class="form-control" id="position" required>
                    </div>
                    <div class="form-group">
                        <label for="files_charge">Cantidad de Expedientes a Cargo</label>
                        <input type="number" name="files_charge" class="form-control" id="files_charge" required>
                    </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" 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 class="d-flex justify-content-start">
                        <a href="<?= BASE_HREF ?>ugel-users" class="btn btn-secondary mr-2">Cancelar</a>
                        <button type="submit" class="btn btn-primary">Guardar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        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>';
            }
        });

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

        function updateRequirement(element, condition) {
            if (condition) {
                element.textContent = element.textContent.replace("✘", "✔");
                element.classList.remove("text-danger");
                element.classList.add("text-success");
            } else {
                element.textContent = element.textContent.replace("✔", "✘");
                element.classList.remove("text-success");
                element.classList.add("text-danger");
            }
        }

        if (passwordInput) {
            passwordInput.addEventListener("input", function () {
                const password = passwordInput.value;

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

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

            passwordInput.dispatchEvent(new Event("input"));
        }
    });
</script>

<script>
    document.getElementById('username').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('password').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('name').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('paternal_surname').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('maternal_surname').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('position').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('address').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });

    document.getElementById('birthdate').addEventListener('change', function () {
        const birthDate = new Date(this.value);
        const today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDiff = today.getMonth() - birthDate.getMonth();
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        document.getElementById('age').value = age;
    });

    document.getElementById('dni').addEventListener('input', function () {
        this.value = this.value.replace(/\D/g, '').slice(0, 8);
    });

    document.getElementById('phone').addEventListener('input', function () {
        this.value = this.value.replace(/\D/g, '').slice(0, 9);
    });
</script>

<script>
    $(document).ready(function () {
        // Inicializar Select2
        $('#area, #group_type, #group, #subgroup').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleccione...',
            allowClear: true,
            width: '100%'
        });

        const areas = <?= json_encode($areas, JSON_PRETTY_PRINT) ?>;
        console.log(areas);

        $('#area').on('change', function () {
            const areaId = $(this).val();

            const $groupType = $('#group_type');
            const $group = $('#group');
            const $subgroup = $('#subgroup');

            // Reset y desactivar selects
            $groupType.empty().append('<option value="">Seleccione un Tipo de Grupo</option>').prop('disabled', true).trigger('change');
            $group.empty().append('<option value="">Seleccione un Grupo</option>').prop('disabled', true).trigger('change');
            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

            if (areaId) {
                const area = areas.find(a => a.id == areaId);
                if (area) {
                    $groupType.prop('disabled', false);
                    Object.values(area.groupTypes).forEach(groupType => {
                        $groupType.append(new Option(groupType.description, groupType.id));
                    });
                    $groupType.trigger('change');
                }
            }
        });

        $('#group_type').on('change', function () {
            const groupTypeId = $(this).val();

            const $group = $('#group');
            const $subgroup = $('#subgroup');

            $group.empty().append('<option value="">Seleccione un Grupo</option>').prop('disabled', true).trigger('change');
            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

            if (groupTypeId) {
                const areaId = $('#area').val();
                const area = areas.find(a => a.id == areaId);
                if (area) {
                    const groupType = Object.values(area.groupTypes).find(gt => gt.id == groupTypeId);
                    if (groupType) {
                        $group.prop('disabled', false);
                        Object.values(groupType.groups).forEach(group => {
                            $group.append(new Option(group.description, group.id));
                        });
                        $group.trigger('change');
                    }
                }
            }
        });

        $('#group').on('change', function () {
            const groupId = $(this).val();
            const $subgroup = $('#subgroup');

            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

            if (groupId) {
                const areaId = $('#area').val();
                const groupTypeId = $('#group_type').val();
                const area = areas.find(a => a.id == areaId);
                if (area) {
                    const groupType = Object.values(area.groupTypes).find(gt => gt.id == groupTypeId);
                    if (groupType) {
                        const group = Object.values(groupType.groups).find(g => g.id == groupId);
                        if (group) {
                            $subgroup.prop('disabled', false);
                            Object.values(group.subGroups).forEach(subgroup => {
                                $subgroup.append(new Option(subgroup.description, subgroup.id));
                            });
                            $subgroup.trigger('change');
                        }
                    }
                }
            }
        });
    });
</script>
