<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckSubscription
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if (!$user) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        if ($user->role === 'admin') {
            return $next($request);
        }

        $activeSubscription = $user->subscriptions()->latest()->first();

        if (!$activeSubscription || !$activeSubscription->canAccess()) {
            return response()->json([
                'message' => 'Akun tidak aktif. Masa trial Anda telah habis. Silakan bayar untuk melanjutkan.',
                'subscription_expired' => true,
            ], 403);
        }

        $request->merge(['active_subscription' => $activeSubscription]);

        return $next($request);
    }
}
