<?php

namespace App\Http\Livewire\User;

use App\Models\User;
use Livewire\Component;
use Illuminate\Support\Str;

class EditUser extends Component
{
    public $user, $name, $email, $type, $status;
    protected $messages = [
        'email.required' => 'El nombre de usuario es obligatorio',
        'email.unique' => 'El nombre de usuario ya existe',
        'name.required' => 'El nombre completo del personal es obligatiorio'
    ];

    public function rules()
    {
        return
            [
                'email' => "required|max:100|unique:users,email," . optional($this->user)->id,
                'name' => 'required'
            ];
    }

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }
    public function mount(User $user)
    {
        $this->user = $user;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->type = $user->type;
        $this->status = $user->status;
    }
    public function render()
    {
        return view('livewire.user.edit-user');
    }

    public function update()
    {
        $this->name = Str::lower($this->name);
        $this->validate();
        $this->user->update([
            'name' => Str::lower($this->name),
            'email' => $this->email,
            'type' => $this->type,
            'status' => $this->status,
        ]);
        $this->emitTo('user.index-user', 'render');
        $this->emit('notify', 'Personal Actualizado');
    }
}
