<?php
namespace App\Http\Livewire;

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

class Usuarios extends Component
{
    use WithPagination;

    public $name, $email, $password, $user_id;
    public $modoEdicion = false;

    protected $rules = [
        'name' => 'required|string',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:6',
    ];

    public function render()
    {
        $usuarios = User::paginate(5);
        return view('livewire.usuarios', compact('usuarios'));
    }

   /*public function guardar()
    {
        $this->validate();

        User::create([
            'name' => $this->name,
            'email' => $this->email,
            'password' => Hash::make($this->password),
        ]);

        session()->flash('message', 'Usuario creado correctamente.');
        $this->resetCampos();
    }*/

        

    public function editar($id)
    {
        $usuario = User::findOrFail($id);
        $this->user_id = $usuario->id;
        $this->name = $usuario->name;
        $this->email = $usuario->email;
        $this->modoEdicion = true;
    }

    public function actualizar()
    {
        $this->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email,' . $this->user_id,
        ]);

        $usuario = User::findOrFail($this->user_id);
        $usuario->update([
            'name' => $this->name,
            'email' => $this->email,
        ]);

        session()->flash('message', 'Usuario actualizado.');
        $this->resetCampos();
    }

    public function eliminar($id)
    {
        User::destroy($id);
        session()->flash('message', 'Usuario eliminado.');
    }

    public function cancelar()
    {
        $this->resetCampos();
    }

    private function resetCampos()
    {
        $this->reset(['name', 'email', 'password', 'user_id', 'modoEdicion']);
    }


}
