<?php if (!empty($_SESSION['error'])): ?>
    <div class="alert alert-danger"><?= $_SESSION['error']; ?></div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

<?php if (!empty($_SESSION['success'])): ?>
    <div class="alert alert-success"><?= $_SESSION['success']; ?></div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>



<h2 class="mb-2 page-title">Trámites</h2>
<p class="card-text">Lista de trámites derivados.</p>
<div class="row mb-3">
    <div class="col text-right">
        <form id="acceptAllForm" action="<?= BASE_ACTION ?>processes/accept-all" method="POST" style="display:inline;">
            <button type="submit" class="btn btn-primary" id="acceptAllButton">
                <span class="fe fe-check fe-12 mr-2"></span> Recibir Todos
            </button>
        </form>
    </div>
</div>

<div class="row my-4">
    <div class="col-md-12">
        <div class="card shadow">
            <div class="card-body">
                <table class="table datatables" id="dataTable-1">
                    <thead class="thead-dark">
                        <tr>
                            <th>N°</th>
                            <th>Expediente</th>
                            <th>Administrado</th>
                            <th>DNI/RUC</th>
                            <th>Procedimiento</th>
                            <th>Asunto</th>
                            <th>Folios</th>
                            <th>Estado</th>
                            <th>Fecha</th>
                            <th>Prioridad</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($processes)): ?>
                            <?php foreach ($processes as $index => $process): ?>
                                
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <?php
                                        $mode = $process->derivation_mode;
                                        $badgeClassMode = $mode === 'AUTOMATICO' ? 'primary' : 'secondary';
                                    ?>
                                    <td>
                                        <?= htmlspecialchars($process->num_exped) ?>
                                        <br>
                                        <span class="badge badge-<?= $badgeClassMode ?>">
                                            <?= $mode === 'AUTOMATICO' ? 'Automático' : 'Manual' ?>
                                        </span>
                                    </td>

                                    
                                    <td>
                                        <?php if (!empty($process->user->name) || !empty($process->user->paternal_surname) || !empty($process->user->maternal_surname)): ?>
                                            <?= htmlspecialchars(trim($process->user->name . ' ' . $process->user->paternal_surname . ' ' . $process->user->maternal_surname)) ?>
                                        <?php else: ?>
                                            <?= htmlspecialchars($process->user->company_name ?? '') ?>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <?= htmlspecialchars($process->user->dni ?? $process->user->ruc ?? '') ?>
                                    </td>



                                    <td><?= htmlspecialchars($process->procedure()->description ?? $process->custom_procedure ?? 'SIN PROCEDIMIENTO') ?></td>
                                    <td><?= htmlspecialchars($process->subject) ?></td>
                                    <td><?= htmlspecialchars($process->folios) ?></td>
                                    <!-- <td><?= htmlspecialchars($process->actualLocation->state ?? 'SIN ESTADO') ?></td> -->

                                    <?php
                                        $estadoLocation = $process->actualLocation->state ?? 'SIN ESTADO';
                                        $badgeClass = 'secondary';

                                        switch ($estadoLocation) {
                                            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;
                                        }
                                        ?>
                                        <td>
                                            <span class="badge badge-<?= $badgeClass ?>">
                                                <?= htmlspecialchars($estadoLocation) ?>
                                            </span>
                                        </td>


                                    <td><?= date('d/m/Y', strtotime($process->entry_date)) ?></td>

                                    <?php
                                        $estado = $process->state;
                                        $label = $estado ? htmlspecialchars($estado->description) : 'RESUELTO';
                                        $color = $estado ? $estado->color : '#3ad29f';
                                    ?>
                                    <td>
                                        <span class="badge" style="background-color: <?= htmlspecialchars($color) ?>; color: #000;">
                                            <?= $label ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="dropdown">
                                            <button class="btn btn-sm dropdown-toggle more-horizontal" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <span class="text-muted sr-only">Acciones</span>
                                            </button>


                                            <?php $isManual = ($process->derivation_mode === 'MANUAL'); ?>
                                                <div class="dropdown-menu dropdown-menu-right">
                                                    <a class="dropdown-item" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/show-process">Ver</a>

                                                    <?php if ($process->actualLocation->state === 'PENDIENTE'): ?>
                                                        <form id="acceptTramiteForm" action="<?= BASE_ACTION ?>processes/<?= $process->id ?>/accept-process" method="POST" style="display:inline;">
                                                            <button type="button" class="dropdown-item acceptTramiteButton" data-is-first-node="<?= $process->actualLocation->is_first_node ? 'true' : 'false' ?>">Aceptar</button>
                                                        </form>

                                                        <!-- Mientras está pendiente, no puede derivar ni responder -->
                                                        <button class="dropdown-item" disabled>Derivar</button>
                                                        <button class="dropdown-item" disabled>Responder o Devolver</button>

                                                    <?php elseif ($process->actualLocation->state === 'RECIBIDO'): ?>
                                                        <form action="<?= BASE_ACTION ?>processes/<?= $process->id ?>/accept-process" method="POST" style="display:inline;">
                                                            <button type="submit" class="dropdown-item" disabled>Aceptar</button>
                                                        </form>

                                                        <?php if ($isManual): ?>
                                                            <!-- En modo MANUAL puede derivar y responder siempre -->
                                                            <a class="dropdown-item" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/derive">Derivar</a>
                                                            <a class="dropdown-item" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/respond">Responder o Devolver</a>
                                                        <?php else: ?>
                                                            <!-- En modo AUTOMATICO sigue la ruta -->
                                                            <?php if (!$process->actualLocation->is_final_node): ?>
                                                                <a class="dropdown-item" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/derive">Derivar</a>
                                                            <?php else: ?>
                                                                <button class="dropdown-item" disabled>Derivar</button>
                                                            <?php endif; ?>

                                                            <a class="dropdown-item" href="<?= BASE_HREF ?>processes/<?= $process->id ?>/respond">Responder o Devolver</a>
                                                            
                                                        <?php endif; ?>

                                                    <?php elseif ($process->actualLocation->state === 'DERIVADO'): ?>
                                                        <form action="<?= BASE_ACTION ?>processes/<?= $process->id ?>/accept-process" method="POST" style="display:inline;">
                                                            <button type="submit" class="dropdown-item" disabled>Aceptar</button>
                                                        </form>
                                                        <button class="dropdown-item" disabled>Derivar</button>
                                                        <button class="dropdown-item" disabled>Responder o Devolver</button>
                                                    <?php endif; ?>
                                                </div>

                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="11" class="text-center">No hay procesos registrados.</td>
                            </tr>
                        <?php endif; ?>
                        </tbody>

                </table>
            </div>
        </div>
    </div>
</div>

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


<!-- <?php if (!empty($process) && $process->actualLocation): ?>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll(".acceptTramiteButton").forEach(button => {
                button.addEventListener("click", function() {
                    let form = this.closest("form");

                    let isReceptionDesk = <?= $process->actualLocation->is_first_node ? true : false ?>;

                    let message = isReceptionDesk
                        ? "Al aceptar el trámite lo está derivando al equipo correspondiente. ¿Estás seguro de aceptarlo?"
                        : "¿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>
<?php endif; ?> -->

<script>
  $(document).ready(function() {    
    $('#dataTable-1').DataTable({
      autoWidth: true,
      "lengthMenu": [
        [10, 15, 20, -1],
        [10, 15, 20, "All"]
      ]
    });
  });
</script>

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

        Swal.fire({
            title: "¿Estás seguro?",
            text: "Esta acción marcará como recibidos todos los trámites.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Sí, recibir",
            cancelButtonText: "Cancelar"
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById("acceptAllForm").submit();
            }
        });
    });
</script>