<?php

namespace Sartoric\ModularCms\Middleware;

use Sartoric\ModularCms\Models\Setting;
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',
                        (Setting::appSetting('app-admin')?Setting::appSetting('app-admin').'/':'').$routecheck
                    )
            )
        ) {
//            return redirect('/');
            return redirect('/home');
        }
        return $next($request);
    }
}
