<?php

namespace App\Http\Middleware;

use App\Helpers\Helper;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RouteAccessMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $exceptRoute = array('admin.dashboard');
        if(in_array($request->route()->getName(), $exceptRoute)){
            return $next($request);
        }else{
            if(auth()->check() == true){
                // dd(Helper::roleHasPermission($request->route()->getName()));
                if(Helper::roleHasPermission($request->route()->getName())){
                    return $next($request);
                }else{
                    abort(403, 'Access denied');
                }
                
            }else{
                // abort(403, 'Access denied'); 
            }
            
        }
        return $next($request);
    }
}
