<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckFeatureAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $feature  The feature to check (e.g., 'has_ads_manager', 'has_analytics')
     */
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        $user = $request->user();

        if (!$user) {
            return redirect()->route('login');
        }

        // Super Admin bypass
        if ($user->hasRole('super_admin')) {
            return $next($request);
        }

        // Check if user has an active subscription
        if (!$user->hasActiveSubscription()) {
            return redirect()->route('subscription.plans')
                ->with('error', 'You need an active subscription to access this feature.');
        }

        $subscription = $user->subscription;
        $plan = $subscription->planModel;

        // Check if the plan has access to this feature
        if (!$plan || !$plan->getAttribute($feature)) {
            return redirect()->back()
                ->with('error', 'This feature is not available in your current plan. Please upgrade to access it.');
        }

        return $next($request);
    }
}