<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\PurchaseOrder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;


class PlanExpire
{
    /**
     * 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)
    {
        // List of routes that can be accessed without an active plan
        $allowedRoutes = [
            '/upgrade-plan'
        ];

        // Check if the current route name is in the allowed routes
        if (in_array(Route::currentRouteName(), $allowedRoutes)) {
            return $next($request);
        }

        // Otherwise, check if the user’s plan has expired
        $userId = Auth::id();
        $purchaseOrder = new \App\Models\PurchaseOrder();

        if ($purchaseOrder->isPlanExpired($userId)) {
            return redirect()->route('plan.expired');
        }

        return $next($request);
    }
}
