<?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)
    {
        $target = explode('.',Route::currentRouteName());

        if ($target[1] == 'grid')
        {
            $target[1] = 'index';
        }
        elseif (in_array($target[1],['destroy','destroyAll','restore','restoreAll']))
        {
            $target[1] = 'delete';
        }
        elseif (in_array($target[1],['create']))
        {
            $target[1] = 'store';
        }
        elseif (in_array($target[1],['edit']))
        {
            $target[1] = 'update';
        }

        $canAccess = $this->moduleService->checkModuleAccess([
            'status' => $target[0] ?? null,
            'path' => $target[1] ?? null,
            'dashboard'=>'admin'
        ],Auth::id());

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