<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckXenForoPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$permissions ): Response
    {
        if( !\Auth::check() )
            return redirect()->to(config('app.forum_url') . '/login' );

        if( empty($permissions) ) // No permissions needed.
            return $next($request);

        foreach ($permissions as $permissionStr) {
            [$group, $permission] = explode('.', $permissionStr);

            if( !\Auth::user()->_can($group, $permission) )
                return $this->deny($request, $permission);
        }

        return $next($request);
    }

    private function deny(Request $request, string $permission): Response
    {
        if($request->expectsJson())
            return \response()->json(['error' => 'forbidden'], 403);

        return response()->view('pages.forbidden', [
            'permission' => $permission,
        ], 403 );
    }
}
