<?php

declare(strict_types=1);

namespace App\Http\Middleware;

// use App\Models\Permission;
// use App\Models\RoleAccess;
use Auth;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Symfony\Component\HttpFoundation\Response;

class HasRouteAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     *
     * @throws AuthorizationException
     */
    public function handle($request, Closure $next)
    {
        $action = $request->route()->getActionName();
        $permissionRoutes = config('permission-routes');
        $permissionKey = '';
        foreach ($permissionRoutes as $key => $routes) {
            if (in_array($action, $routes)) {
                $permissionKey = $key;
                break;
            }
        }

        if ($permissionKey == '' || Auth::user()->userRole->hasAccess($permissionKey)) {
            return $next($request);
        }
        return abort(Response::HTTP_FORBIDDEN, '403 Access Forbidden');
    }
}
