<?php

namespace App\Http\Middleware;

use Closure;
use Spatie\Permission\Exceptions\UnauthorizedException;

class PermissionMiddleware {



    public function handle($request, Closure $next, $permission, $guard = null) {

        $guard = (is_null($guard)) ? activeGuard() : $guard;
//        dd(auth($guard)->user());

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

        if ($authGuard->guest()) {
            throw UnauthorizedException::notLoggedIn();
        }

        $permissions = is_array($permission)
            ? $permission
            : explode('|', $permission);

//        dd(auth($guard)->user()->privileges);
        foreach ($permissions as $permission) {
//            if ($authGuard->user()->can($permission)) {
            if (in_array($permission,$authGuard->user()->privileges)) {
                return $next($request);
            }
        }

        throw UnauthorizedException::forPermissions($permissions);
    }

}
