<?php

namespace App\Http\Controllers\Auth;

use App\Events\BulkUpdates;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Models\AssetHistory;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Hash;

class ChangePasswordController extends Controller
{
    public function update()
    {
        $this->validate(request(), [
            'current-password' => 'required',
            'password' => 'required|confirmed',
            'password_confirmation' => 'required',
        ]);

        $user = User::find(Auth::id());
        $userName = $user->first_name . ' ' . $user->last_name;
        if (!Hash::check(request('current-password'), $user->password)) {
            return redirect('change-password')
                ->withErrors([
                    'current-password' => 'Current password is incorrect',
                ]);
        }

        $password = Hash::make(request('password'));
        $user->update(['password' => $password]);

        $description = __('history.PasswordChanged', [
            'userName' => $userName,
        ]);
        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'password_changed',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];
        event(new BulkUpdates($assetHistory));

        return redirect('change-password')->with('status', 'Password Changed!');
    }
}
