<?php
/**
 * Created by PhpStorm.
 * User: stana
 * Date: 25.02.2017
 * Time: 14:05
 */

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Validator;


class ChangePasswordController extends Controller
{
    public function index(){
        return view('change_password');
    }

    public function changeUserPassword(Request $request){
        $old_password = Auth::user()->getAuthPassword();
        if (Hash::check($request->old_password, $old_password)) {
            $messages = [
                'old_password.required' => 'Zadejte staré heslo',
                'password.required' => 'Zadejte nové heslo',
                'password.min' => 'Heslo je příliš krátké (> 6 znaků)',
                'password_confirmation.required' => 'Potvrďte nové heslo',
                'password.different' => 'Staré a nové heslo musí být odlišné',
                'password_confirmation.same' => 'Hesla se neshodují',
            ];

            $validator = Validator::make($request->all(), [
                'old_password' => 'required',
                'password' => 'required|min:6|different:old_password',
                'password_confirmation' => 'required|same:password',
            ], $messages);

            if ($validator->fails()) {
                return redirect('change_password')->withErrors($validator)->withInput();
            }

            $user = Auth::user();
            $user->password = bcrypt($request->password);
            $user->save();
            flash('Heslo bylo aktualizováno!', 'success');

        }else{
            flash('Staré heslo není zadáno správně!', 'warning');
        }
        return view('change_password');
    }
}