From 464ed71360a87557a958b8148fadcc201a2dd677 Mon Sep 17 00:00:00 2001 From: "m.razaghi" Date: Sun, 16 Aug 2026 17:33:19 +0330 Subject: [PATCH] Fixed SubscribePlanController.php --- .../api/SubscribePlanController.php | 44 ++++++++++++++----- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/app/Http/Controllers/api/SubscribePlanController.php b/app/Http/Controllers/api/SubscribePlanController.php index 15158ad..f5e1bce 100644 --- a/app/Http/Controllers/api/SubscribePlanController.php +++ b/app/Http/Controllers/api/SubscribePlanController.php @@ -285,22 +285,42 @@ class SubscribePlanController extends Controller { $user = auth()->user(); - $subscribePlans = UserSubscriber::where('user_id', $user->id) - ->where('expired_at', '>', now()) - ->orderBy('expired_at', 'desc') + // 1. Fetch all active subscriptions + $activeSubscribers = $user->userSubscribers() + ->with('subscribe') + ->where('expired_at', '>=', now()) ->get(); - if ($subscribePlans->isNotEmpty()) { - $totalExpiredDays = $subscribePlans->sum('expired_day'); - $latestPlan = $subscribePlans->first(); + if ($activeSubscribers->isNotEmpty()) { + // 2. Separate Paid plans from Free plans + $paidSubscriptions = $activeSubscribers->reject(function ($subscriber) { + return $subscriber->is_free || ($subscriber->subscribe && $subscriber->subscribe->is_free); + }); + + // 3. AUTHORITY RULE: Paid plans absolutely override Free plans! + if ($paidSubscriptions->isNotEmpty()) { + $latestSubscription = $paidSubscriptions->sortByDesc('expired_at')->first(); + } else { + $latestSubscription = $activeSubscribers->sortByDesc('expired_at')->first(); + } + + // 4. Calculate accurate remaining days + $expiredDays = $latestSubscription->expired_at->diffInDays(now()); + + $isFree = (bool) ( + $latestSubscription->is_free || + ($latestSubscription->subscribe && $latestSubscription->subscribe->is_free) + ); + + // 5. Format the exact same object expected by the frontend $subscribePlanData = [ - 'id' => $latestPlan->id, - 'name' => $latestPlan->subscribe->name, - 'price' => $latestPlan->subscribe->price, - 'expired_day' => $totalExpiredDays, - 'is_free' => $latestPlan->subscribe->is_free == 1, - 'expired_at' => Carbon::now()->addDays($totalExpiredDays)->format('Y-m-d'), + 'id' => $latestSubscription->id, + 'name' => $latestSubscription->subscribe->name ?? 'Subscription', + 'price' => $latestSubscription->subscribe->price ?? 0, + 'expired_day' => $expiredDays, + 'is_free' => $isFree, + 'expired_at' => $latestSubscription->expired_at->format('Y-m-d'), ]; return $this->success($subscribePlanData, 'Subscribe Plan', 'Current Subscribe Plan');