@extends('layouts.app')

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="card">
    <div class="card-header"><h5 class="mb-0">{{ ($isSuperAdmin ?? false) ? 'All Trust Score Events' : 'Trust Score Events' }}</h5></div>

    @can('view trust score')
      <div class="table-responsive">
        <table @if($events->count() > 0) id="trust-score-events-table" @endif class="table">
          <thead>
            <tr>
              @if($isSuperAdmin ?? false)<th>User</th>@endif
              <th>Score Change</th>
              <th>Reason</th>
              <th>Reviewer</th>
              <th>Date</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            @forelse($events as $event)
            <tr>
              @if($isSuperAdmin ?? false)<td>{{ $event->user->name ?? 'N/A' }}</td>@endif
              <td>{{ $event->score_change }}</td>
              <td>{{ $event->reason }}</td>
              <td>{{ $event->reviewer->name ?? 'System' }}</td>
              <td>{{ $event->created_at->format('Y-m-d H:i') }}</td>
              <td>
                @if(auth()->check() && auth()->user()->hasRole('super admin'))
                  <form method="POST" action="{{ route('admin.trust-scores.destroy', $event) }}">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this trust score event?')">Delete</button>
                  </form>
                @else
                  <span class="text-muted">-</span>
                @endif
              </td>
            </tr>
            @empty
            <tr><td colspan="{{ ($isSuperAdmin ?? false) ? 6 : 5 }}" class="text-center py-4">No trust score records found.</td></tr>
            @endforelse
          </tbody>
        </table>
      </div>
    @else
      <div class="card-body"><div class="alert alert-warning mb-0">You do not have permission to view trust score events.</div></div>
    @endcan

    <div class="card-body">{{ $events->links() }}</div>
  </div>
</div>
@endsection

@if($events->count() > 0)
@push('script')
<script>
$(document).ready(function () {
  const $table = $('#trust-score-events-table');
  if (!$table.length) return;
  const dateColumnIndex = {{ ($isSuperAdmin ?? false) ? 4 : 3 }};

  $table.DataTable({
    responsive: false,
    scrollX: true,
    pageLength: 10,
    lengthMenu: [5, 10, 25, 50, 100],
    order: [[dateColumnIndex, 'desc']],
    columnDefs: [{ orderable: false, targets: -1 }]
  });
});
</script>
@endpush
@endif
