<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\CheckAccessController;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Modules\User\Services\ModuleService;

class CheckRole
{
    public function __construct(private ModuleService $moduleService)
    {
    }

    /**
     * Handle an incoming request.
     * Redirect user to home page if he has not the privilege to make the next action
     * @param  Request  $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $path = explode('.',Route::currentRouteName())[0];

        $canAccess = $this->moduleService->checkModuleAccess($path,Auth::id());

        if(!$canAccess){
            return abort(403);
        }
        return $next($request);
    }
}
