<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Profile extends Component
{
    public $name, $email, $password, $passwordConfirm, $update = false, $editPassword = false, $errorConfirm;

    protected $rules = [
        'name' => 'required',
        'email' => 'required'
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'email.required' => 'La mail è obbligatoria',
        'password.required' => 'La password è obbligatoria',
        'passwordConfirm.required' => 'La conferma password è obbligatoria',
    ];

    public function resetFields(){
        //$this->name = '';
        //$this->email = '';
        $this->errorConfirm = '';
        $this->password = '';
        $this->newPassword = '';
    }

    public function mount()
    {
        $this->name = \Auth::user()->name;
        $this->email = \Auth::user()->email;
    }

    public function render()
    {
        
        return view('livewire.profile');
    }

    public function edit()
    {
        //$this->resetFields();
        $this->update = true;
    }

    public function editPwd()
    {
        $this->resetFields();
        $this->editPassword = true;
    }

    public function save()
    {

        $this->validate();
        try {
            $user = \Auth::user();
            $user->name = $this->name;
            $user->email = $this->email;
            if ($this->password != '')
            {
                $user->password = bcrypt($this->password);
            }
            $user->save();
            session()->flash('success','Dato creato');
            $this->resetFields();
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function updatePwd()
    {
        $this->errorConfirm = '';
        $this->validate(['password' => 'required', 'passwordConfirm' => 'required']);
        try {
            $user = \Auth::user();
            if ($this->password == $this->passwordConfirm)
            {
                $user->password = bcrypt($this->password);
                $user->save();
                session()->flash('success','Dato creato');
                $this->resetFields();
                $this->update = false;
            }
            else
            {
                $this->errorConfirm = 'Le password non coincidono';
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancel()
    {
        $this->resetFields();
        $this->update = false;
        $this->editPassword = false;
    }

}

