<h2 class="page-title">Editar Usuario UGEL</h2>
<p class="text-muted">Modifique 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/<?= $userUgel->id ?>/update" method="POST">
                    <input type="hidden" name="_method" value="PUT">
                    <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 value="<?= htmlspecialchars($userUgel->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" required value="<?= htmlspecialchars($userUgel->maternal_surname) ?>">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="name">Nombre</label>
                        <input type="text" name="name" class="form-control" id="name" required value="<?= htmlspecialchars($userUgel->name) ?>">
                    </div>
                    <div class="form-group">
                        <label for="dni">DNI</label>
                        <input type="text" name="dni" class="form-control" id="dni" maxlength="8" required value="<?= htmlspecialchars($userUgel->dni) ?>">
                    </div>
                    <div class="form-group">
                        <label for="birthdate">Fecha de Nacimiento</label>
                        <input type="date" name="birthdate" class="form-control" id="birthdate" required value="<?= htmlspecialchars($userUgel->birthdate) ?>">
                    </div>
                    <div class="form-group">
                        <label for="age">Edad</label>
                        <input type="number" name="age" class="form-control" id="age" required readonly value="<?= htmlspecialchars($userUgel->age) ?>">
                    </div>
                    <div class="form-group">
                        <label for="phone">Teléfono</label>
                        <input type="text" name="phone" class="form-control" id="phone" required value="<?= htmlspecialchars($userUgel->phone) ?>">
                        <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 value="<?= htmlspecialchars($userUgel->email) ?>">
                    </div>
                    <div class="form-group">
                        <label for="address">Dirección</label>
                        <textarea name="address" class="form-control" id="address" rows="2" required><?= htmlspecialchars($userUgel->address) ?></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 ?>" <?= ($userUgel->area() && $userUgel->area()->id == $area->id) ? 'selected' : '' ?>>
                                    <?= $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" required>
                            <option value="">Seleccione un Tipo de Grupo</option>
                            <?php if ($userUgel->area()) : ?>
                                <?php foreach ($userUgel->area()->groupTypes as $gt) : ?>
                                    <option value="<?= $gt->id ?>" <?= ($userUgel->groupType() && $userUgel->groupType()->id == $gt->id) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($gt->description) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="group">Grupo</label>
                        <select id="group" name="group_id" class="form-control" required>
                            <option value="">Seleccione un Grupo</option>
                            <?php if ($userUgel->groupType()) : ?>
                                <?php foreach ($userUgel->groupType()->groups as $g) : ?>
                                    <option value="<?= $g->id ?>" <?= ($userUgel->group() && $userUgel->group()->id == $g->id) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($g->description) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="subgroup">Subgrupo</label>
                        <select id="subgroup" name="subgroup_id" class="form-control">
                            <option value="">Seleccione un Subgrupo</option>
                            <?php if ($userUgel->group()) : ?>
                                <?php foreach ($userUgel->group()->subgroups as $sg) : ?>
                                    <option value="<?= $sg->id ?>" <?= ($userUgel->subgroup() && $userUgel->subgroup()->id == $sg->id) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($sg->description) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="position">Cargo</label>
                        <input type="text" name="position" class="form-control" id="position" required value="<?= htmlspecialchars($userUgel->position) ?>">
                    </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 value="<?= htmlspecialchars($userUgel->files_charge) ?>">
                    </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 value="<?= htmlspecialchars($user->username) ?>">
                    </div>
                    <div class="form-group">
                        <label for="password">Nueva Contraseña (opcional) <small class="text-muted">Si no desea cambiar la contraseña, deje este campo vacío.</small></label>
                        <input type="password" id="password" name="password" class="form-control">
                        <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" <?= $userUgel->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" <?= $userUgel->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 ?>ugel-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", 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>
    const areas = <?= json_encode($areas, JSON_PRETTY_PRINT) ?>;
    console.log(areas);

    function loadGroupTypes(selectedGroupTypeId = null) {
        const areaId = document.getElementById('area').value;
        const groupTypeSelect = document.getElementById('group_type');
        groupTypeSelect.innerHTML = '<option value="">Seleccione un Tipo de Grupo</option>';

        if (areaId) {
            const area = areas.find(a => a.id == areaId);
            if (area) {
                groupTypeSelect.disabled = false;
                Object.values(area.groupTypes).forEach(groupType => {
                    const option = new Option(groupType.description, groupType.id);
                    if (selectedGroupTypeId && selectedGroupTypeId == groupType.id) {
                        option.selected = true;
                    }
                    groupTypeSelect.add(option);
                });
            }
        }
    }

    function loadGroups(selectedGroupId = null) {
        const groupTypeId = document.getElementById('group_type').value;
        const groupSelect = document.getElementById('group');
        groupSelect.innerHTML = '<option value="">Seleccione un Grupo</option>';

        if (groupTypeId) {
            const areaId = document.getElementById('area').value;
            const area = areas.find(a => a.id == areaId);
            if (area) {
                const groupType = Object.values(area.groupTypes).find(gt => gt.id == groupTypeId);
                if (groupType) {
                    groupSelect.disabled = false;
                    Object.values(groupType.groups).forEach(group => {
                        const option = new Option(group.description, group.id);
                        if (selectedGroupId && selectedGroupId == group.id) {
                            option.selected = true;
                        }
                        groupSelect.add(option);
                    });
                }
            }
        }
    }

    function loadSubgroups(selectedSubgroupId = null) {
        const groupId = document.getElementById('group').value;
        const subgroupSelect = document.getElementById('subgroup');
        subgroupSelect.innerHTML = '<option value="">Seleccione un Subgrupo</option>';

        if (groupId) {
            const areaId = document.getElementById('area').value;
            const groupTypeId = document.getElementById('group_type').value;
            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) {
                        subgroupSelect.disabled = false;
                        Object.values(group.subGroups).forEach(subgroup => {
                            const option = new Option(subgroup.description, subgroup.id);
                            if (selectedSubgroupId && selectedSubgroupId == subgroup.id) {
                                option.selected = true;
                            }
                            subgroupSelect.add(option);
                        });
                    }
                }
            }
        }
    }

    document.getElementById('area').addEventListener('change', function () {
        loadGroupTypes();
        document.getElementById('group').innerHTML = '<option value="">Seleccione un Grupo</option>';
        document.getElementById('subgroup').innerHTML = '<option value="">Seleccione un Subgrupo</option>';
    });

    document.getElementById('group_type').addEventListener('change', function () {
        loadGroups();
        document.getElementById('subgroup').innerHTML = '<option value="">Seleccione un Subgrupo</option>';
    });

    document.getElementById('group').addEventListener('change', function () {
        loadSubgroups();
    });

    window.onload = function () {
        loadGroupTypes(<?= $userUgel->groupType() ? $userUgel->groupType()->id : 'null' ?>);
        loadGroups(<?= $userUgel->group() ? $userUgel->group()->id : 'null' ?>);
        loadSubgroups(<?= $userUgel->subgroup() ? $userUgel->subgroup()->id : 'null' ?>);
    };
</script>
