<h2 class="page-title">Derivar Trámite</h2>
<p class="text-muted">Ingrese los datos de la derivación 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 id="formTramite" action="<?= BASE_ACTION ?>processes-derive" method="POST" enctype="multipart/form-data">
                    
                    <input type="hidden" name="process_id" value="<?= $process->id ?>">

                    <h5 class="mb-3">Modo de Derivación</h5>
                    <div class="border rounded p-3 bg-light d-flex align-items-center justify-content-between">
                        <div>
                            <label for="switchDerivacion" class="font-weight-bold mb-1">Derivación Automática</label>
                            <div id="switchLabel" class="text-muted small">
                            <?= ($process->derivation_mode === 'MANUAL')
                                ? 'Actualmente en modo manual. No puede volver a automático.'
                                : 'El sistema derivará el trámite automáticamente según la ruta establecida.' ?>
                            </div>
                        </div>

                        <div class="custom-control custom-switch m-0">
                            <input 
                            type="checkbox" 
                            class="custom-control-input" 
                            id="switchDerivacion" 
                            name="derivation_mode"
                            value="AUTOMATICO"
                            <?= ($process->derivation_mode === 'AUTOMATICO') ? 'checked' : '' ?>
                            <?= ($process->derivation_mode === 'MANUAL') ? 'disabled' : '' ?>
                            >
                            <label class="custom-control-label" for="switchDerivacion"></label>
                        </div>
                    </div>

                    <!-- Campo oculto que guarda el valor real -->
                    <input type="hidden" name="derivation_mode_value" id="derivation_mode_value" value="<?= $process->derivation_mode ?>">


                    <h5 class="mb-3 mt-4">Archivos del Trámite</h5>
                    <div class="form-group">
                        <?php if (!empty($attachments)) : ?>
                            <ul class="list-group">
                                <?php foreach ($attachments as $attachment) : ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <a href="<?= BASE_HREF . ltrim($attachment->file_path, '/') ?>" target="_blank">
                                            <?= htmlspecialchars($attachment->file_name) ?>
                                        </a>
                                        <small class="text-muted">Subido el <?= htmlspecialchars($attachment->created_at) ?></small>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else : ?>
                            <p class="text-muted">No hay archivos adjuntos.</p>
                        <?php endif; ?>
                    </div>


                    <h5 class="mb-3 mt-4">Destino de Trámite</h5>

                    <!-- 🔹 AUTOMÁTICO -->
                    <div id="destino-automatico">
                        <div class="form-group">
                            <label>Área</label>
                            <input type="text" id="area_auto" class="form-control" 
                                value="<?= htmlspecialchars($nextRoute?->area()->description ?? 'NO DEFINIDO') ?>" disabled>
                        </div>

                        <div class="form-group">
                            <label>Tipo de Grupo</label>
                            <input type="text" id="group_type_auto" class="form-control" 
                                value="<?= htmlspecialchars($nextRoute?->groupType()->description ?? 'NO DEFINIDO') ?>" disabled>
                        </div>

                        <div class="form-group">
                            <label>Grupo</label>
                            <input type="text" id="group_auto" class="form-control" 
                                value="<?= htmlspecialchars($nextRoute?->group()->description ?? 'NO DEFINIDO') ?>" disabled>
                        </div>

                        <div class="form-group">
                            <label>Subgrupo</label>
                            <input type="text" id="subgroup_auto" class="form-control" 
                                value="<?= htmlspecialchars($nextRoute?->subgroup()->description ?? 'SUBGRUPO NO DEFINIDO') ?>" disabled>
                        </div>
                    </div>



                    <!-- 🔹 MANUAL -->
                    <div id="destino-manual" style="display: none;">
                        <div class="form-group">
                            <label for="area">Área</label>
                            <select id="area" name="area_id" class="form-control">
                                <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>
                                <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>
                                <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>



                    <h5 class="mb-3 mt-4">Adjuntar Archivos</h5>
                    <div class="form-group">
                        <label for="file-upload" class="form-label">Si desea puede adjuntar archivos al trámite <small class="text">(Solo PDF, máx. 5 MB)</small></label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="file-upload" name="files[]" multiple accept="application/pdf">
                            <label class="custom-file-label" for="file-upload">Seleccionar archivos</label>
                        </div>
                        <ul id="file-list" class="list-group mt-2"></ul>
                    </div>

                    <h5 class="mb-3 mt-4">Comentario (Opcional)</h5>
                    <div class="form-group">
                        <label for="comment">Añadir comentario</label>
                        <textarea class="form-control" name="comment" id="comment" rows="4"></textarea>
                    </div>


                    <div class="buttons-container d-flex justify-content-start mt-3">
                        <a href="<?= BASE_HREF ?>processes/show-processes" class="btn btn-secondary mr-2">Cancelar</a>
                        <button type="submit" class="btn btn-primary" id="btnGuardar">Derivar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script>
    document.getElementById("formTramite").addEventListener("submit", function(event) {
        event.preventDefault();

        if (!this.checkValidity()) {
            this.reportValidity();
            return;
        }

        const derivationMode = document.getElementById("derivation_mode_value").value;

        if (derivationMode === 'MANUAL') {
            const area = document.getElementById("area").value.trim();
            const group = document.getElementById("group").value.trim();

            if (!area || !group) {
                Swal.fire({
                    icon: "warning",
                    title: "Campos requeridos",
                    text: "Debe seleccionar al menos el área y el grupo antes de derivar el trámite en modo MANUAL.",
                });
                return;
            }
        }

        let groupName = "NO DEFINIDO";
        if (derivationMode === "AUTOMATICO") {
            groupName = document.getElementById('group_auto').value;
        } else if (derivationMode === "MANUAL") {
            const selectManual = document.getElementById("group");
            if (selectManual && selectManual.value) {
                groupName = selectManual.options[selectManual.selectedIndex].text;
            }
        }

        Swal.fire({
            title: "¿Estás seguro?",
            text: `Este trámite será derivado a la oficina de ${groupName}.`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Sí, derivar",
            cancelButtonText: "Cancelar"
        }).then((result) => {
            if (result.isConfirmed) {
                event.target.submit();
            }
        });
    });
