<?php

namespace App\Http\Middleware;

use App\Models\ClientRole;
use App\Models\Menu;
use Closure;
use Illuminate\Support\Facades\Auth;
use Route;
use App\User;
class AccessControlMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->user_type==1){
            return $next($request);
        }
        $route= Route::currentRouteName();
        $found=0;
        $user= User::with('roles')->find(Auth::id());
        foreach ($user->roles as $role){
            $decodedRoutes= json_decode($role->routes,true);
            if(!empty($decodedRoutes)){
                foreach ($decodedRoutes as $val){
                    if($val==$route){
                        $found=1; break;
                    }
                }
            }

        }
        if($found==1){
            return $next($request);
        }else{
            abort(403, 'Access denied');
        }

    }
}
