<h2 class="page-title">Subsanar Trámite</h2>
<p class="text-muted">Modifica los datos del trámite y guarda los cambios.</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/<?= $process->id ?>/correct" method="POST" enctype="multipart/form-data">
                    
                <input type="hidden" name="_method" value="PUT">
                <input type="hidden" name="dni" value="<?= $process->user_dni ?>">

                    <h5 class="mb-3">Archivos Iniciales del Trámite</h5>
                    <div class="form-group">
                        <?php if (!empty($location->attachments())) : ?>
                            <ul class="list-group">
                                <?php foreach ($location->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 se han adjuntado archivos al inicio del trámite.</p>
                        <?php endif; ?>
                    </div>

                    <h5 class="mb-3 mt-4">Detalles de Trámite</h5>
                    
                    <div class="form-group">
                        <label for="procedure_id">Procedimiento</label>
                        <select id="procedure_id" name="procedure_id" class="form-control" required>
                            <option value="">Seleccione un Procedimiento</option>
                            <?php foreach ($procedures as $procedure) : ?>
                                <option value="<?= $procedure->id ?>" <?= $process->procedure_id == $procedure->id ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($procedure->description) ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="other" <?= empty($process->procedure_id) ? 'selected' : '' ?>>OTROS</option>
                        </select>
                    </div>

                    <div class="form-group" id="customProcedureContainer" style="display: <?= empty($process->procedure_id) ? 'block' : 'none' ?>;">
                        <label for="custom_procedure">Especifique el procedimiento</label>
                        <input type="text" id="custom_procedure" name="custom_procedure" class="form-control"
                            value="<?= htmlspecialchars($process->custom_procedure ?? '') ?>" 
                            placeholder="Ingrese el procedimiento manualmente">
                    </div>

                    
                    <div class="form-group">
                        <label for="folios">Folios</label>
                        <input type="number" name="folios" class="form-control" id="folios" required min="0" value="<?= $process->folios ?>">
                    </div>

                    <div class="form-group">
                        <label for="subject">Asunto</label>
                        <textarea class="form-control" name="subject" id="subject" rows="4" required><?= $process->subject ?></textarea>
                    </div>

                    <div class="form-group">
                        <label for="rationale">Fundamentación</label>
                        <textarea class="form-control" name="rationale" id="rationale" rows="4" required><?= $process->rationale ?? '' ?></textarea>
                    </div>

                    <h5 class="mb-3 mt-4">Adjuntar Archivos</h5>
                    <div class="form-group">
                        <label for="file-upload" class="form-label">Nota: Recuerde actualizar el número de folios si adjunta más 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="buttons-container d-flex justify-content-start mt-3">
                        <?php if ($_SESSION['role'] == "COMUNITY") : ?>
                            <a href="<?= BASE_HREF ?>processes/my-processes" class="btn btn-secondary mr-2">Cancelar</a>
                        <?php else: ?>
                            <a href="<?= BASE_HREF ?>processes/show-processes" class="btn btn-secondary mr-2">Cancelar</a>
                        <?php endif; ?>
                        <button type="submit" class="btn btn-primary">Actualizar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        $('#procedure_id').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleccione un Procedimiento',
            allowClear: true,
            width: '100%'
        });

        $('#procedure_id').on('change', function() {
            let selected = $(this).val();

            if (selected === 'other') {
                $('#customProcedureContainer').show();
            } else {
                $('#customProcedureContainer').hide();
            }
        });

    });
</script>


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

        // 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("formTramite").addEventListener("submit", function(event) {
        event.preventDefault();

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

        Swal.fire({
            title: "¿Estás seguro?",
            text: "Esta acción reingresará el trámite y usted no podrá editarlo hasta recibir una respuesta.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Sí, reingresar",
            cancelButtonText: "Cancelar"
        }).then((result) => {
            if (result.isConfirmed) {
                event.target.submit();
            }
        });
    });
</script>

<script>
    document.getElementById('subject').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('custom_procedure').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
    document.getElementById('rationale').addEventListener('input', function (event) {
        event.target.value = event.target.value.toUpperCase();
    });
</script>