<?php

namespace App\Components\Admin\Users;

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

class UserIndex extends Component {
    use WithPagination;

    public int $perPage = 25;
    public string $search = '';
    public ?string $role = null;

    public function render() {
        $users = User::query()
            ->with('roles')
            ->when($this->search, fn($q) => $q->where('name_first', 'like', "%{$this->search}%")
                ->orWhere('name_last', 'like', "%{$this->search}%")
                ->orWhere('email_address', 'like', "%{$this->search}%")
            )
            ->when($this->role, fn($q) => $q->whereHas('roles', fn($r) => $r->where('name', $this->role))
            )
            ->paginate($this->perPage);

        return view('components.admin.users.user-index', [
            'users' => $users,
            'roles' => Role::orderBy('name')->get()
        ]);
    }
}
