<h2 class="page-title">Detalle del Trámite</h2>
<p class="text-muted">Consulta la información completa del trámite.</p>

<div class="d-flex justify-content-end mb-3">
    <?php if ($process->general_state == "OBSERVADO") : ?>
        <a href="<?= BASE_HREF ?>processes/<?= $process->id ?>/amend" class="btn btn-warning" style="margin-right: 10px;">Ir a Subsanar</a>
    <?php endif; ?>

    <?php if ($_SESSION['role'] !== 'COMUNITY') : ?>
        <a href="<?= BASE_HREF ?>voucher/<?= $process->id ?>/print" class="btn btn-primary" target="_blank" style="margin-right: 10px;">
            Imprimir Voucher
        </a>
        <a href="<?= BASE_HREF ?>processes/show-processes" class="btn btn-secondary" style="margin-right: 10px;">Volver</a>
    <?php else: ?>
        <a href="<?= BASE_HREF ?>processes/my-processes" class="btn btn-secondary" style="margin-right: 10px;">Volver</a>
    <?php endif; ?>

    <?php if ($lastLocation->state === 'PENDIENTE'): ?>
        <form id="acceptTramiteForm" action="<?= BASE_ACTION ?>processes/<?= $process->id ?>/accept-process" method="POST" style="display:inline;">
            <button type="button" class="btn btn-success acceptTramiteButton" style="margin-right: 10px;" data-is-first-node="<?= $isFirstNode ? 'true' : 'false' ?>">Aceptar</button>
        </form>
    <?php endif; ?>

    <?php if ($lastLocation->state === 'RECIBIDO'): ?>
        <form action="<?= BASE_ACTION ?>processes/<?= $process->id ?>/accept-process" method="POST" style="display:inline;">
            <button type="submit" class="btn btn-gray" style="margin-right: 10px;" disabled>Aceptar</button>
        </form>

        <!-- En modo MANUAL puede derivar y responder siempre -->
        <a class="btn btn-success" style="margin-right: 10px;" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/derive">Derivar</a>
        <a class="btn btn-danger" style="margin-right: 10px;" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/respond">Responder o Devolver</a>
    <?php endif; ?>
