@extends('nexus.layouts.app')

@section('page-title', 'Audit Log')
@section('sys-mode', 'AUDIT LOG')

@section('content')

    {{-- PAGE HEADER --}}
    <div class="page-header">
        <div>
            <h1>AUDIT <em>LOG</em></h1>
            <p class="page-header-sub">System event history and decision trail</p>
        </div>
        <div class="page-header-right">
            <div class="stat-label">Total Records</div>
            <div class="stat-value">{{ number_format($auditLogs->total()) }}</div>
        </div>
    </div>

    {{-- FILTERS --}}
    <div class="filter-bar">
        <form method="GET" action="/nexus/audit" id="filterForm" style="display: flex; gap: 12px; flex-wrap: wrap; align-items: center; width: 100%;">

            <select name="event" class="filter-select" onchange="document.getElementById('filterForm').submit()">
                <option value="">All Events</option>
                @foreach ($eventTypes ?? [] as $type)
                    <option value="{{ $type }}" {{ request('event') === $type ? 'selected' : '' }}>{{ $type }}</option>
                @endforeach
            </select>

            <input type="text"
                   name="user_id"
                   class="filter-input"
                   placeholder="User ID"
                   value="{{ request('user_id') }}"
                   style="width: 100px;">

            <input type="text"
                   name="session_id"
                   class="filter-input"
                   placeholder="Session ID"
                   value="{{ request('session_id') }}"
                   style="width: 110px;">

            <input type="date"
                   name="date_from"
                   class="filter-input"
                   value="{{ request('date_from') }}"
                   style="width: 150px;">

            <span class="text-dim mono" style="font-size: 9px;">TO</span>

            <input type="date"
                   name="date_to"
                   class="filter-input"
                   value="{{ request('date_to') }}"
                   style="width: 150px;">

            <button type="submit" class="btn-sm btn-ghost">FILTER</button>

            @if (request()->hasAny(['event', 'user_id', 'session_id', 'date_from', 'date_to']))
                <a href="/nexus/audit" class="btn-sm btn-ghost" style="text-decoration: none;">CLEAR</a>
            @endif

            <div style="margin-left: auto;">
                <button type="button" class="btn-export" onclick="nexus.exportAuditCsv()">EXPORT CSV</button>
            </div>
        </form>
    </div>

    {{-- AUDIT TABLE --}}
    @if ($auditLogs->count() > 0)
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Timestamp</th>
                    <th>Event</th>
                    <th>Actor</th>
                    <th>User</th>
                    <th>Session</th>
                    <th>Context</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($auditLogs as $log)
                    @php
                        $logId = $log->id;
                        $logEvent = $log->event ?? '';
                        $logActorType = $log->actor_type ?? '';
                        $logActorId = $log->actor_id ?? '';
                        $logUserId = $log->subject_user_id ?? '';
                        $logSessionId = $log->nexus_session_id ?? '';
                        $logContext = $log->context ?? null;
                        $logNotes = $log->notes ?? '';
                        $logCreated = $log->created_at ?? '';
                        $hasContext = !empty($logContext);
                    @endphp
                    <tr>
                        <td class="col-num">{{ $logId }}</td>
                        <td class="text-dim" style="font-size: 10px; white-space: nowrap;">
                            {{ $logCreated ? \Carbon\Carbon::parse($logCreated)->format('M d H:i:s') : '' }}
                        </td>
                        <td>
                            <span class="chip chip-sm {{ str_contains($logEvent, 'fail') || str_contains($logEvent, 'reject') ? 'chip-error' : (str_contains($logEvent, 'login') ? 'chip-active' : 'chip-completed') }}">
                                {{ $logEvent }}
                            </span>
                        </td>
                        <td class="text-grey">
                            {{ $logActorType }}{{ $logActorId ? ' #' . $logActorId : '' }}
                        </td>
                        <td class="text-dim">{{ $logUserId ?: '-' }}</td>
                        <td class="text-dim">{{ $logSessionId ?: '-' }}</td>
                        <td>
                            @if ($hasContext)
                                <span class="context-toggle" onclick="nexus.toggleContext({{ $logId }})">
                                    VIEW
                                </span>
                            @elseif ($logNotes)
                                <span class="text-dim" style="font-size: 10px;">{{ \Illuminate\Support\Str::limit($logNotes, 40) }}</span>
                            @else
                                <span class="text-dim">-</span>
                            @endif
                        </td>
                    </tr>
                    @if ($hasContext)
                        <tr>
                            <td colspan="7" style="padding: 0;">
                                <div class="context-json" id="context-{{ $logId }}">@php
                                    $decoded = is_string($logContext) ? json_decode($logContext, true) : $logContext;
                                    if (is_array($decoded)) {
                                        array_walk_recursive($decoded, function (&$val) {
                                            if (is_float($val)) $val = round($val, 4);
                                        });
                                        echo json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                                    } else {
                                        echo $logContext;
                                    }
                                @endphp</div>
                            </td>
                        </tr>
                    @endif
                @endforeach
            </tbody>
        </table>

        {{-- PAGINATION --}}
        @if ($auditLogs->hasPages())
            <div class="pagination">
                @if ($auditLogs->onFirstPage())
                    <span class="disabled">PREV</span>
                @else
                    <a href="{{ $auditLogs->appends(request()->query())->previousPageUrl() }}">PREV</a>
                @endif

                @php
                    $currentPage = $auditLogs->currentPage();
                    $lastPage = $auditLogs->lastPage();
                    $start = max(1, $currentPage - 3);
                    $end = min($lastPage, $currentPage + 3);
                @endphp

                @for ($p = $start; $p <= $end; $p++)
                    @if ($p === $currentPage)
                        <span class="current">{{ $p }}</span>
                    @else
                        <a href="{{ $auditLogs->appends(request()->query())->url($p) }}">{{ $p }}</a>
                    @endif
                @endfor

                @if ($auditLogs->hasMorePages())
                    <a href="{{ $auditLogs->appends(request()->query())->nextPageUrl() }}">NEXT</a>
                @else
                    <span class="disabled">NEXT</span>
                @endif
            </div>
        @endif

    @else
        <div class="empty-state">
            <span class="empty-state-text">No audit records found{{ request()->hasAny(['event', 'user_id', 'session_id', 'date_from', 'date_to']) ? ' matching filters' : '' }}</span>
        </div>
    @endif

@endsection
