<?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\UserRole;
use App\Models\Auth\AvailableUserRole;

class RequireRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, $role = 'None'): Response
    {
        $ranking = array();
        $roles = AvailableUserRole::all();

        foreach($roles as $r) {
            $ranking[$r->role] = $r->rank;
        }
        
        $check = UserRole::where('character_id', auth()->user()->character_id)->get(['role']);

        if(!isset($check[0]->role)) {
            abort(403, "You don't have any roles.");
        }

        if($ranking[$check[0]->role] < $ranking[$role]) {
            abort(403, "You don't have the correct role to be in the area.");
        }

        return $next($request);
    }
}
