<?php

namespace Sartoric\ModularCms\Middleware;

use Closure;

class ViewRights
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $dotpos = strrpos($request->route()->getName(), '.');
        $routecheck = substr($request->route()->getName(), 0, $dotpos?$dotpos:strlen($request->route()->getName()));
        // If the user doesn't have the rights for that menu it will be redirected to login form
        if (!$request->user()->isSuperAdmin() &&
            ($routecheck && !$request->user()->menuitems()->contains('link', $routecheck))) {
//            return redirect('/');
            return redirect('/home');
        }
        return $next($request);
    }
}