<h2 class="page-title">Seguimiento de Trámite</h2>
<p class="text-muted">Ingrese los datos del trámite que desea buscar.</p>

<!-- Formulario de Búsqueda -->
<div class="row">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">Formulario de Búsqueda</strong>
            </div>
            <div class="card-body">
                <form action="<?= BASE_ACTION ?>processes/search-process" method="POST">
                    
                    

                    <div class="form-group">
                        <label for="">Tipo de Trámite</label>
                        <select id="modality_id" name="modality_id" class="form-control">
                            <option value="">Seleccione un Tipo de Trámite</option>
                            <?php foreach ($modalities as $modality) : ?>
                                <option value="<?= $modality->id ?>" <?= isset($data['modality_id']) && $data['modality_id'] == $modality->id ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($modality->description) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="period">Periodo</label>
                        <select id="period" name="period" class="form-control" required>
                            <option value="">Seleccione un Periodo</option>
                            <?php foreach ($periods as $period) : ?>
                                <option value="<?= $period ?>" <?= isset($data['period']) && $data['period'] == $period ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($period) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="num_exp">Número de Trámite</label>
                        <input type="text" name="num_exp" class="form-control" id="num_exp" value="<?= htmlspecialchars($data['num_exp'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="">Clave</label>
                        <input type="text" name="key" class="form-control" id="key" value="<?= htmlspecialchars($data['key'] ?? '') ?>">
                    </div>

                    <div class="d-flex justify-content-start">
                        <button type="submit" class="btn btn-primary">Buscar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Resultados de la Búsqueda -->
<?php if (isset($process)) : ?>
    <?php if ($process) : ?>
        <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>
            <?php endif; ?>
        </div>

        <div class="row">
            <!-- Información General del Trámite -->
            <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> <?= 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 ?? 'Sin procedimiento') ?></li>
                            <li class="list-group-item"><strong>Asunto:</strong> <?= htmlspecialchars($process->subject) ?></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>

            <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) ?></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>

                                        <?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 . 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>
    <?php else : ?>
        <div class="alert alert-warning mt-4">No se encontró ningún trámite con los datos ingresados.</div>
    <?php endif; ?>
<?php endif; ?>

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

<script>
    document.addEventListener("DOMContentLoaded", function () {
    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>';
        }
    });
});
</script>