<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckSubscription
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();

        if ($user && $user->role === 'seller') {
            $seller = $user->seller;
            
            // Check if seller has an active subscription
            $activeSubscription = $seller->subscription()->active()->first();

            if (!$activeSubscription) {
                // Allow access to subscription pages
                if ($request->routeIs('seller.subscription.*')) {
                    return $next($request);
                }

                // Redirect to subscription page with message
                return redirect()->route('seller.subscription.index')
                    ->with('error', 'Please subscribe to a plan to access this feature.');
            }
        }

        return $next($request);
    }
}
