<h2 class="page-title">Dar Respuesta a Trámite</h2>
<p class="text-muted">Completa la información y adjunta archivos si es necesario.</p>

<div class="d-flex justify-content-end mb-3">
    <a href="<?= BASE_HREF ?>processes/show-processes" class="btn btn-secondary">Volver</a>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">Información General</strong>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-group">
                            <li class="list-group-item"><strong>Administrado:</strong> <?= htmlspecialchars($user->name) . ' ' . htmlspecialchars($user->paternal_surname) . ' ' . htmlspecialchars($user->maternal_surname) ?></li>
                            <li class="list-group-item"><strong>Número de Expediente:</strong> <?= htmlspecialchars($process->num_exped) ?></li>
                            <li class="list-group-item"><strong>Procedimiento:</strong> <?= htmlspecialchars($process->procedure()->description ?? $process->custom_procedure ?? 'Sin procedimiento') ?></li>
                            <li class="list-group-item"><strong>Asunto:</strong> <?= htmlspecialchars($process->subject) ?></li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-group">
                            <li class="list-group-item"><strong>Folios:</strong> <?= htmlspecialchars($process->folios) ?></li>
                            <li class="list-group-item"><strong>Fecha de Ingreso:</strong> <?= date('d/m/Y', strtotime($process->entry_date)) ?></li>
                            <li class="list-group-item"><strong>Prioridad:</strong> <?= htmlspecialchars($process->state->description ?? 'RESUELTO') ?></li>
                            <li class="list-group-item"><strong>Clave:</strong> <?= htmlspecialchars($process->key) ?></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">
                    Respuesta
                </strong>
            </div>
            <div class="card-body">
                <form id="resolveTramite" action="<?= BASE_ACTION ?>processes/respond" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="process_id" value="<?= $process->id ?>">

                    <!-- Opciones de respuesta -->
                    <div class="form-group">
                        <label>Seleccione una opción:</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="response_type" id="response" value="RESPONDER">
                            <label class="form-check-label" for="response">
                                Resolver Trámite
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="response_type" id="return" value="DEVOLVER">
                            <label class="form-check-label" for="return">
                                Devolver para Subsanar (Proveído)
                            </label>
                        </div>
                    </div>
                    
                    <div class="form-group" id="resolution-field" style="display: none;">
                        <label for="resolution_number">Número de Resolución</label>
                        <input type="text" name="resolution_number" id="resolution_number" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label for="file-upload" class="form-label">Subir Archivos <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>

                    <div class="form-group">
                        <label for="comment">Comentario (opcional)</label>
                        <textarea name="comment" id="comment" class="form-control"></textarea>
                    </div>

                    <a href="<?= BASE_HREF ?>processes/show-processes" class="btn btn-secondary">Cancelar</a>
                    <button type="submit" class="btn btn-success">Guardar</button>
                </form>
            </div>
        </div>
    </div>
</div>


<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Comentario en mayúsculas
        const commentInput = document.getElementById('comment');
        if (commentInput) {
            commentInput.addEventListener('input', function (event) {
                event.target.value = event.target.value.toUpperCase();
            });
        }

        // Número de resolución en mayúsculas
        const resolutionInput = document.getElementById('resolution_number');
        if (resolutionInput) {
            resolutionInput.addEventListener('input', function (event) {
                event.target.value = event.target.value.toUpperCase();
            });
        }

        // Mostrar/ocultar campo resolución
        const responseRadio = document.getElementById('response');
        const returnRadio = document.getElementById('return');
        const resolutionField = document.getElementById('resolution-field');

        function toggleResolutionField() {
            if (responseRadio && responseRadio.checked) {
                resolutionField.style.display = 'block';
            } else {
                resolutionField.style.display = 'none';
            }
        }

        if (responseRadio && returnRadio && resolutionField) {
            toggleResolutionField();
            responseRadio.addEventListener('change', toggleResolutionField);
            returnRadio.addEventListener('change', toggleResolutionField);
        }

        // Mostrar asterisco en labels de 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>';
            }
        });

        // 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
        }

        // Confirmación al enviar el formulario
        const resolveForm = document.getElementById("resolveTramite");
        if (resolveForm) {
            resolveForm.addEventListener("submit", function(event) {
                event.preventDefault();
                if (!this.checkValidity()) {
                    this.reportValidity();
                    return;
                }

                Swal.fire({
                    title: "¿Estás seguro?",
                    text: "Esta acción emitirá una respuesta al trámite del usuario.",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "Sí, responder",
                    cancelButtonText: "Cancelar"
                }).then((result) => {
                    if (result.isConfirmed) {
                        event.target.submit();
                    }
                });
            });
        }
    });
</script>