<?php

namespace App\Http\Middleware;

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

class CheckAdminRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is logged in AND has role_id == 1 or 2
        if (Auth::check() && in_array(Auth::user()->role_id, [1, 2])) {
            return $next($request);
        }

        // If not admin, redirect or throw error
        return redirect('/login')->withErrors(['username' => 'You do not have admin access.']);
    }
}
