Fixed SubscribePlanController.php
This commit is contained in:
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user