<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckNgbvdPermission
{
    public function handle($request, Closure $next, string $permissions)
    {
        $user = Auth::user();

        if (!$user) {
            return redirect()->guest(route('login'));
        }

        if (method_exists($user, 'canBypassNgbvdPermissions') && $user->canBypassNgbvdPermissions()) {
            return $next($request);
        }

        $permissionList = array_filter(array_map('trim', explode('|', $permissions)));
        foreach ($permissionList as $permission) {
            if (method_exists($user, 'hasNgbvdPermission') && $user->hasNgbvdPermission($permission)) {
                return $next($request);
            }
        }

        return $this->deny($request);
    }

    private function deny($request)
    {
        if ($request->expectsJson() || $request->ajax()) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to access this module.',
            ], 403);
        }

        return redirect('/error/access')->with('error', 'You do not have permission to access this module.');
    }
}
