<?php

namespace App\Components\Admin\Permission;

use App\Models\User\Permission;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class PermissionIndex extends Component {
    use AuthorizesRequests, WithPagination;

    #[Url]
    public int $perPage = 25;
    #[Url]
    public string $search = '';

    public function mount(): void {
        $this->authorize('permissions.view');
    }

    public function updatedSearch() {
        $this->resetPage();
    }

    public function render() {
        $permissions = Permission::query()
            ->withCount('roles')
            ->when($this->search, fn($q) => $q->where('name', 'like', "%{$this->search}%")
                ->orWhere('label', 'like', "%{$this->search}%")
            )
            ->orderBy('group')
            ->orderBy('label')
            ->paginate($this->perPage);

        return view('components.admin.permission.permission-index', [
            'permissions' => $permissions,
        ]);
    }
}
