<?php

namespace App\Livewire\Users;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Spatie\Permission\Models\Role;

class AdminUsers extends Component
{
    public string $search = '';

    public $roles;

    public function mount(): void
    {
        abort_unless(Auth::user()->can('view users'), 403);
        $this->roles = Role::orderBy('name')->get();
    }

    public function getUsersProperty()
    {
        return User::with('roles')
            ->when($this->search, fn ($q) => $q->where(fn ($q2) => $q2
                ->where('name', 'like', '%'.$this->search.'%')
                ->orWhere('email', 'like', '%'.$this->search.'%')))
            ->orderBy('name')
            ->get();
    }

    public function deleteUser(int $userId): void
    {
        if ($userId === Auth::id()) {
            $this->dispatch('notify', 'No puedes eliminarte a ti mismo.');

            return;
        }
        User::findOrFail($userId)->delete();
        $this->dispatch('notify', 'Usuario eliminado.');
    }

    public function render()
    {
        return view('livewire.users.admin-users');
    }
}
