@extends('layouts.app')

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0">Categories</h5>
      @can('create categories')
        <a class="btn btn-primary btn-sm" href="{{ route('admin.categories.create') }}">Add Category</a>
      @endcan
    </div>

    <div class="table-responsive">
      <table @if($categories->count() > 0) id="categories-table" @endif class="table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Slug</th>
            <th>Status</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          @forelse($categories as $category)
            <tr>
              <td>{{ $category->name }}</td>
              <td>{{ $category->slug }}</td>
              <td>{{ $category->is_active ? 'Active' : 'Pending' }}</td>
              <td>
                <div class="d-flex gap-2">
                  @can('update categories')
                    <a href="{{ route('admin.categories.edit', $category) }}" class="btn btn-sm btn-outline-primary">Edit</a>
                  @endcan

                  @can('delete categories')
                    <form method="POST" action="{{ route('admin.categories.destroy', $category) }}">
                      @csrf
                      @method('DELETE')
                      <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this category?')">Delete</button>
                    </form>
                  @endcan
                </div>
              </td>
            </tr>
          @empty
            <tr><td colspan="4" class="text-center py-4">No categories found.</td></tr>
          @endforelse
        </tbody>
      </table>
    </div>

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

@if($categories->count() > 0)
@push('script')
<script>
$(document).ready(function () {
  const $table = $('#categories-table');
  if (!$table.length) return;

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