<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Spatie\Permission\Exceptions\UnauthorizedException;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle($request, Closure $next, $permission = null, $guard = null)
    {
        $authGuard = app('auth')->guard($guard);

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

        if (!is_null($permission)) {
            $permissions = is_array($permission)
                ? $permission
                : explode('|', $permission);
        }

        if (is_null($permission)) {
            $permission = $request->route()->getName();

            $permissions = array($permission);
        }

        $user_permision_list = $authGuard->user()->getAllPermissions()->pluck('name')->toArray();

        foreach ($permissions as $permission) {

            foreach ($user_permision_list as $user_permision) {
                if ($user_permision == $permission) {
                    return $next($request);
                }
            }
        }

        $exist_route = Permission::where('name', $permission)->first();
        if (!$exist_route) {
            return $next($request);
        }

        throw UnauthorizedException::forPermissions($permissions);
    }
}
