<?php

namespace App\Http\Livewire;

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

class Usuarios extends Component
{
    use WithPagination;

    public $name, $email, $password, $rol, $usuario_id;
    public $modoEdicion = false;
    public $busqueda = '';

    protected $paginationTheme = 'bootstrap';

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

    public function render()
    {
        $usuarios = User::where('name', 'like', '%'.$this->busqueda.'%')
            ->orWhere('email', 'like', '%'.$this->busqueda.'%')
            ->orderBy('name')
            ->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),
            'rol' => $this->rol,
        ]);

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

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

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

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

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

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

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

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