</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">
                <ul class="list-group">
                    <li class="list-group-item">
                        <strong>Administrado:</strong>
                        <?php
                        if (!empty($user->name) || !empty($user->paternal_surname) || !empty($user->maternal_surname)) {
                            echo htmlspecialchars(trim(($user->name ?? '') . ' ' . ($user->paternal_surname ?? '') . ' ' . ($user->maternal_surname ?? '')));
                        } elseif (!empty($user->company_name)) {
                            echo htmlspecialchars($user->company_name);
                        } else {
                            echo '<em>Sin datos</em>';
                        }
                        ?>
                    </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>
                        <?php
                        $role = $_SESSION['role'];
                        $group = $_SESSION['group'] ?? null;
                        ?>

                        <?php if (($role === 'UGEL' || $role === 'ADMIN') && $group === 'MESA DE PARTES' && ($lastLocation->state === 'PENDIENTE' || $lastLocation->state === 'RECIBIDO') && $isFirstNode): ?>
                            <form id="updateProcedureForm"
                                action="<?= BASE_ACTION ?>processes/update-procedure/<?= $process->id ?>"
                                method="POST"
                                class="d-flex align-items-center"
                                style="gap: 10px; width: auto; margin-top: 5px;">

                                <select name="procedure_id" id="procedure_id"
                                    class="form-control form-control-sm"
                                    style="min-width: 250px;">
                                    <?php foreach ($procedures as $procedure): ?>
                                        <option value="<?= $procedure->id ?>" <?= $procedure->id == $process->procedure_id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($procedure->description) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                                <button type="submit" class="btn btn-sm btn-primary">
                                    <i class="fas fa-save"></i> Guardar
                                </button>
                            </form>

                            <div id="procedureUpdateMsg" class="mt-2 small"></div>
                        <?php else: ?>
                            <?= htmlspecialchars($process->procedure()->description ?? $process->custom_procedure ?? 'Sin procedimiento') ?>
                        <?php endif; ?>
                    </li>

                    <li class="list-group-item"><strong>Asunto:</strong> <?= htmlspecialchars($process->subject) ?></li>
                    <li class="list-group-item"><strong>Fundamentación:</strong> <?= htmlspecialchars($process->rationale) ?></li>
                    <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 g:i A', 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>

    <!-- Historial de Derivaciones -->
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">Historial del Trámite</strong>
            </div>
            <div class="card-body">
                <?php if (!empty($locations)) : ?>
                    <?php foreach ($locations as $location) : ?>
                        <div class="card mb-3 shadow-sm">
                            <div class="card-header d-flex justify-content-between">
                                <span><strong>Área:</strong>
                                    <?= htmlspecialchars($location->area->description) . ' - ' .
                                        htmlspecialchars($location->group->description) .
                                        ($location->subgroup ? ' - ' . htmlspecialchars($location->subgroup->description) : '') ?>
                                </span>

                                <?php
                                $badgeClass = 'secondary';

                                switch ($location->state) {
                                    case 'PENDIENTE':
                                        $badgeClass = 'warning';
                                        break;
                                    case 'RECIBIDO':
                                        $badgeClass = 'primary';
                                        break;
                                    case 'DERIVADO':
                                        $badgeClass = 'info';
                                        break;
                                    case 'RESUELTO':
                                        $badgeClass = 'success';
                                        break;
                                    case 'OBSERVADO':
                                        $badgeClass = 'danger';
                                        break;
                                }
                                ?>
                                <span class="badge badge-<?= $badgeClass ?>">
                                    <?= htmlspecialchars($location->state) ?>
                                </span>

                            </div>
                            <div class="card-body">
                                <p><strong>Derivado:</strong> <?= date('d/m/Y g:i A', strtotime($location->derived_date)) ?></p>
                                <p><strong>Recibido:</strong> <?= $location->receipt_date ? date('d/m/Y g:i A', strtotime($location->receipt_date)) : 'Aún no se ha recibido' ?></p>
                                <p><strong>Comentario:</strong> <?= htmlspecialchars($location->comment ?? 'Sin comentarios') ?></p>

                                <!-- Archivos Adjuntos -->
                                <?php if (!empty($location->attachments)) : ?>
                                    <h6>Archivos Adjuntos:</h6>
                                    <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 . 'public/' . ltrim($attachment->file_path, '/') ?>" target="_blank"><?= htmlspecialchars($attachment->file_name) ?></a>
                                                <small class="text-muted">
                                                    <?= date('d/m/Y g:i A', strtotime($attachment->created_at)) ?>
                                                </small>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else : ?>
                                    <p class="text-muted">No hay archivos adjuntos.</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else : ?>
                    <p class="text-muted">No hay historial disponible para este trámite.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('updateProcedureForm');
        const msgBox = document.getElementById('procedureUpdateMsg');

        if (form) {
            form.addEventListener('submit', async function(e) {
                e.preventDefault();

                const formData = new FormData(form);
                const url = form.action;

                msgBox.innerHTML = '<span class="text-secondary">Guardando...</span>';

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();

                    if (result.success) {
                        msgBox.innerHTML = '<span class="text-success">✅ Procedimiento actualizado correctamente.</span>';
                    } else {
                        msgBox.innerHTML = '<span class="text-danger">⚠️ ' + (result.message || 'Error al actualizar.') + '</span>';
                    }
                } catch (error) {
                    msgBox.innerHTML = '<span class="text-danger">❌ Error de conexión.</span>';
                }

                setTimeout(() => msgBox.innerHTML = '', 4000);
            });
        }
    });
</script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll(".acceptTramiteButton").forEach(button => {
            button.addEventListener("click", function() {
                let form = this.closest("form");

                let isReceptionDesk = this.dataset.isFirstNode === "true";

                let message = "¿Estás seguro de aceptar este trámite?";

                Swal.fire({
                    title: "Confirmación",
                    text: message,
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "Sí, aceptar",
                    cancelButtonText: "Cancelar"
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });
        });
    });
</script>

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