<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\PasswordExpiredRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Auth;
use Flash;
use Illuminate\Support\Facades\Redirect;
use Session;

class ExpiredPasswordController extends Controller
{

    public function expired()
    {
        return view('auth.passwords.expired');
    }
    

    public function postExpired(PasswordExpiredRequest $request)
    {
        // Checking current password
        if (!Hash::check($request->current_password, $request->user()->password)) {
            return redirect()->back()->withErrors(['current_password' => 'Current password doesnot match']);
        }
        $oldPassword = $request->user()->password;
        $hashedPwd = bcrypt($request->password);
        if($hashedPwd == $oldPassword){
            return redirect()->back()->withErrors(['new_password' => 'New password must be different from old one.']);
        }
        $request->user()->update([
            'password' => $hashedPwd,
            'password_changed_at' => Carbon::now()->toDateTimeString()
        ]);

        Auth::logout();

        Session::flash('message', 'Password changed successfully, Please login again with new passowrd');

        return Redirect::intended();
    }
}