<?php

namespace App\Http\Controllers;

use App\Models\Plan;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Customer;
use Stripe\Subscription;
use Stripe\Exception\ApiErrorException;
use App\Models\User;
use App\Models\Order;
use App\Models\Subscription as AppSubscription;
use GrahamCampbell\ResultType\Success;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Stripe\PaymentMethod;
use Stripe\Invoice;
use App\Models\EmpCompanyDetails;
use Carbon\Carbon;
class SubscriptionController extends Controller
{
    public function __construct()
    {
        Stripe::setApiKey(config('stripe.secret'));
    }

    public function subscribe(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'stripe_token'  => 'required|string',
            'plan_id'       => 'required|integer|exists:plans,id',
            'customer_id'   => 'required|integer|exists:users,id',
            'interval'       => 'required|in:monthly,yearly',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors'  => $validator->errors(),
            ], 422);
        }

        $user = User::find($request->input('customer_id'));
        $plan = Plan::find($request->input('plan_id'));
        $planType = $request->input('interval');

        $priceId = null;

        if ($planType == 'monthly') {
            $priceId = $plan->price_key;
        } elseif ($planType == 'yearly') {
            $priceId = $plan->price_key_yearly;
        }

        try {
            if ($user->cus_id) {
                $customer = \Stripe\Customer::retrieve($user->cus_id);
            } else {
                $paymentMethod = \Stripe\PaymentMethod::create([
                    'type' => 'card',
                    'card' => [
                        'token' => $request->input('stripe_token'),
                    ],
                ]);

                $customer = $this->findOrCreateCustomer(
                    $user->email,
                    $user->name,
                    $paymentMethod->id
                );

                $paymentMethod->attach(['customer' => $customer->id]);
                \Stripe\Customer::update($customer->id, [
                    'invoice_settings' => [
                        'default_payment_method' => $paymentMethod->id,
                    ],
                ]);

                $user->update(['cus_id' => $customer->id]);
            }

            $subscription = \Stripe\Subscription::create([
                'customer'         => $customer->id,
                'items'            => [['price' => $priceId]],  
                'payment_behavior' => 'default_incomplete',
                'payment_settings' => [
                    'save_default_payment_method' => 'on_subscription',
                ],
            ]);

            $invoiceId = $subscription->latest_invoice;
            $invoice   = \Stripe\Invoice::retrieve(
                $invoiceId,
                ['expand' => ['payment_intent']] 
            );

            $clientSecret = $invoice->payment_intent->client_secret ?? null;

            return $this->success([
                'subscription_id'   => $subscription->id,
                'client_secret'     => $clientSecret,
                'status'            => $subscription->status,
                'latest_invoice_id' => $invoiceId,
            ], 'Subscription Subscribed Successfully');
        } catch (ApiErrorException $e) {
            Log::error('Stripe Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'error'   => $e->getMessage(),
            ], 400);
        } catch (\Exception $e) {
            Log::error('Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'error'   => 'Subscription processing failed',
            ], 500);
        }
    }


    private function findOrCreateCustomer($email, $name, $paymentMethodId)
    {
        $customers = Customer::all([
            'email' => $email,
            'limit' => 1
        ]);

        if (!empty($customers->data)) {
            $customer = $customers->data[0];

            $this->attachPaymentMethod($customer->id, $paymentMethodId);

            return $customer;
        }

        return Customer::create([
            'email' => $email,
            'name' => $name,
            'payment_method' => $paymentMethodId,
        ]);
    }

    private function attachPaymentMethod($customerId, $paymentMethodId)
    {
        try {
            $paymentMethod = \Stripe\PaymentMethod::retrieve($paymentMethodId);
            $paymentMethod->attach(['customer' => $customerId]);

            Customer::update($customerId, [
                'invoice_settings' => [
                    'default_payment_method' => $paymentMethodId
                ]
            ]);
        } catch (ApiErrorException $e) {
            Log::warning('Error attaching payment method: ' . $e->getMessage());
        }
    }



    public function getSubscription(Request $request)
    {
        $validated = $request->validate([
            'subscription_id' => 'required|string'
        ]);

        try {
            $subscription = Subscription::retrieve([
                'id' => $validated['subscription_id'],
                'expand' => ['customer', 'items.data.price.product']
            ]);

            return response()->json($subscription);
        } catch (ApiErrorException $e) {
            return response()->json([
                'error' => $e->getMessage()
            ], 400);
        }
    }

    public function checkUserExpiry()
    {
        $now = Carbon::now();
    
        // 1. Get expired admins
        $expiredAdmins = User::whereNotNull('plan_expire_date')
            ->where('plan_expire_date', '<', $now)
            ->get();
    
        $expiredAdminEmails = [];
        $expiredAdminIds = [];
    
        foreach ($expiredAdmins as $admin) {
            $admin->tokens()->delete(); 
            $admin->active_plan_id = null;
            $admin->plan_expire_date = null;
            $admin->save();
    
            $expiredAdminEmails[] = $admin->email;
            $expiredAdminIds[] = $admin->id;
        }
    
        $expiredEmployees = EmpCompanyDetails::whereIn('customer_id', $expiredAdminIds)->get();
        $expiredEmployeeEmails = [];
    
        foreach ($expiredEmployees as $employee) {
            $employee->tokens()->delete();
            $expiredEmployeeEmails[] = $employee->employee_email;
        }
    
        return response()->json([
            'message' => 'Expired users logged out successfully.',
            'expired_admins_count' => count($expiredAdminEmails),
            'expired_admins_emails' => $expiredAdminEmails,
            'expired_employees_count' => $expiredEmployees->count(),
            'expired_employees_emails' => $expiredEmployeeEmails,
        ]);
    }


    public function getPaymentHistory(Request $request)
    {
        try {
            $user = Auth::guard('admin')->user() ?? Auth::guard('api')->user();
            
            if (!$user) {
                return $this->error('User not authenticated', 401);
            }

            $currentSubscription = $this->getCurrentSubscription($user);
            $page = max(1, (int) $request->input('page', 1));
            $perPage = max(1, min(100, (int) $request->input('per_page', 10)));

            $ordersPaginator = Order::where('user_id', $user->id)
                ->with(['plan', 'subscription'])
                ->orderBy('created_at', 'desc')
                ->paginate($perPage, ['*'], 'page', $page);

            $currentSubscriptionData = $currentSubscription 
                ? $this->formatCurrentSubscription($currentSubscription, $user) 
                : null;

            $currentOrderId = $this->getCurrentOrderId($currentSubscription);
            $paymentHistory = collect($ordersPaginator->items())->map(function ($order) use ($user, $currentSubscription, $currentOrderId) {
                return $this->formatPaymentHistoryItem($order, $user, $currentSubscription, $currentOrderId);
            });

            $pagination = $this->buildPaginationMetadata($ordersPaginator, $page, $perPage, $request);
            
            return response()->json([
                'current_subscription' => $currentSubscriptionData,
                'payment_history' => $paymentHistory,
                'pagination' => $pagination
            ], 200);

        } catch (\Exception $e) {
            Log::error('Error fetching payment history: ' . $e->getMessage());
            return $this->error('Failed to retrieve payment history: ' . $e->getMessage(), 500);
        }
    }

    private function formatCurrentSubscription($subscription, $user)
    {
        $order = is_object($subscription) && isset($subscription->order) ? $subscription->order : ($subscription->order ?? null);
        $plan = is_object($subscription) && isset($subscription->plan) ? $subscription->plan : ($subscription->plan ?? null);
        
        if (!$plan && $user->active_plan_id) {
            $plan = \App\Models\Plan::find($user->active_plan_id);
        }
        
        $paymentMethod = $this->getPaymentMethodFromStripe($user);
        $invoiceNumber = $order ? ($order->order_id ?? null) : null;
        $transactionId = $order ? ($order->txn_id ?? null) : null;

        $interval = $subscription->interval ?? $order->interval ?? 'month';
        $billingCycle = $this->formatBillingCycle($interval);

        $dateFormat = $this->getSystemDateFormat();
        
        $nextBillingDate = null;
        if ($user->plan_expire_date) {
            $parsedDate = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date');
            $nextBillingDate = $parsedDate && $parsedDate instanceof Carbon ? $parsedDate->format($dateFormat) : null;
        }
        
        if (!$nextBillingDate && isset($subscription->current_period_end) && $subscription->current_period_end) {
            $parsedDate = \App\Models\BaseModel::safeCarbonParse($subscription->current_period_end, 'current_period_end');
            $nextBillingDate = $parsedDate && $parsedDate instanceof Carbon ? $parsedDate->format($dateFormat) : null;
        }

        $subscriptionDate = null;
        if ($order && $order->created_at) {
            $parsedDate = \App\Models\BaseModel::safeCarbonParse($order->created_at, 'created_at');
            $subscriptionDate = $parsedDate && $parsedDate instanceof Carbon ? $parsedDate->format($dateFormat) : null;
        } elseif (isset($subscription->created_at) && $subscription->created_at) {
            $parsedDate = \App\Models\BaseModel::safeCarbonParse($subscription->created_at, 'created_at');
            $subscriptionDate = $parsedDate && $parsedDate instanceof Carbon ? $parsedDate->format($dateFormat) : null;
        }

        $subtotal = $order ? ($order->original_price ?? $order->price ?? 0) : ($subscription->amount ?? 0);
        $total = $subtotal;

        $invoiceItems = [
            [
                'description' => ($plan ? $plan->name : $subscription->name) . ' Subscription',
                'price' => number_format($subtotal, 2, '.', '')
            ]
        ];

        $subscriptionStatus = 'Active';
        if ($user->plan_expire_date) {
            $expireDate = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date');
            if ($expireDate && $expireDate instanceof Carbon && $expireDate->isPast()) {
                $subscriptionStatus = 'Expired';
            } else {
                $subscriptionStatus = ucfirst($subscription->stripe_status ?? 'active');
            }
        } else {
            $subscriptionStatus = ucfirst($subscription->stripe_status ?? 'active');
        }
        
        $isActive = method_exists($subscription, 'isActive') 
            ? $subscription->isActive() 
            : ($subscriptionStatus === 'Active' && $this->isPlanNotExpired($user));

        return [
            'invoice_number' => $invoiceNumber,
            'transaction_id' => $transactionId,
            'date' => $subscriptionDate,
            'subscription_status' => $subscriptionStatus,
            'plan_name' => $plan ? $plan->name : ($subscription->name ?? 'N/A'),
            'plan_id' => $user->active_plan_id ?? ($plan ? $plan->id : null),
            'billing_cycle' => $billingCycle,
            'payment_method' => $paymentMethod ?? ($order ? $this->getPaymentTypeText($order->payment_type) : 'N/A'),
            'next_billing_date' => $nextBillingDate,
            'plan_expire_date' => $user->plan_expire_date 
                ? (($parsed = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date')) && $parsed instanceof Carbon 
                    ? $parsed->format($dateFormat) 
                    : null)
                : null,
            'invoice_items' => $invoiceItems,
            'subtotal' => number_format($subtotal, 2, '.', ''),
            'tax' => number_format(0, 2, '.', ''),
            'total' => number_format($total, 2, '.', ''),
            'is_active' => $isActive,
        ];
    }
    private function formatPaymentHistoryItem($order, $user, $currentSubscription = null, $currentOrderId = null)
    {
        $subscription = $order->subscription;
        $plan = $order->plan;
        $orderUser = $order->user ?? $user;

        $paymentMethod = null;
        
        try {
            if ($orderUser && $orderUser->cus_id) {
                $stripeCustomer = \Stripe\Customer::retrieve($orderUser->cus_id);
                if ($stripeCustomer->invoice_settings->default_payment_method) {
                    $pm = \Stripe\PaymentMethod::retrieve($stripeCustomer->invoice_settings->default_payment_method);
                    if ($pm->card) {
                        $paymentMethod = 'Credit Card ending in ' . $pm->card->last4;
                    }
                }
            }
        } catch (\Exception $e) {
            Log::warning('Could not retrieve payment method for order: ' . $e->getMessage());
        }

        $invoiceNumber = $order->order_id ?? null;
        $paymentStatus = $this->getPaymentStatusText($order->payment_status);
        $subscriptionStatus = 'Expired';
        $isCurrentOrder = ($currentOrderId && $order->id == $currentOrderId);
        if ($user->active_plan_id && $order->plan_id == $user->active_plan_id && $user->plan_expire_date) {
            $expireDate = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date');
            if ($expireDate && $expireDate instanceof Carbon && $expireDate->isFuture()) {
                $subscriptionStatus = $isCurrentOrder ? 'Active' : 'Upgraded';
            } else {
                $subscriptionStatus = 'Expired';
            }
        } elseif ($subscription) {
            $subscriptionEndDate = $subscription->current_period_end 
                ? \App\Models\BaseModel::safeCarbonParse($subscription->current_period_end, 'current_period_end')
                : null;
            
            $isSubscriptionPeriodValid = $subscriptionEndDate && $subscriptionEndDate instanceof Carbon && $subscriptionEndDate->isFuture();
            
            if ($isSubscriptionPeriodValid) {
                $subscriptionStatus = $isCurrentOrder ? 'Active' : 'Upgraded';
            } elseif ($subscription->ended()) {
                $subscriptionStatus = 'Expired';
            } elseif ($subscription->canceled()) {
                $subscriptionStatus = 'Canceled';
            } else {
                $subscriptionStatus = 'Expired';
            }
        } else {
            if ($order->payment_status == config('constants.payment_statuses.completed')) {
                if ($isCurrentOrder && $user->active_plan_id && $order->plan_id == $user->active_plan_id) {
                    $subscriptionStatus = 'Active';
                } elseif ($user->active_plan_id && $order->plan_id == $user->active_plan_id && !$isCurrentOrder) {
                    $subscriptionStatus = 'Upgraded';
                } elseif ($user->active_plan_id && $user->active_plan_id != $order->plan_id && $currentSubscription) {
                    $orderDate = \App\Models\BaseModel::safeCarbonParse($order->created_at, 'created_at');
                    if ($orderDate && $orderDate instanceof Carbon) {
                        $interval = $order->interval ?? 'month';
                        $estimatedEndDate = $orderDate->copy();
                        if (in_array(strtolower($interval), ['year', 'yearly', '12'])) {
                            $estimatedEndDate->addYear();
                        } else {
                            $estimatedEndDate->addMonth();
                        }
                        $subscriptionStatus = $estimatedEndDate->isFuture() ? 'Upgraded' : 'Expired';
                    } else {
                        $subscriptionStatus = 'Expired';
                    }
                } else {
                    $subscriptionStatus = 'Expired';
                }
            }
        }

        $dateFormat = $this->getSystemDateFormat();
        
        return [
            'invoice_number' => $invoiceNumber,
            'date' => $order->created_at 
                ? (($parsed = \App\Models\BaseModel::safeCarbonParse($order->created_at, 'created_at')) && $parsed instanceof Carbon 
                    ? $parsed->format($dateFormat) 
                    : null)
                : null,
            'expiry_date' => $this->getOrderExpireDate($order, $user, $subscription, $isCurrentOrder),
            'plan_name' => $order->plan_name ?? ($plan ? $plan->name : 'N/A'),
            'amount' => number_format($order->original_price ?? $order->price ?? 0, 2, '.', ''),
            'payment_method' => $paymentMethod ?? $this->getPaymentTypeText($order->payment_type),
            'payment_status' => $paymentStatus,
            'subscription_status' => $subscriptionStatus,
            'order_id' => $order->id,
            'receipt_url' => $order->receipt ? asset($order->receipt) : null,
        ];
    }
    private function getPaymentStatusText($status)
    {
        $statuses = config('constants.payment_statuses');
        $statusMap = array_flip($statuses);
        
        if (isset($statusMap[$status])) {
            return ucfirst($statusMap[$status]);
        }
        
        return match ($status) {
            0 => 'Pending',
            1 => 'Paid',
            2 => 'Failed',
            3 => 'Refunded',
            4 => 'Rejected',
            default => 'Unknown',
        };
    }
    private function getPaymentTypeText($paymentType)
    {
        if (!$paymentType) {
            return 'N/A';
        }
        
        return match (strtolower($paymentType)) {
            'stripe', '3' => 'Credit Card',
            'bank', '1' => 'Bank Transfer',
            'paypal', 'pay_pal', '2' => 'PayPal',
            default => ucfirst($paymentType),
        };
    }
    private function getCurrentSubscription($user)
    {
        $currentSubscription = null;

        // First priority: Check user's active_plan_id and plan_expire_date
        if ($user->active_plan_id && $user->plan_expire_date) {
            $planExpireDate = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date');
            
            if ($planExpireDate && $planExpireDate instanceof Carbon && $planExpireDate->isFuture()) {
                $currentSubscription = AppSubscription::where('user_id', $user->id)
                    ->where('plan_id', $user->active_plan_id)
                    ->with(['plan', 'order'])
                    ->orderBy('created_at', 'desc')
                    ->first();
                
                if (!$currentSubscription) {
                    $orderWithPlan = Order::where('user_id', $user->id)
                        ->where('plan_id', $user->active_plan_id)
                        ->where('payment_status', config('constants.payment_statuses.completed'))
                        ->with(['subscription.plan', 'subscription.order', 'plan'])
                        ->orderBy('created_at', 'desc')
                        ->first();
                    
                    if ($orderWithPlan && $orderWithPlan->subscription) {
                        $currentSubscription = $orderWithPlan->subscription;
                    } elseif ($orderWithPlan) {
                        $currentSubscription = (object)[
                            'id' => null,
                            'user_id' => $user->id,
                            'order_id' => $orderWithPlan->id,
                            'plan_id' => $user->active_plan_id,
                            'name' => $orderWithPlan->plan_name,
                            'stripe_status' => 'active',
                            'current_period_start' => $orderWithPlan->created_at,
                            'current_period_end' => $user->plan_expire_date,
                            'interval' => $orderWithPlan->interval ?? 'month',
                            'amount' => $orderWithPlan->price ?? 0,
                            'currency' => $orderWithPlan->price_curency ?? 'AUD',
                            'order' => $orderWithPlan,
                            'plan' => $orderWithPlan->plan,
                        ];
                    }
                }
            }
        }
        
        // Fallback: Find subscription with active/trialing status
        if (!$currentSubscription) {
            $currentSubscription = AppSubscription::where('user_id', $user->id)
                ->whereIn('stripe_status', ['active', 'trialing'])
                ->where(function ($query) {
                    $query->where('cancel_at_period_end', false)->orWhereNull('cancel_at_period_end');
                })
                ->where(function ($query) {
                    $query->where('current_period_end', '>', Carbon::now())->orWhereNull('current_period_end');
                })
                ->with(['plan', 'order'])
                ->orderBy('created_at', 'desc')
                ->first();
        }

        // Fallback: Find from orders with stripe_subscription_id
        if (!$currentSubscription) {
            $orderWithSubscription = Order::where('user_id', $user->id)
                ->whereNotNull('stripe_subscription_id')
                ->where('payment_status', config('constants.payment_statuses.completed'))
                ->with(['subscription.plan', 'subscription.order', 'plan'])
                ->orderBy('created_at', 'desc')
                ->first();

            if ($orderWithSubscription && $orderWithSubscription->subscription) {
                $subscription = $orderWithSubscription->subscription;
                $parsedEnd = $subscription->current_period_end 
                    ? \App\Models\BaseModel::safeCarbonParse($subscription->current_period_end, 'current_period_end')
                    : null;
                if ($subscription->isActive() || ($parsedEnd && $parsedEnd instanceof Carbon && $parsedEnd->isFuture())) {
                    $currentSubscription = $subscription;
                }
            }
        }

        // Last fallback: Find any non-expired subscription
        if (!$currentSubscription) {
            $currentSubscription = AppSubscription::where('user_id', $user->id)
                ->whereNotNull('current_period_end')
                ->where('current_period_end', '>', Carbon::now())
                ->where(function ($query) {
                    $query->whereNull('ends_at')->orWhere('ends_at', '>', Carbon::now());
                })
                ->with(['plan', 'order'])
                ->orderBy('current_period_end', 'desc')
                ->first();
        }

        if (!$currentSubscription) {
            Log::info('No active subscription found for user', ['user_id' => $user->id]);
        }

        return $currentSubscription;
    }

    private function getCurrentOrderId($currentSubscription)
    {
        if (!$currentSubscription) {
            return null;
        }

        if (isset($currentSubscription->order_id)) {
            return $currentSubscription->order_id;
        }

        if (isset($currentSubscription->order)) {
            return is_object($currentSubscription->order) ? $currentSubscription->order->id : null;
        }

        return null;
    }

    private function buildPaginationMetadata($paginator, $page, $perPage, $request)
    {
        $total = $paginator->total();
        $lastPage = $paginator->lastPage();
        $from = ($page - 1) * $perPage + 1;
        $to = min($page * $perPage, $total);

        $baseUrl = $request->url();
        $queryParams = $request->query();
        
        $nextPageUrl = null;
        if ($page < $lastPage) {
            $queryParams['page'] = $page + 1;
            $nextPageUrl = $baseUrl . '?' . http_build_query($queryParams);
        }

        $prevPageUrl = null;
        if ($page > 1) {
            $queryParams['page'] = $page - 1;
            $prevPageUrl = $baseUrl . '?' . http_build_query($queryParams);
        }

        return [
            'total' => $total,
            'per_page' => $perPage,
            'current_page' => $page,
            'last_page' => $lastPage,
            'from' => $total > 0 ? $from : null,
            'to' => $total > 0 ? $to : null,
            'next_page_url' => $nextPageUrl,
            'prev_page_url' => $prevPageUrl
        ];
    }

    private function getPaymentMethodFromStripe($user)
    {
        try {
            if ($user->cus_id) {
                $stripeCustomer = \Stripe\Customer::retrieve($user->cus_id);
                if ($stripeCustomer->invoice_settings->default_payment_method) {
                    $pm = \Stripe\PaymentMethod::retrieve($stripeCustomer->invoice_settings->default_payment_method);
                    if ($pm->card) {
                        return 'Credit Card ending in ' . $pm->card->last4;
                    }
                }
            }
        } catch (\Exception $e) {
            Log::warning('Could not retrieve payment method: ' . $e->getMessage());
        }
        return null;
    }

    private function formatBillingCycle($interval)
    {
        $billingCycle = ucfirst($interval);
        if ($billingCycle == '1' || strtolower($billingCycle) == '1') {
            return 'Monthly';
        } elseif ($billingCycle == '12' || strtolower($billingCycle) == '12') {
            return 'Yearly';
        }
        return $billingCycle;
    }

    private function isPlanNotExpired($user)
    {
        if (!$user->plan_expire_date) {
            return false;
        }
        $expireDate = \App\Models\BaseModel::safeCarbonParse($user->plan_expire_date, 'plan_expire_date');
        return $expireDate && $expireDate instanceof Carbon && $expireDate->isFuture();
    }

    private function getOrderExpireDate($order, $user, $subscription = null, $isCurrentOrder = false)
    {
        $dateFormat = $this->getSystemDateFormat();

        
        // Step 2: If no literal expiry date found, calculate from order date + interval
        $orderDate = \App\Models\BaseModel::safeCarbonParse($order->created_at, 'created_at');
        if (!$orderDate || !($orderDate instanceof Carbon)) {
            return null;
        }
        
        $interval = $order->interval ?? 1;
        $calculatedExpiryDate = $orderDate->copy();
        
        // Handle interval - can be numeric (months) or string (month/year/yearly)
        if (is_numeric($interval)) {
            // Numeric interval represents months
            $intervalMonths = (int)$interval;
            if ($intervalMonths <= 0) {
                $intervalMonths = 1; // Default to 1 month
            }
            $calculatedExpiryDate->addMonths($intervalMonths);
        } else {
            // String interval: check for year/yearly/12
            $intervalLower = strtolower((string)$interval);
            if (in_array($intervalLower, ['year', 'yearly', '12'])) {
                $calculatedExpiryDate->addYear();
            } else {
                // Default to 1 month for month/monthly or unknown strings
                $calculatedExpiryDate->addMonth();
            }
        }
        
        return $calculatedExpiryDate->format($dateFormat);
    }

    private function getSystemDateFormat()
    {
        $baseModel = new \App\Models\BaseModel();
        return $baseModel->getUserDateFormat();
    }
}
