<?php

namespace App\Components\Admin\Role;

use App\Models\User\Role;
use Livewire\Component;
use Livewire\WithPagination;

class RoleIndex extends Component {

    use WithPagination;

    #[Url]
    public int $perPage = 25;

    #[Url]
    public string $search = '';

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

    public function updatedPerPage(): void {
        $this->resetPage();
    }

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

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