<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\DB;

use App\Models\Auth\User;
use App\Models\Auth\UserPermission;
use App\Models\Auth\UserRole;
use App\Models\Auth\AvailableUserPermission;

class RequirePermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, $permission = 'None'): Response
    {
        $role = UserRole::where([
            'character_id' => auth()->user()->character_id,
        ])->get(['role']);

        if($role[0]-> != "Admin") {
            $perms = UserPermission::where(['character_id' => auth()->user()->character_id, 'permission' => $permission])->get(['permission']);

            abort_unless(auth()->check() && isset($perms[0]->permission), 403, "You don't have the correct permission to be in this area.");
        }

        return $next($request);
    }
}
