<?php

namespace App\Http\Livewire;

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

class UserController extends Component
{
    use WithPagination;
    public $buscador = '', $modal = false;
    public $user, $role_id, $password;

    protected $rules = [
        'user.name' => 'required|min:3',
        'user.email' => 'required|email',
        'user.password' => 'required|min:6',
    ];

    public function updatingBuscador()
    {
        $this->resetPage();
    }

    public function render()
    {
        $users = User::where('email','like','%'.$this->buscador.'%')->paginate(10);
        return view('user',[
            'users' => $users,
            'roles' => Role::all(),
        ]);
    }

    
    public function create()
    {
        $this->clearInputs();
        $this->user = new User();

        $this->showModal();
    }

    public function edit(User $user)
    {
        $this->user = $user;
        $this->role_id = $this->user->roles->first()->id;
        $this->showModal();
    }

    public function save()
    {
        if(!isset($this->user->id))
        {
            $this->validate([
                'user.email' => 'required|min:3|unique:users,email',
            ]);
        }
        $this->validate([
            'user.name' => 'required|min:3',
            // 'password' => 'required|min:6'
        ]);
        
        $this->user->password = Hash::make($this->password);
        
        $this->user->save();
        
        $this->user->roles()->sync($this->role_id);

        session()->flash('message',$this->user->id?"El usuario se ha actualizado correctamente!":"El usuario se ha registrado correctamente!");

        $this->clearInputs();
        $this->closeModal();
    }


    public function showModal()
    {
        $this->modal = true;
    }

    public function closeModal()
    {
        $this->modal = false;
    }

    public function clearInputs()
    {
        $this->reset();
    }
}
