<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class PasswordController extends Controller
{


    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function change()
    {
        return view('auth.passwords.change');
    }
    public function update(Request $request)
    {
        $user=Auth::user();
        $request->validate($this->rules(), $this->validationErrorMessages());
        $user->password = Hash::make($request->input('password'));
        $user->setRememberToken(Str::random(60));
        $user->save();
        event(new PasswordReset($user));
        Auth::guard()->login($user);
        return view('auth.passwords.changed');
    }
    protected function rules()
    {
        return [
            'old_password' => ['required',function($attr,$val,$fail){
                $oldPwd=Auth::user()['password'];
                if(!Hash::check($val,$oldPwd)){
                    $fail('旧密码输入不匹配');
                }
            }],
            'password' => 'required|confirmed|min:6',
        ];
    }
    /**
     * Get the password reset validation error messages.
     *
     * @return array
     */
    protected function validationErrorMessages()
    {
        return [
            'old_password.required'=>'请输入正确的旧密码',
            'password.required'=>'不得为空',
            'password.min'=>'密码至少要输入 :min 位或以上',
            'password.confirmed'=>'两次密码必须一致'
        ];
    }
}
