<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\CheckAccessController;
use App\Models\Module;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class CheckRole
{
    /**
     * 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)
    {

        $action=explode('.',Route::currentRouteName())[0];
        $canAccess=$request->user()->canAccess($action);

        $moduleIsActive = Module::where('path', $action)->first();

        if ($moduleIsActive->deleted_at){
            return redirect('/admin/');
        }

        if (in_array($request->user()->role, ['super_admin', 'admin']) || $request->user()->admin_token){
            $canAccess = true;
        }

        if(!$canAccess){
            return redirect('/admin/');
        }
        



        return $next($request);
    }
}
