<?php
/**
 * Created by PhpStorm.
 * User: stana
 * Date: 25.02.2017
 * Time: 17:33
 */

namespace App\Http\Controllers;

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

class ChangeEmailController
{
    public function index(){
        $user = Auth::user();
        return view('change_email', ['email_old' => $user->email]);
    }

    public function changeUserEmail(Request $request){

        $messages = [
            'email.required' => 'Zadejte nový e-mail',
            'email.unique' => 'Zadaný e-mail již někdo používá',
            'email.max' => 'E-mail je příliš dlouhý',
            'email.min' => 'E-mail je příliš krátký',
            'email.email' => 'Zadejte e-mail ve správném formátu',
        ];

        $validator = Validator::make($request->all(), [
            'email' => 'required|email|max:255|min:5|unique:users',
        ], $messages);

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

        $user = Auth::user();
        $user->email = $request->email;
        $user->save();
        flash('E-mail byl aktualizován!', 'success');
        return view('change_email', ['email_old' => $user->email]);
    }
}