</script>

<script>
    document.addEventListener("DOMContentLoaded", function () {

        const switchDerivacion = document.getElementById('switchDerivacion');
        const switchLabel = document.getElementById('switchLabel');
        const derivationModeValue = document.getElementById('derivation_mode_value');

        if (!switchDerivacion.disabled) {
            switchDerivacion.addEventListener('change', function() {
            if (this.checked) {
                switchLabel.textContent = "El sistema derivará el trámite automáticamente según la ruta establecida.";
                derivationModeValue.value = "AUTOMATICO";
            } else {
                switchLabel.textContent = "Ahora el usuario deberá seleccionar manualmente el destino de la derivación.";
                derivationModeValue.value = "MANUAL";
            }
            });
        }

        // Marcar campos obligatorios con asterisco
        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>';
            }
        });

        // Manejo de archivos
        let fileInput = document.getElementById("file-upload");
        let fileList = document.getElementById("file-list");

        fileInput.addEventListener("change", function (event) {
            fileList.innerHTML = "";

            let files = Array.from(event.target.files);
            let dt = new DataTransfer();

            files.forEach((file, i) => {
                const isPDF = file.type === "application/pdf";
                const isSizeValid = file.size <= 5 * 1024 * 1024;

                if (!isPDF || !isSizeValid) {
                    let msg = `El archivo "${file.name}" `;
                    if (!isPDF) msg += "no es un archivo PDF válido.";
                    else if (!isSizeValid) msg += "excede el tamaño máximo de 5MB.";
                    alert(msg);
                    return;
                }

                dt.items.add(file);

                // Crear ítem en la lista
                let listItem = document.createElement("li");
                listItem.classList.add("list-group-item", "d-flex", "justify-content-between", "align-items-center");
                listItem.textContent = `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;

                let removeBtn = document.createElement("button");
                removeBtn.classList.add("btn", "btn-danger", "btn-sm");
                removeBtn.textContent = "X";
                removeBtn.onclick = function () {
                    removeFile(i);
                };

                listItem.appendChild(removeBtn);
                fileList.appendChild(listItem);
            });

            fileInput.files = dt.files;
        });

        function removeFile(indexToRemove) {
            let files = Array.from(fileInput.files);
            let dt = new DataTransfer();

            files.forEach((file, index) => {
                if (index !== indexToRemove) {
                    dt.items.add(file);
                }
            });

            fileInput.files = dt.files;
            fileInput.dispatchEvent(new Event("change")); // vuelve a actualizar la lista
        }

    });
</script>

<script>
    document.getElementById('comment').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById("file").addEventListener("change", function() {
        var fileName = this.files[0].name;
        var label = document.querySelector(".custom-file-label");
        label.textContent = fileName;
    });
</script>


<script>
    $(document).ready(function() {
        const $switch = $('#switchDerivacion');
        const $destinoAutomatico = $('#destino-automatico');
        const $destinoManual = $('#destino-manual');
        const $hiddenMode = $('#derivation_mode_value');

        function actualizarVista() {
            if ($switch.is(':checked')) {
                // Automático
                $destinoAutomatico.show();
                $destinoManual.hide();
                $hiddenMode.val('AUTOMATICO');
            } else {
                // Manual
                $destinoAutomatico.hide();
                $destinoManual.show();
                $hiddenMode.val('MANUAL');
            }
        }

        // Evento al cambiar el switch
        $switch.on('change', actualizarVista);

        // Inicializar vista según estado inicial del proceso
        actualizarVista();


        $('#area, #group_type, #group, #subgroup').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleccione...',
            allowClear: true,
            width: '100%'
        });

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

        $('#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>