<?php

namespace App\Http\Middleware;

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

class EnsureAdminAreaAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! Auth::check()) {
            return redirect()->route('admin.logindata');
        }

        $userType = (int) (Auth::user()->usertype ?? 0);
        if ($userType === 4) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('admin.studentslogin')
                ->with('message', 'You are not allowed to access the admin panel.');
        }

        if ($userType === 5) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('admin.caminslogin')
                ->with('message', 'This legacy support account type is disabled for the current project.');
        }

        return $next($request);
    }
}
