@extends('layouts.app')
@section('title','Sharing Logs - NGBVD')

@section('content')
@include('integrations.partials.settings_style')
<div class="ni-shell">
    <div class="ni-hero">
        <div>
            <span class="ni-kicker">Zero Trust API Audit Trail</span>
            <h2 class="ni-title">Sharing Logs</h2>
            <p class="ni-subtitle">Detailed inbound and outbound API activity: client, IP, endpoint, data accessed, timing, rate limits, signatures and responses.</p>
        </div>
        <div class="ni-actions">
            <a href="{{ url('/integrations') }}" class="btn ngbvd-btn-soft"><i class="ti-arrow-left"></i> Overview</a>
            <a href="{{ url('/integrations/api-clients') }}" class="btn ngbvd-btn-primary"><i class="ti-key"></i> API Clients</a>
        </div>
    </div>

    <div class="ni-layout">
        <div class="ni-card">
            <div class="ni-card-body">
                <div class="ni-heading">
                    <div><h4>API Access and Data Sharing Register</h4><p>Every protected GET/POST API call is recorded here after the zero-trust middleware validates the client.</p></div>
                    <span class="ni-heading-icon"><i class="ti-clipboard"></i></span>
                </div>
                <div class="ni-table-wrap">
                    <table class="table table-hover ngbvd-modern-table" data-datatable="false" >
                        <thead>
                            <tr>
                                <th>Date/Time</th>
                                <th>Client</th>
                                <th>Direction</th>
                                <th>Endpoint</th>
                                <th>IP / Where</th>
                                <th>Data Accessed</th>
                                <th>Duration</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($logs as $log)
                            @php
                                $status=strtolower($log->status ?? 'pending');
                                $badge=$status==='success'?'ni-success':(in_array($status,['failed','error'])?'ni-danger':($status==='retrying'?'ni-warning':'ni-muted'));
                                $modalId='integrationLogModal'.($log->id ?? md5($log->uuid ?? $loop->index));
                                $client = $log->apiClient ?? null;
                            @endphp
                            <tr>
                                <td><strong>{{ optional($log->created_at)->format('d M Y') ?: 'N/A' }}</strong><br><small class="text-muted">{{ optional($log->created_at)->format('H:i:s') }}</small></td>
                                <td><strong>{{ $client->name ?? $log->system_name ?? $log->integration_name ?? 'Unknown Client' }}</strong><br><small class="text-muted">{{ $client->client_key ?? 'No key captured' }}</small></td>
                                <td><span class="ni-badge {{ ($log->direction ?? '') === 'inbound' ? 'ni-blue' : 'ni-warning' }}">{{ ucfirst($log->direction ?: 'outbound') }}</span></td>
                                <td><code class="ni-code">{{ $log->http_method ?: 'GET' }} {{ $log->endpoint ?: '-' }}</code><br><small>{{ $log->route_name ?: '' }}</small></td>
                                <td><strong>{{ $log->ip_address ?: 'N/A' }}</strong><br><small>{{ $log->geo_city ?: '' }} {{ $log->geo_country ?: '' }}</small></td>
                                <td><small>{{ \Illuminate\Support\Str::limit($log->data_accessed ?: $log->record_type ?: 'N/A', 100) }}</small><br>@if($log->response_record_count !== null)<span class="ni-chip">{{ $log->response_record_count }} records</span>@endif</td>
                                <td>{{ $log->duration_ms !== null ? number_format($log->duration_ms).' ms' : '-' }}<br><small>{{ $log->response_size_bytes ? number_format($log->response_size_bytes).' bytes' : '' }}</small></td>
                                <td><span class="ni-badge {{ $badge }}">{{ ucfirst($status) }}</span><br><small>HTTP {{ $log->response_code ?: '-' }}</small></td>
                                <td><button type="button" class="btn btn-sm ngbvd-btn-soft" data-toggle="modal" data-target="#{{ $modalId }}"><i class="ti-eye"></i> View</button></td>
                            </tr>
                        @empty
                            <tr><td colspan="9"><div class="ni-empty"><i class="ti-clipboard"></i><strong>No integration logs found</strong><span>Sharing logs will appear here after protected API activity is recorded.</span></div></td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="ni-card ni-panel ni-filter-card">
            <div class="ni-card-body">
                <div class="ni-heading"><div><h4>Filter Logs</h4><p>Review by client, endpoint, IP, status or date.</p></div><span class="ni-heading-icon"><i class="ti-filter"></i></span></div>
                <form method="GET" action="{{ url('/integrations/logs') }}">
                    <div class="form-group"><label>Client/System</label><input class="form-control" name="client" value="{{ request('client') }}" placeholder="UBOS, NSR, client key"></div>
                    <div class="form-group"><label>Integration/System</label><input class="form-control" name="integration_name" value="{{ request('integration_name') }}" placeholder="UBOS, Sauti, GBV Portal"></div>
                    <div class="form-group"><label>Endpoint</label><input class="form-control" name="endpoint" value="{{ request('endpoint') }}" placeholder="/api/v2/reference-data"></div>
                    <div class="form-group"><label>IP Address</label><input class="form-control" name="ip_address" value="{{ request('ip_address') }}" placeholder="41.210..."></div>
                    <div class="form-group"><label>Status</label><select class="form-control" name="status" data-no-selectize="true"><option value="">All statuses</option>@foreach(['pending'=>'Pending','success'=>'Success','failed'=>'Failed','retrying'=>'Retrying'] as $value=>$label)<option value="{{ $value }}" {{ request('status')===$value?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
                    <div class="form-group"><label>Direction</label><select class="form-control" name="direction" data-no-selectize="true"><option value="">All</option><option value="inbound" {{ request('direction')==='inbound'?'selected':'' }}>Inbound</option><option value="outbound" {{ request('direction')==='outbound'?'selected':'' }}>Outbound</option></select></div>
                    <div class="form-group"><label>HTTP Method</label><select class="form-control" name="http_method" data-no-selectize="true"><option value="">All</option>@foreach(['GET','POST','PUT','PATCH','DELETE'] as $method)<option value="{{ $method }}" {{ request('http_method')===$method?'selected':'' }}>{{ $method }}</option>@endforeach</select></div>
                    <div class="row"><div class="col-md-6 form-group"><label>From</label><input type="date" class="form-control" name="date_from" value="{{ request('date_from') }}"></div><div class="col-md-6 form-group"><label>To</label><input type="date" class="form-control" name="date_to" value="{{ request('date_to') }}"></div></div>
                    <button class="btn ngbvd-btn-primary btn-block"><i class="ti-filter"></i> Apply Filters</button>
                    <a class="btn ngbvd-btn-soft btn-block mt-2" href="{{ url('/integrations/logs') }}"><i class="ti-close"></i> Clear</a>
                </form>
            </div>
        </div>
    </div>
</div>

@foreach($logs as $log)
    @php
        $status=strtolower($log->status ?? 'pending');
        $badge=$status==='success'?'ni-success':(in_array($status,['failed','error'])?'ni-danger':($status==='retrying'?'ni-warning':'ni-muted'));
        $modalId='integrationLogModal'.($log->id ?? md5($log->uuid ?? $loop->index));
        $client = $log->apiClient ?? null;
    @endphp
    <div class="modal fade ni-modal" id="{{ $modalId }}" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header"><div><h5 class="modal-title">Integration Log Detail</h5><small class="text-muted">{{ $log->uuid ?: 'Log reference not available' }}</small></div><button type="button" class="close" data-dismiss="modal"><span>&times;</span></button></div>
                <div class="modal-body">
                    @include('integrations.partials.log_detail_grid', ['log' => $log, 'client' => $client, 'badge' => $badge, 'status' => $status])
                </div>
                <div class="modal-footer"><a class="btn ngbvd-btn-soft" href="{{ url('/integrations/logs/'.$log->uuid) }}"><i class="ti-new-window"></i> Open Full Page</a><button type="button" class="btn ngbvd-btn-primary" data-dismiss="modal"><i class="ti-check"></i> Close</button></div>
            </div>
        </div>
    </div>
@endforeach
@endsection
