<?php

namespace App\Http\Middleware;

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

class EnsureUserHasAssociation
{
    /**
     * Handle an incoming request.
     *
     * Ensures that the authenticated user has an association_id.
     * If not, redirects to the admin panel.
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is authenticated
        if (! Auth::check()) {
            // Let the Authenticate middleware handle this
            return $next($request);
        }

        $user = Auth::user();

        // Check if user has an association_id
        if (is_null($user->association_id)) {
            // Redirect to admin panel for users without association
            return redirect('/admin');
        }

        return $next($request);
    }
}
