@extends('layouts.app')

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

@section('content')
<style>
    .table-scroll { max-height: 70vh; overflow-y: auto; overflow-x: auto; }
    .table-scroll table { min-width: 1400px; }
    .table-scroll thead th { position: sticky; top: 0; z-index: 2; background: #f8f9fa; }
    .nowrap { white-space: nowrap; }
    .truncate { max-width: 340px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .codebox { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: .85rem; }
</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</h3>
        <small class="text-muted">Registro de accesos a módulos y acciones realizadas por los usuarios</small>
    </div>
</div>

@if(!empty($audit_not_ready))
    <div class="alert alert-warning">
        <div class="fw-bold mb-1"><i class="fas fa-triangle-exclamation me-2"></i>Auditoría no inicializada</div>
        <div>
            Ejecute las migraciones para crear la tabla <span class="codebox">auditoria_logs</span>.
            (Ej.: <span class="codebox">php artisan migrate</span>)
        </div>
    </div>
@endif

<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.index') }}" 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)$idSede === (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)$userId === (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="{{ $from }}" class="form-control">
            </div>

            <div class="col-md-2">
                <label class="form-label">Hasta</label>
                <input type="date" name="to" value="{{ $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)$action === (string)$a ? 'selected' : '' }}>
                            {{ $a }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-12 d-flex gap-2">
                <button class="btn btn-primary">
                    <i class="fas fa-search me-2"></i>Consultar
                </button>
                <a href="{{ route('admin.auditoria.index') }}" 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.grouped', request()->query()) }}">
                        <i class="fas fa-layer-group me-2"></i>Vista agrupada
                    </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</div>
        <small class="text-muted">Total: {{ $logs->total() }}</small>
    </div>

    <div class="table-scroll">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th class="nowrap" style="width:70px;">#</th>
                    <th class="nowrap" style="min-width:170px;">Fecha / Hora</th>
                    <th class="nowrap" style="min-width:180px;">Sede</th>
                    <th class="nowrap" style="min-width:260px;">Usuario</th>
                    <th class="nowrap" style="min-width:180px;">Tipo Usuario</th>
                    <th class="nowrap" style="min-width:180px;">Módulo</th>
                    <th class="nowrap" style="min-width:160px;">Acción</th>
                    <th style="min-width:360px;">Detalle</th>
                    <th class="nowrap" style="min-width:150px;">IP</th>
                    <th class="nowrap" style="min-width:220px;">Ruta</th>
                </tr>
            </thead>

            <tbody>
            @forelse($logs as $log)
                @php
                    $usuario = $log->user;
                    $nombre = $usuario?->nombre_completo ?? $usuario?->name ?? '—';
                    $dni = $usuario?->dni;
                    $userTxt = trim(($dni ? $dni.' - ' : '').$nombre);
                    $detalle = $log->description ?: '';
                    $payload = $log->payload;
                    $payloadTxt = $payload ? json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : null;
                @endphp
                <tr>
                    <td class="fw-semibold nowrap" align="center">
                        {{ ($logs->currentPage() - 1) * $logs->perPage() + $loop->iteration }}
                    </td>
                    <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->sede_nombre }}</td>
                    <td class="truncate" title="{{ $userTxt }}">{{ $userTxt }}</td>
                    <td class="nowrap">{{ $log->tipo_usuario_nombre }}</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>
                        <div class="truncate" title="{{ $detalle }}">{{ $detalle ?: '-' }}</div>
                        @if($payloadTxt)
                            <details class="mt-1">
                                <summary class="text-primary" style="cursor:pointer;">Ver payload</summary>
                                <div class="codebox bg-light border rounded p-2 mt-2">{{ $payloadTxt }}</div>
                            </details>
                        @endif
                    </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>
            @empty
                <tr>
                    <td colspan="10" class="text-center text-muted py-5">
                        No hay registros para los filtros seleccionados.
                    </td>
                </tr>
            @endforelse
            </tbody>
        </table>
    </div>

    <div class="card-footer bg-white">
        {{ $logs->links() }}
    </div>
</div>
@endsection
