@extends('layouts.app')

@section('title','Auditoría (Agrupada)')

@section('content')
<style>
    .codebox { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: .85rem; }
    .nowrap { white-space: nowrap; }
    .truncate { max-width: 520px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
</style>

<div class="d-flex align-items-center justify-content-between mt-3 mb-3">
    <div>
        <h3 class="mb-0 fw-bold"><i class="fas fa-clipboard-list me-2"></i>Auditoría (Agrupada)</h3>
        <small class="text-muted">Vista agrupada por usuario (hasta 5,000 registros). Para volúmenes mayores usa Exportar.</small>
    </div>
</div>

<div class="card shadow-sm border-0 mb-3">
    <div class="card-header bg-white fw-bold">
        <i class="fas fa-filter me-2"></i>Filtros
    </div>
    <div class="card-body">
        <form method="GET" action="{{ route('admin.auditoria.grouped') }}" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Sede</label>
                <select name="id_sede" class="form-select">
                    <option value="">-- Todas --</option>
                    @foreach($sedes as $s)
                        <option value="{{ $s->id }}" {{ (string)request('id_sede') === (string)$s->id ? 'selected' : '' }}>
                            {{ $s->sede }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md-3">
                <label class="form-label">Usuario</label>
                <select name="user_id" class="form-select">
                    <option value="">-- Todos --</option>
                    @foreach($users as $u)
                        <option value="{{ $u->id }}" {{ (string)request('user_id') === (string)$u->id ? 'selected' : '' }}>
                            {{ $u->dni ? $u->dni.' - ' : '' }}{{ $u->nombre_completo ?? $u->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Desde</label>
                <input type="date" name="from" value="{{ request('from') }}" class="form-control">
            </div>

            <div class="col-md-2">
                <label class="form-label">Hasta</label>
                <input type="date" name="to" value="{{ request('to') }}" class="form-control">
            </div>

            <div class="col-md-2">
                <label class="form-label">Acción</label>
                <select name="action" class="form-select">
                    <option value="">-- Todas --</option>
                    @foreach($acciones as $a)
                        <option value="{{ $a }}" {{ (string)request('action') === (string)$a ? 'selected' : '' }}>
                            {{ $a }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-12 d-flex flex-wrap gap-2">
                <button class="btn btn-primary">
                    <i class="fas fa-search me-2"></i>Consultar
                </button>
                <a href="{{ route('admin.auditoria.grouped') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-rotate-left me-2"></i>Limpiar
                </a>

                <div class="ms-auto d-flex flex-wrap gap-2">
                    <a class="btn btn-outline-dark" href="{{ route('admin.auditoria.index', request()->query()) }}">
                        <i class="fas fa-table me-2"></i>Vista normal
                    </a>
                    <a class="btn btn-outline-success" href="{{ route('admin.auditoria.export.csv', request()->query()) }}">
                        <i class="fas fa-file-excel me-2"></i>Exportar Excel (CSV)
                    </a>
                    <a class="btn btn-outline-danger" href="{{ route('admin.auditoria.export.pdf', request()->query()) }}">
                        <i class="fas fa-file-pdf me-2"></i>Exportar PDF
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div class="fw-bold">Resultados agrupados</div>
        <small class="text-muted">Usuarios: {{ $grouped->count() }} | Registros: {{ $grouped->flatten(1)->count() }}</small>
    </div>

    <div class="card-body">
        @if($grouped->isEmpty())
            <div class="text-center text-muted py-4">No hay registros para los filtros seleccionados.</div>
        @else
            <div class="accordion" id="auditoriaAccordion">
                @foreach($grouped as $usuarioLabel => $items)
                    @php
                        $first = $items->first();
                        $tipo = $first?->tipo_usuario_nombre;
                        $sede = $first?->sede_nombre;
                        $accId = 'acc'.md5($usuarioLabel);
                    @endphp
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="h{{ $accId }}">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#c{{ $accId }}" aria-expanded="false" aria-controls="c{{ $accId }}">
                                <div class="w-100 d-flex flex-wrap align-items-center justify-content-between">
                                    <div>
                                        <span class="fw-semibold">{{ $usuarioLabel }}</span>
                                        <span class="text-muted ms-2">({{ $tipo }} · {{ $sede }})</span>
                                    </div>
                                    <span class="badge bg-dark">{{ $items->count() }} acciones</span>
                                </div>
                            </button>
                        </h2>
                        <div id="c{{ $accId }}" class="accordion-collapse collapse" aria-labelledby="h{{ $accId }}" data-bs-parent="#auditoriaAccordion">
                            <div class="accordion-body">
                                <div class="table-responsive">
                                    <table class="table table-sm table-hover align-middle mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th class="nowrap">Fecha / Hora</th>
                                                <th class="nowrap">Módulo</th>
                                                <th class="nowrap">Acción</th>
                                                <th>Detalle</th>
                                                <th class="nowrap">IP</th>
                                                <th class="nowrap">Ruta</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($items as $log)
                                                <tr>
                                                    <td class="nowrap">
                                                        <div class="fw-semibold">{{ $log->created_at?->format('d/m/Y') }}</div>
                                                        <div class="text-muted">{{ $log->created_at?->format('H:i:s') }}</div>
                                                    </td>
                                                    <td class="nowrap">{{ $log->module ?? '-' }}</td>
                                                    <td class="nowrap">
                                                        @if(($log->action ?? '') === 'LOGIN')
                                                            <span class="badge bg-success">LOGIN</span>
                                                        @elseif(($log->action ?? '') === 'LOGOUT')
                                                            <span class="badge bg-secondary">LOGOUT</span>
                                                        @elseif(in_array(($log->action ?? ''), ['CREAR','ACTUALIZAR','ELIMINAR'], true))
                                                            <span class="badge bg-primary">{{ $log->action }}</span>
                                                        @else
                                                            <span class="badge bg-dark">{{ $log->action ?? '-' }}</span>
                                                        @endif
                                                    </td>
                                                    <td class="truncate" title="{{ $log->description }}">{{ $log->description ?? '-' }}</td>
                                                    <td class="nowrap">{{ $log->ip_address ?? '-' }}</td>
                                                    <td class="nowrap">
                                                        <div class="fw-semibold">{{ $log->method ?? '-' }} {{ $log->status_code ? '(' . $log->status_code . ')' : '' }}</div>
                                                        <div class="text-muted truncate" title="{{ $log->route_name }}">{{ $log->route_name ?? '-' }}</div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        @endif
    </div>
</div>
@endsection
