File size: 26,762 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<?php

namespace App\Http\Controllers\Finance;

use App\Actions\CreateActivity;
use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\CustomBilingPlans;
use App\Models\GatewayProducts;
use App\Models\Gateways;
use App\Models\PaymentPlans;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserOrder;
// use App\Models\Subscriptions;
use App\Services\GatewaySelector;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Cashier\Subscription as Subscriptions;

class PaymentProcessController extends Controller
{
    // payment area
    public function isActiveSubscription($planId) // Checks subscription table if given plan is active on user (already subscribed)
    {
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $activesubid = $activeSub->id;
        } else {
            $activeSub_yokassa = getCurrentActiveSubscriptionYokkasa();
            if ($activeSub_yokassa != null) {
                $activesubid = $activeSub_yokassa->id;
            } else {
                $activesubid = 0; //id can't be zero, so this will be easy to check instead of null
            }
        }

        return $activesubid == $planId;
    }

    public function startSubscriptionProcess($planId, $gatewayCode)
    { // when click on subscribe
        $plan = PaymentPlans::where('id', $planId)->first();
        if ($plan != null) {
            if (self::isActiveSubscription($planId) == true) {
                return back()->with([
                    'message' => __('You already have subscription. Please cancel it before creating a new subscription'),
                    'type'    => 'error',
                ]);
            }
            if ($gatewayCode == 'walletmaxpay') {
                return back()->with([
                    'message' => __('WalletMaxPay available only for Token Packs'), 'type' => 'error',
                ]);
            }

            try {
                return GatewaySelector::selectGateway($gatewayCode)::subscribe($plan);
            } catch (Exception $e) {
                return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
            }
        }
        abort(404);
    }

    public function startPrepaidPaymentProcess($planId, $gatewayCode)
    {
        $plan = PaymentPlans::where('id', $planId)->first();
        if ($plan != null) {
            try {
                return GatewaySelector::selectGateway($gatewayCode)::prepaid($plan);
            } catch (Exception $e) {
                return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
            }
        }
        abort(404);
    }

    public function startSubscriptionCheckoutProcess(Request $request, $gateway = null, $referral = null)
    {
        if ($gateway !== 'freeservice' && $request->isMethod('post')) {

            $gateways = Gateways::where('is_active', 1)->pluck('code')->toArray();
            $request->validate([
                'planID'   => 'required',
                'orderID'  => 'nullable',
                'couponID' => 'nullable',
                'gateway'  => ['required', 'in:' . implode(',', $gateways)],
            ]);
            if ($gateway == null) {
                $gateway = $request->gateway;
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway)::subscribeCheckout($request, $referral);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public function startPrepaidCheckoutProcess(Request $request, $gateway = null, $referral = null)
    {
        if ($gateway !== 'freeservice' && $request->isMethod('post')) {
            $gateways = Gateways::where('is_active', 1)->pluck('code')->toArray();
            $request->validate([
                'planID'   => 'required',
                'orderID'  => 'nullable',
                'couponID' => 'nullable',
                'gateway'  => ['required', 'in:' . implode(',', $gateways)],
            ]);
            if ($gateway == null) {
                $gateway = $request->gateway;
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway)::prepaidCheckout($request, $referral);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    // additional required functions
    public function createPayPalOrder(Request $request)
    {
        try {
            return GatewaySelector::selectGateway('paypal')::createPayPalOrder($request);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public function iyzicoPrepaidCallback(Request $request)
    {
        try {
            return GatewaySelector::selectGateway('iyzico')::iyzicoPrepaidCallback($request);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public function iyzicoSubscribeCallback(Request $request)
    {
        try {
            return GatewaySelector::selectGateway('iyzico')::iyzicoSubscribeCallback($request);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public function iyzicoProductsList(Request $request)
    {
        try {
            return GatewaySelector::selectGateway('iyzico')::iyzicoProductsList($request);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public function succesful()
    {
        return view('panel.user.finance.succesful');
    }

    // webhook control area
    public function handleWebhook(Request $request, $gateway)
    {
        // [stripe,paypal,yokassa,iyzico,paystack,twocheckout]
        try {
            if ($request->isMethod('post')) { // accept the post method for all
                if ($gateway == 'simulate') {
                    return GatewaySelector::selectGateway($gateway)::simulateWebhookEvent($request);
                }

                return GatewaySelector::selectGateway($gateway)::handleWebhook($request);
            } elseif ($request->isMethod('get')) { // accept the get method only for [twocheckout, simulate]
                if ($gateway == 'simulate') {
                    return GatewaySelector::selectGateway('paypal')::simulateWebhookEvent($request);
                } elseif ($gateway == 'twocheckout') {
                    return GatewaySelector::selectGateway($gateway)::handleWebhook($request);
                } elseif ($gateway == 'razorpay') {
                    return GatewaySelector::selectGateway($gateway)::handleWebhook($request);
                } else {
                    abort(404);
                }
            }
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    // admin control area
    public static function banktransactions()
    {
        $bankOrders = UserOrder::where('payment_type', 'banktransfer')->orderByRaw("CASE WHEN status = 'Waiting' THEN 0 ELSE 1 END")->orderBy('created_at', 'desc')->get();

        return view('panel.admin.banktransfer.index', compact('bankOrders'));
    }

    public static function bankDelete($id = null)
    {
        $post = UserOrder::findOrFail($id);
        $post->delete();

        return back()->with(['message' => __('Deleted Successfully'), 'type' => 'success']);
    }

    public static function bankUpdateSave(Request $request)
    {
        if ($request->order_status != 0) {
            $order = UserOrder::findOrFail($request->order_id);
            self::changeOrderStatus($request->order_status, $order);
        }

        return back()->with(['message' => __('Updated Successfully'), 'type' => 'success']);
    }

    private static function changeOrderStatus($status, $order)
    {
        switch ($status) {
            case 'Waiting':
                // sent mail if required here later
                CreateActivity::for($order->user, __('Bank transaction status updated to:') . ' ' . __($status), $order->plan->name . ' ' . __('Plan'));

                break;
            case 'Approved':
                if ($order->type == 'subscription') {
                    $subs = Subscriptions::where('stripe_id', $order->order_id)->first();
                    if ($subs) {
                        $subs->stripe_status = 'bank_approved';

                        switch ($order->plan->frequency) {
                            case 'monthly':
                                $subs->ends_at = \Carbon\Carbon::now()->addMonths(1);

                                break;
                            case 'yearly':
                                $subs->ends_at = \Carbon\Carbon::now()->addYears(1);

                                break;
                            case 'lifetime_monthly':
                                $subs->ends_at = \Carbon\Carbon::now()->addMonths(1); //ends each month but auto renewing without payment reqs
                                $subs->auto_renewal = 1;

                                break;
                            case 'lifetime_yearly':
                                $subs->ends_at = \Carbon\Carbon::now()->addYears(1); //ends each year but auto renewing without payment reqs
                                $subs->auto_renewal = 1;

                                break;
                            default:
                                $subs->ends_at = \Carbon\Carbon::now()->addMonths(1);

                                break;
                        }
                        $subs->save();
                    }
                }
                $order->plan->total_words == -1 ? ($order->user->remaining_words = -1) : ($order->user->remaining_words += $order->plan->total_words);
                $order->plan->total_images == -1 ? ($order->user->remaining_images = -1) : ($order->user->remaining_images += $order->plan->total_images);
                $order->user->save();
                // sent mail if required here later
                CreateActivity::for($order->user, __('Purchased with approved bank transaction'), $order->plan->name . ' ' . __('Plan'));

                break;
            case 'Rejected':
                $subs = Subscriptions::where('stripe_id', $order->order_id)->first();
                if ($subs) {
                    $subs->stripe_status = 'bank_rejected';
                    $subs->save();
                }
                // sent mail if required here later
                CreateActivity::for($order->user, __('Bank transaction status updated to:') . ' ' . __($status), $order->plan->name . ' ' . __('Plan'));

                break;
            default:
                break;
        }

        $order->status = $status;
        $order->save();
    }

    public static function getSubscriptionStatus()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();

        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway)::getSubscriptionStatus();
        } catch (Exception $e) {
            return false;
        }
    }

    public static function getSubscriptionDaysLeft()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway)::getSubscriptionDaysLeft();
        } catch (Exception $e) {
            return null;
        }
    }

    public static function cancelActiveSubscription()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway, 'Could not cancel subscription. Please try again. If this error occures again, please update and migrate.')::subscribeCancel();
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public static function checkIfTrial()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            if ($gateway == null) {
                return false;
            }

            return GatewaySelector::selectGateway($gateway)::checkIfTrial();
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public static function getSubscriptionRenewDate()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            return GatewaySelector::selectGateway($gateway)::getSubscriptionRenewDate();
        } catch (Exception $e) {
            return null;
        }
    }

    public static function deletePaymentPlan($id)
    {
        $plan = PaymentPlans::where('id', $id)->first();
        if ($plan != null) {
            // Get related subscriptions
            $queryAnd = [['stripe_status', '=', 'active'], ['plan_id', '=', $plan->id]];
            $queryOr = [['stripe_status', '=', 'trialing'], ['plan_id', '=', $plan->id]];
            $queryOr2 = [['stripe_status', '=', 'bank_approved'], ['plan_id', '=', $plan->id]];
            $queryOr3 = [['stripe_status', '=', 'bank_renewed'], ['plan_id', '=', $plan->id]];
            $queryOr4 = [['stripe_status', '=', 'free_approved'], ['plan_id', '=', $plan->id]];
            $subscriptions = Subscriptions::where($queryAnd)
                ->orWhere($queryOr)
                ->orWhere($queryOr2)
                ->orWhere($queryOr3)
                ->orWhere($queryOr4)
                ->get();

            // Remove subcriptions one by one
            if ($subscriptions != null) {
                foreach ($subscriptions as $subscription) {
                    try {
                        $tmp = GatewaySelector::selectGateway($subscription->paid_with)::cancelSubscribedPlan($subscription, $plan->id);
                    } catch (Exception $e) {
                        return false;
                    }
                }
            }

            // Delete Plan
            $plan->delete();

            return back()->with([
                'message' => __('All subscriptions related to this plan has been cancelled. Plan is deleted.'),
                'type'    => 'success',
            ]);
        } else {
            return back()->with(['message' => 'Couldn\'t find plan.', 'type' => 'error']);
        }

    }

    public static function saveGatewayProducts($plan)
    {

        // $typ = $type == "prepaid" ? "o" : "s"; # o => one-time | s => subscription
        // switch ($frequency) {
        //     case 'monthly':
        //         $freq = "m";
        //         break;
        //     case 'yearly':
        //         $freq = "y";
        //         break;
        //     case 'lifetime_monthly':
        //         $freq = "lm";
        //         break;
        //     case 'lifetime_yearly':
        //         $freq = "ly";
        //         break;
        //     default:
        //         $freq = "m";
        //         break;
        // }

        $gateways = Gateways::all();
        if ($gateways != null) {
            foreach ($gateways as $gateway) {
                if ((int) $gateway->is_active == 1) {
                    try {
                        $tmp = GatewaySelector::selectGateway($gateway->code)::saveProduct($plan);
                    } catch (Exception $e) {
                    }
                }
            }
        } else {
            Log::error(self::$GATEWAY_CODE . '-> saveGatewayProducts(): Could not find any active gateways!');

            return back()->with(['message' => __('Please enable at least one gateway.'), 'type' => 'error']);
        }
    }

    public static function checkForOngoingPayments()
    {
        return null;
    }

    public static function checkUnmatchingSubscriptions()
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription();
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa();
            if ($activeSubY != null) {
                $gateway = 'yokassa';
                $activeSub = $activeSubY;
                $activeSub->paid_with = 'yokassa';
            }
        }
        if ($activeSub) {
            $priceArray = GatewayProducts::all()->pluck('price_id')->toArray();
            // if some plan cancelation happens when appling coupon then add the custom product price_id to custom bilings table
            $customPriceArray = CustomBilingPlans::all()->pluck('custom_plan_price_id')->toArray();
            if (in_array($activeSub->stripe_price, $priceArray) == true || in_array($activeSub->stripe_price, $customPriceArray) == true) {
                // Do nothing. This is what we want.
            } else {
                // Cancel subscription
                try {
                    if ($activeSub->paid_with != 'yokassa') {
                        $tmp = self::cancelActiveSubscription();
                    }
                } catch (Exception $ex) {
                    Log::error("PaymentProcessController::checkUnmatchingSubscriptions()\n" . $ex->getMessage());
                }
            }
            // Check if active subscription exists on gateway (by stripe_id / subscription id)
            // getSubscriptionStatus function is already called on subscription status file. BUT after functions which gives errors,
            // this needs priority, that's why we add here too. Also this function updates database as cancelled if can't find in gateway
            // there are webhooks for paypal and stripe and paystack
            if ($gateway != 'paypal' && $gateway != 'stripe' && $gateway != 'paystack') {
                $isValid = false;

                try {
                    $isValid = GatewaySelector::selectGateway($gateway)::getSubscriptionStatus();
                } catch (Exception $e) {
                }
            }
            // For some gateways we need to create orders first thats why we have so many Waiting order records. We must clean them.
            $orders = UserOrder::where([
                ['payment_type', '!=', 'banktransfer'], ['status', '=', 'Waiting'], ['user_id', '=', auth()->user()->id],
            ])->get();
            foreach ($orders as $order) {
                $order->delete();
            }
        }

        return null;
    }

    public static function cancelActiveSubscriptionByAdmin($userId)
    {
        $gateway = null;
        $activeSub = getCurrentActiveSubscription($userId);
        if ($activeSub != null) {
            $gateway = $activeSub->paid_with;
        } else {
            $activeSubY = getCurrentActiveSubscriptionYokkasa($userId);
            if ($activeSubY != null) {
                $gateway = 'yokassa';
            }
        }

        try {
            $user = User::find($userId);

            return GatewaySelector::selectGateway($gateway, 'Could not cancel subscription. Please try again. If this error occures again, please update and migrate.')::subscribeCancel($user);
        } catch (Exception $e) {
            return back()->with(['message' => $e->getMessage(), 'type' => 'error']);
        }
    }

    public static function assignPlanByAdmin(Request $request)
    {
        $request->validate([
            'planID' => 'required',
            'userID' => 'required',
        ]);
        $planID = $request->planID;
        $userID = $request->userID;

        $user = User::find($userID);
        $plan = PaymentPlans::where('id', $planID)->first();
        $total = $plan->price;

        $gatewayCode = 'freeservice';
        $tax = 0;
        $taxRate = 0;
        $status = 'free_approved';
        $gateway = Gateways::where('is_active', 1)->first();
        if ($gateway != null) {
            $taxValue = taxToVal($plan->price, $gateway->tax);
            $total += $taxValue;
            $gatewayCode = $gateway->code;
            $tax = $taxValue;
            $taxRate = $gateway->tax;
            $status = $gateway->code . '_approved';
        }

        $currency = Currency::where('id', $gateway->currency)->first()->code;
        $settings = Setting::first();

        try {
            DB::beginTransaction();
            // Create the subscription with the customer ID, price ID, and necessary options.
            $subscription = new Subscriptions;
            $subscription->user_id = $user->id;
            $subscription->name = $planID;
            $subscription->stripe_id = 'FLS-' . strtoupper(Str::random(13));
            $subscription->stripe_status = $status;
            $subscription->stripe_price = 'Not Needed';
            $subscription->quantity = 1;
            $subscription->trial_ends_at = null;
            $subscription->ends_at = $plan->frequency == 'lifetime_monthly' ? \Carbon\Carbon::now()->addMonths(1) : \Carbon\Carbon::now()->addYears(1);
            $subscription->auto_renewal = 1;
            $subscription->plan_id = $planID;
            $subscription->paid_with = $gatewayCode;
            $subscription->tax_rate = $taxRate;
            $subscription->tax_value = $tax;
            $subscription->total_amount = $total;
            $subscription->save();

            // save the order
            $order = new UserOrder;
            $order->order_id = $subscription->stripe_id;
            $order->plan_id = $planID;
            $order->user_id = $user->id;
            $order->payment_type = $gatewayCode;
            $order->price = $total;
            $order->affiliate_earnings = ($total * $settings->affiliate_commission_percentage) / 100;
            $order->status = 'Success';
            $order->country = $user->country ?? 'Unknown';
            $order->tax_rate = $taxRate;
            $order->tax_value = $tax;
            $order->save();
            // add plan credits
            $plan->total_words == -1 ? ($user->remaining_words = -1) : ($user->remaining_words += $plan->total_words);
            $plan->total_images == -1 ? ($user->remaining_images = -1) : ($user->remaining_images += $plan->total_images);
            $user->save();
            // inform the admin
            CreateActivity::for($user, __('Subscribed to'), $plan->name . ' ' . __('Plan'), null);

            DB::commit();

            return back()->with([
                'message' => __('The plan has been successfully assigned to the user.'), 'type' => 'success',
            ]);
        } catch (Exception $ex) {
            DB::rollBack();
            Log::error($gatewayCode . '-> assignPlan(): ' . $ex->getMessage());

            return back()->with(['message' => Str::before($ex->getMessage(), ':'), 'type' => 'error']);
        }
    }

    public static function assignTokenByAdmin(Request $request)
    {
        $request->validate([
            'token'  => 'required',
            'userID' => 'required',
        ]);
        $planID = $request->token;
        $userID = $request->userID;

        $user = User::find($userID);
        $plan = PaymentPlans::where('id', $planID)->first();

        $total = $plan->price;

        $gatewayCode = 'freeservice';
        $tax = 0;
        $taxRate = 0;
        $status = 'free_approved';
        $gateway = Gateways::where('is_active', 1)->first();
        if ($gateway != null) {
            $taxValue = taxToVal($plan->price, $gateway->tax);
            $total += $taxValue;
            $gatewayCode = $gateway->code;
            $tax = $taxValue;
            $taxRate = $gateway->tax;
            $status = $gateway->code . '_approved';
        }

        try {
            DB::beginTransaction();
            $order = new UserOrder;
            $order->order_id = 'ADM-' . strtoupper(Str::random(13));
            $order->plan_id = $plan->id;
            $order->user_id = $user->id;
            $order->type = 'prepaid';
            $order->payment_type = $gatewayCode;
            $order->price = $plan->price;
            $order->affiliate_earnings = 0;
            $order->status = 'Approved';
            $order->country = $user->country ?? 'Unknown';
            $order->tax_rate = 0;
            $order->tax_value = 0;
            $order->save();

            $order->plan->total_words == -1 ? ($order->user->remaining_words = -1) : ($order->user->remaining_words += $order->plan->total_words);
            $order->plan->total_images == -1 ? ($order->user->remaining_images = -1) : ($order->user->remaining_images += $order->plan->total_images);
            $order->user->save();
            // sent mail if required here later
            CreateActivity::for($order->user, __('Purchased'), $order->plan->name . ' ' . __('Plan') . ' ' . __('For free'), null);
            DB::commit();

            return back()->with([
                'message' => __('The plan has been successfully assigned to the user.'), 'type' => 'success',
            ]);
        } catch (Exception $th) {
            DB::rollBack();
            Log::error($gatewayCode . '-> subscribe(): ' . $th->getMessage());

            return back()->with(['message' => Str::before($th->getMessage(), ':'), 'type' => 'error']);
        }
    }
}