<?php

namespace App\Http\Livewire\User;

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

class PerfilUser extends Component
{
    public $user, $email, $old_password, $password, $repeat_password;
    public $name, $type;

    protected $messages = [
        'email.required' => 'El nombre de usuario es obligatorio',
        'email.unique' => 'El nombre de usuario ya existe'
    ];

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

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function mount()
    {
        $this->user = User::find(Auth::user()->id);
        $this->name = $this->user->name;
        $this->email = $this->user->email;
        $this->type = $this->user->type;
        if ($this->type == '0') {
            $this->type = 'ÁREA DE MECÁNICA';
        } elseif ($this->type == '1') {
            $this->type = 'ÁREA DE ADMINISTRACIÓN';
        } else {
            $this->type = 'ADMINISTRADOR';
        }
    }
    public function render()
    {
        return view('livewire.user.perfil-user')
            ->layout('app');
    }

    public function updateEmail()
    {
        $this->validate();
        $this->user->update([
            'email' => $this->email
        ]);
        $this->emit('notify', 'Nombre de usuario actualizado');
    }

    public function updatePassword()
    {
        if (Str::length($this->password) >= 8) {
            if (Hash::check($this->old_password, $this->user->password)) {
                if ($this->password == $this->repeat_password) {
                    $this->user->update([
                        'password' => Hash::make($this->password)
                    ]);
                    $this->emit('notify', 'Contraseña Actualizada');
                    $this->reset(['repeat_password', 'password', 'old_password']);
                } else {
                    $this->emit('error', [
                        'title' => 'La contraseñas no coinciden',
                        'subtitile' =>  '',
                        'footer' => 'LISAC Motors'
                    ]);
                }
            } else {
                $this->emit('error', [
                    'title' => 'La contraseña antigua no es la correcta',
                    'subtitile' =>  '',
                    'footer' => 'LISAC Motors'
                ]);
            }
        } else {
            $this->emit('error', [
                'title' => 'Mínimo de 8 caracteres para la nueva contraseña',
                'subtitile' =>  '',
                'footer' => 'LISAC Motors'
            ]);
        }
    }
}
