<?php

namespace App\Livewire\Settings;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;

class Changepassword extends Component
{
    use LivewireAlert;

    public $current_password;
    public $new_password;
    public $new_password_confirmation;

    protected $rules = [
        'current_password' => 'required',
        'new_password' => 'required|min:8|different:current_password',
        'new_password_confirmation' => 'required|same:new_password',
    ];

    public function changePassword()
    {
        $this->validate();

        if (Auth::check()) {
            if (Hash::check($this->current_password, Auth::user()->password)) {
                $user = Auth::user();
                $user->password = Hash::make($this->new_password);
                $user->save();

                $this->alert('success', 'Password changed successfully', [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            } else {
                $this->alert('error', 'Current password incorrect!', [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        }
    }

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