<?php

namespace App\Components\Admin\Permission;

use App\Models\User\Permission;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class PermissionIndex extends Component {
    use WithPagination;

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

    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,
        ]);
    }
}
