<?php

namespace App\Livewire\User;

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

class Index extends Component
{
    use WithPagination;

    public $search;
    public function updatingPage()
    {
        // Resetear a la primera página cuando cambian otros filtros
        $this->resetPage();
    }

    public function render()
    {
        $users = $this->searchElement();
        return view('livewire.user.index', ['users' => $users]);
    }

    public function mount()
    {
        $this->users = User::all();
    }

    public function searchElement()
    {
        $search = $this->search;
        return Person::query()
            ->join('users', 'people.id', '=', 'users.person_id')
            ->where(function ($query) use ($search) {
                $query->where('people.first_name', 'like', "%{$search}%")
                    ->orWhere('people.second_name', 'like', "%{$search}%")
                    ->orWhere('users.email', 'like', "%{$search}%");
            })
            ->where('users.role_id', '!=', 2)
            ->select('people.*', 'users.email')
            ->paginate(10);
    }
}
