<?php
/**
 * Created by PhpStorm.
 * User: jirislav
 * Date: 6.5.17
 * Time: 13:57
 */

namespace App\Http\Middleware;

use Closure;
use Entrust;
use Redirect;

class Locale
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $desiredLocale = $request->get('locale', false);

        if (in_array($desiredLocale, config('app.languages'))) {

            $request->session()->put('locale', $desiredLocale);

        } else if (!$request->session()->has('locale')) {
            $request->session()->put('locale', $request->getPreferredLanguage(config('app.languages')));
        }

        app()->setLocale($request->session()->get('locale'));

        return $next($request);
    }

}