<?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 CheckRoleEmplyee
{
    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[2] == 'grid')
        {
            $target[2] = 'index';
        }
        elseif (in_array($target[2],['destroy','destroyAll','restore','restoreAll']))
        {
            $target[2] = 'delete';
        }
        elseif (in_array($target[2],['create']))
        {
            $target[2] = 'store';
        }
        elseif (in_array($target[2],['edit']))
        {
            $target[2] = 'update';
        }

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

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