<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ModuleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle($request, Closure $next, $module, $guard = null)
    {

        $authGuard = app('auth')->guard($guard);

        if ($authGuard->guest()) {
            throw abort(401, 'User is not logged in');
        }

        $systemModules = $request->user()->currentRole->roleHasSystemModule()->with(['systemModule'])->get();

        $moduleGuards = $systemModules->map(function ($systemModule) {
            return $systemModule->systemModule->name;
        })->toArray();

        $modules = is_array($module)
            ? $module
            : explode('|', $module);

        foreach ($modules as $module) {
            if (in_array($module, $moduleGuards)) {
                return $next($request);
            }
        }

        throw abort(403, 'Forbidden');
    }
}
