<x-app-layout>
    <x-slot name="title">
        Auditoría del Sistema
    </x-slot>

    <!-- Filtros de Auditoría -->
    <div class="card mb-4 border-0 shadow-sm rounded-4">
        <div class="card-header bg-white border-bottom-0 pt-4 px-4 pb-0">
            <h6 class="fw-bold mb-0 text-muted"><i class="bi bi-funnel-fill me-2 text-primary"></i> Filtros de Trazabilidad</h6>
        </div>
        <div class="card-body p-4">
            <form method="GET" action="{{ route('admin.auditoria.index') }}" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted mb-1">Usuario (Nombre/DNI)</label>
                    <input type="text" name="usuario" value="{{ request('usuario') }}" class="form-control form-control-sm" placeholder="Buscar por Nombre o DNI">
                </div>
                @role('superadmin')
                <div class="col-md-2 mb-2">
                    <label class="form-label small fw-bold text-muted mb-1">Sede (Multitenant)</label>
                    <select name="sucursal_id" class="form-select form-select-sm tom-select">
                        <option value="">Cualquier Sede</option>
                        @foreach($sucursales as $s)
                            <option value="{{ $s->id }}" {{ request('sucursal_id') == $s->id ? 'selected' : '' }}>{{ $s->nombre }}</option>
                        @endforeach
                    </select>
                </div>
                @endrole
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted mb-1">Módulo / Modelo</label>
                    <select name="modelo" class="form-select form-select-sm tom-select">
                        <option value="">Todas</option>
                        @foreach($modelos as $m)
                            <option value="{{ $m }}" {{ request('modelo') == $m ? 'selected' : '' }}>{{ $m }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted mb-1">Acción</label>
                    <select name="accion" class="form-select form-select-sm tom-select">
                        <option value="">Todas</option>
                        @foreach($acciones as $a)
                            <option value="{{ $a }}" {{ request('accion') == $a ? 'selected' : '' }}>{{ ucfirst($a) }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted mb-1">Desde</label>
                    <input type="date" name="desde" value="{{ request('desde') }}" class="form-control form-control-sm">
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted mb-1">Hasta</label>
                    <input type="date" name="hasta" value="{{ request('hasta') }}" class="form-control form-control-sm">
                </div>
                <div class="col-md-1 d-flex gap-1 justify-content-md-end">
                    <button type="submit" class="btn btn-sm btn-primary rounded-pill fw-bold w-100 shadow-sm" title="Filtrar">
                        <i class="bi bi-search"></i>
                    </button>
                    @if(request()->hasAny(['usuario', 'modelo', 'accion', 'desde', 'hasta']))
                        <a href="{{ route('admin.auditoria.index') }}" class="btn btn-sm btn-light rounded-pill border w-100 text-center" title="Limpiar">
                            <i class="bi bi-x-lg"></i>
                        </a>
                    @endif
                </div>
            </form>
        </div>
    </div>

    <!-- Tabla de Registros -->
    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0" style="font-size: 0.9rem;">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4 py-3 text-secondary" style="font-size: 0.75rem;">Fecha y Hora</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem;">Usuario</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem;">Acción</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem;">Módulo Afectado</th>
                            <th class="py-3 text-secondary text-uppercase" style="font-size: 0.75rem;">Detalle Red</th>
                            <th class="pe-4 py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem;">Cambios</th>
                        </tr>
                    </thead>
                    <tbody class="border-top-0">
                        @forelse($registros as $log)
                            <tr>
                                <td class="ps-4 py-3 text-nowrap">
                                    <div class="fw-bold text-dark">{{ $log->created_at->format('d/m/Y') }}</div>
                                    <div class="text-muted small">{{ $log->created_at->format('H:i:s') }}</div>
                                </td>
                                <td class="py-3">
                                    @if($log->usuario)
                                        <div class="fw-bold text-primary">{{ $log->usuario->name }}</div>
                                        <div class="text-muted small">{{ $log->usuario->email }}</div>
                                    @else
                                        <span class="text-muted fst-italic">Sistema / Desconocido</span>
                                    @endif
                                </td>
                                <td class="py-3">
                                    @php
                                        $bColor = match($log->accion) {
                                            'crear'    => 'success',
                                            'editar'   => 'primary',
                                            'eliminar' => 'danger',
                                            'login'    => 'info',
                                            'logout'   => 'secondary',
                                            default    => 'dark'
                                        };
                                        $icon = match($log->accion) {
                                            'crear'    => 'plus-circle',
                                            'editar'   => 'pencil-square',
                                            'eliminar' => 'trash',
                                            'login'    => 'box-arrow-in-right',
                                            'logout'   => 'box-arrow-right',
                                            default    => 'record-circle'
                                        };
                                    @endphp
                                    <span class="badge bg-{{ $bColor }} bg-opacity-10 text-{{ $bColor }} border border-{{ $bColor }} border-opacity-25 rounded-pill px-3 py-1">
                                        <i class="bi bi-{{ $icon }} me-1"></i> {{ ucfirst($log->accion) }}
                                    </span>
                                </td>
                                <td class="py-3">
                                    @if($log->modelo)
                                        <div class="fw-bold text-dark">{{ class_basename($log->modelo) }}</div>
                                        <div class="text-muted small">ID: {{ $log->modelo_id }}</div>
                                    @else
                                        <span class="text-muted small">—</span>
                                    @endif
                                </td>
                                <td class="py-3">
                                    <div class="text-dark small"><i class="bi bi-globe me-1 text-muted"></i> {{ $log->ip }}</div>
                                    <div class="text-muted text-truncate" style="max-width: 150px; font-size: 0.65rem;" title="{{ $log->user_agent }}">{{ $log->user_agent }}</div>
                                    @if($log->sucursal)
                                        <div class="badge bg-light text-dark border mt-1">{{ $log->sucursal->nombre }}</div>
                                    @endif
                                </td>
                                <td class="pe-4 py-3 text-end">
                                    @if($log->valores_anteriores || $log->valores_nuevos)
                                        <button type="button" class="btn btn-sm btn-outline-secondary rounded-pill fw-bold" data-bs-toggle="modal" data-bs-target="#logModal{{ $log->id }}">
                                            Ver JSON
                                        </button>
                                        
                                        <!-- Modal de Detalle JSON -->
                                        <div class="modal fade text-start" id="logModal{{ $log->id }}" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered modal-lg">
                                                <div class="modal-content border-0 shadow-lg rounded-4">
                                                    <div class="modal-header bg-light border-0 rounded-top-4 p-4">
                                                        <h5 class="fw-bold mb-0">Detalle de Cambios (#{{ $log->id }})</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body p-4 bg-white">
                                                        @if(is_array($log->valores_anteriores) && is_array($log->valores_nuevos) && in_array($log->accion, ['actualizar', 'editar']))
                                                            <div class="table-responsive border rounded-3 overflow-hidden shadow-inner mb-0">
                                                                <table class="table table-borderless table-striped table-hover mb-0 small">
                                                                    <thead class="bg-light border-bottom">
                                                                        <tr>
                                                                            <th class="ps-4 fw-bold text-secondary text-uppercase py-3" style="width: 30%">Propiedad (Columna)</th>
                                                                            <th class="fw-bold text-secondary text-uppercase py-3" style="width: 35%"><i class="bi bi-dash-circle-fill text-danger me-1"></i> Estado Anterior</th>
                                                                            <th class="fw-bold text-secondary text-uppercase py-3" style="width: 35%"><i class="bi bi-plus-circle-fill text-success me-1"></i> Estado Actual</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>
                                                                        @foreach(array_keys(array_merge($log->valores_anteriores, $log->valores_nuevos)) as $key)
                                                                            @if(array_key_exists($key, $log->valores_anteriores) || array_key_exists($key, $log->valores_nuevos))
                                                                            <tr>
                                                                                <td class="ps-4 fw-bold text-dark text-uppercase bg-light bg-opacity-50 border-end">{{ $key }}</td>
                                                                                <td class="text-danger fw-medium lh-sm" style="word-break: break-all;">
                                                                                    {{ is_array($log->valores_anteriores[$key] ?? null) ? json_encode($log->valores_anteriores[$key], JSON_UNESCAPED_UNICODE) : ($log->valores_anteriores[$key] ?? '— (Vacío)') }}
                                                                                </td>
                                                                                <td class="text-success fw-medium lh-sm" style="word-break: break-all;">
                                                                                    {{ is_array($log->valores_nuevos[$key] ?? null) ? json_encode($log->valores_nuevos[$key], JSON_UNESCAPED_UNICODE) : ($log->valores_nuevos[$key] ?? '— (Vacío)') }}
                                                                                </td>
                                                                            </tr>
                                                                            @endif
                                                                        @endforeach
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        @else
                                                            <div class="row">
                                                                @if($log->valores_anteriores)
                                                                    <div class="col-md-6 mb-3 mb-md-0">
                                                                        <label class="form-label text-danger fw-bold small"><i class="bi bi-clock-history me-1"></i> Valores Anteriores / Eliminados</label>
                                                                        <pre class="bg-light p-3 rounded-3 shadow-inner" style="font-size: 0.75rem; white-space: pre-wrap;"><code>{{ json_encode($log->valores_anteriores, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</code></pre>
                                                                    </div>
                                                                @endif
                                                                
                                                                @if($log->valores_nuevos)
                                                                    <div class="col-md-{{ $log->valores_anteriores ? '6' : '12' }}">
                                                                        <label class="form-label text-success fw-bold small"><i class="bi bi-check2-circle me-1"></i> Nuevos Valores Creados</label>
                                                                        <pre class="bg-light p-3 rounded-3 shadow-inner border-start border-4 border-success" style="font-size: 0.75rem; white-space: pre-wrap;"><code>{{ json_encode($log->valores_nuevos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</code></pre>
                                                                    </div>
                                                                @endif
                                                            </div>
                                                        @endif
                                                    </div>
                                                    <div class="modal-footer border-0 p-3 pt-0 text-center d-block">
                                                        <a href="{{ route('admin.auditoria.show', $log) }}" class="btn btn-primary rounded-pill px-4" title="Ver en página completa">Ir a página de detalle completo</a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @else
                                        <span class="text-muted small fst-italic">Sin datos</span>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">
                                    <i class="bi bi-shield-slash fs-1 d-block mb-3 text-light"></i>
                                    No hay registros de auditoría que coincidan con los filtros.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @if($registros->hasPages())
                <div class="p-4 border-top">
                    {{ $registros->links('pagination::bootstrap-5') }}
                </div>
            @endif
        </div>
    </div>

    @push('styles')
    <style>
        .shadow-inner { box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06); }
    </style>
    @endpush
</x-app-layout>
