Fixed SubscribePlanController.php
This commit is contained in:
@@ -285,22 +285,42 @@ class SubscribePlanController extends Controller
|
|||||||
{
|
{
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
|
|
||||||
$subscribePlans = UserSubscriber::where('user_id', $user->id)
|
// 1. Fetch all active subscriptions
|
||||||
->where('expired_at', '>', now())
|
$activeSubscribers = $user->userSubscribers()
|
||||||
->orderBy('expired_at', 'desc')
|
->with('subscribe')
|
||||||
|
->where('expired_at', '>=', now())
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
if ($subscribePlans->isNotEmpty()) {
|
if ($activeSubscribers->isNotEmpty()) {
|
||||||
$totalExpiredDays = $subscribePlans->sum('expired_day');
|
|
||||||
$latestPlan = $subscribePlans->first();
|
|
||||||
|
|
||||||
|
// 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 = [
|
$subscribePlanData = [
|
||||||
'id' => $latestPlan->id,
|
'id' => $latestSubscription->id,
|
||||||
'name' => $latestPlan->subscribe->name,
|
'name' => $latestSubscription->subscribe->name ?? 'Subscription',
|
||||||
'price' => $latestPlan->subscribe->price,
|
'price' => $latestSubscription->subscribe->price ?? 0,
|
||||||
'expired_day' => $totalExpiredDays,
|
'expired_day' => $expiredDays,
|
||||||
'is_free' => $latestPlan->subscribe->is_free == 1,
|
'is_free' => $isFree,
|
||||||
'expired_at' => Carbon::now()->addDays($totalExpiredDays)->format('Y-m-d'),
|
'expired_at' => $latestSubscription->expired_at->format('Y-m-d'),
|
||||||
];
|
];
|
||||||
|
|
||||||
return $this->success($subscribePlanData, 'Subscribe Plan', 'Current Subscribe Plan');
|
return $this->success($subscribePlanData, 'Subscribe Plan', 'Current Subscribe Plan');
|
||||||
|
|||||||
Reference in New Issue
Block a user