<?php

namespace App\Http\Middleware;

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

class ClientAdminAuth
{
    /**
     * Handle an incoming request.
     *
     * Checks if client admin is authenticated and has an active subscription.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if authenticated as client admin
        if (!Auth::guard('client_admin')->check()) {
            return redirect()->route('client.login');
        }

        $clientAdmin = Auth::guard('client_admin')->user();

        // Check if client admin is active
        if (!$clientAdmin->is_active) {
            Auth::guard('client_admin')->logout();
            return redirect()->route('client.login')->withErrors([
                'email' => 'Your account has been disabled. Please contact your organization administrator.',
            ]);
        }

        // Check if client is active
        if (!$clientAdmin->client || !$clientAdmin->client->is_active) {
            Auth::guard('client_admin')->logout();
            return redirect()->route('client.login')->withErrors([
                'email' => 'Your organization has been disabled. Please contact support.',
            ]);
        }

        // Check if client has active subscription
        if (!$clientAdmin->client->hasActiveSubscription()) {
            Auth::guard('client_admin')->logout();
            return redirect()->route('client.login')->withErrors([
                'email' => 'Your organization\'s subscription has expired. Please contact support for renewal.',
            ]);
        }

        return $next($request);
    }
}
