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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace App\Services\PaymentGateways;

use App\Actions\CreateActivity;
use App\Models\Gateways;
use App\Models\RevenueCatProducts;
use App\Models\Setting;
use App\Models\User;
// use App\Models\SubscriptionItems;
use App\Models\UserOrder;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Subscription as Subscriptions;

class RevenueCatService
{
    public static function saveAllProducts()
    {
        return null;
    }

    public static function saveProduct()
    {
        return null;
    }

    public static function getSubscriptionDaysLeft()
    {
        $userId = Auth::user()->id;
        $activeSub = getCurrentActiveSubscription($userId);
        if ($activeSub != null) {
            if ($activeSub->stripe_status == 'trialing') {
                return \Carbon\Carbon::parse($activeSub->trial_ends_at)->diffInDays();
            } else {
                return \Carbon\Carbon::parse($activeSub->ends_at)->diffInDays();
            }
        }

        return null;

    }

    public static function getSubscriptionRenewDate()
    {
        $userId = Auth::user()->id;
        $activeSub = getCurrentActiveSubscription($userId);
        if ($activeSub != null) {
            if ($activeSub->stripe_status == 'trialing') {
                return \Carbon\Carbon::parse($activeSub->trial_ends_at)->format('F jS, Y');
            } else {
                return \Carbon\Carbon::parse($activeSub->ends_at)->format('F jS, Y');
            }
        }

        return null;

    }

    public static function getSubscriptionStatus($fromApi = false)
    {

        /// Developer Note:
        /// This functions returns true if user has an active subscription, otherwise returns false and null for errors
        /// If fromApi is true, then it returns json response instead of true/false/null
        /// Api responses are 4 types: 200, 404, 412, 500
        /// 200: Active subscription found
        /// 404: No active subscription found
        /// 412: Error occured
        /// 500: Error occured
        /// Mobile app displays returned error messages for 412 and 500 responses, but not for 404. Hence, do not change the messages and codes for these responses

        $user = Auth::user();
        $userId = $user->id;

        // Since this is RevenueCat (updates are made outside of our system), we need to get the subscription status from the RevenueCat API first
        // Get api key from gateway settings
        $gateway = Gateways::where('code', 'revenuecat')->first();
        if ($gateway == null) {
            Log::error('Gateway not found. RevenueCatService@getSubscriptionStatus');
            if ($fromApi) {
                return response()->json(['message' => 'Gateway not found.'], 412);
            } else {
                return null;
            }
        }

        $apiKey = $gateway->live_client_id;
        if ($apiKey == null) {
            Log::error('Gateway is not set properly. RevenueCatService@getSubscriptionStatus');
            if ($fromApi) {
                return response()->json(['message' => 'Gateway is not set properly.'], 412);
            } else {
                return null;
            }
        }

        $settings = Setting::first();

        // Get user's revenuecat id
        $user = Auth::user();
        $userId = $user->id;
        $userRevenueCatId = $user->revenuecat_id;

        if ($userRevenueCatId == null) {
            Log::error('User is not set properly. User must login at least once from mobile app. RevenueCatService@getSubscriptionStatus');
            if ($fromApi) {
                return response()->json(['message' => 'User is not set properly. User must login at least once from mobile app.'], 412);
            } else {
                return null;
            }
        }

        // Get subscription status from RevenueCat API
        $url = 'https://api.revenuecat.com/v1/subscribers/' . $userRevenueCatId;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        if ($response == null || $response == '' || $response == '{}') {
            Log::error('Error getting subscription status from RevenueCat API. RevenueCatService@getSubscriptionStatus');
            if ($fromApi) {
                return response()->json(['message' => 'Error getting subscription status from RevenueCat API.'], 500);
            } else {
                return null;
            }
        }

        $response = json_decode($response, true);

        $subscriber = $response['subscriber'];

        // Log::info('RevenueCat API Response: ' . json_encode($response));

        ///////////////////////////
        /// TOKEN PACKS
        ///////////////////////////
        $tokenPacks = $subscriber['non_subscriptions'];

        // check if all token packs are applied and saved to database
        /*
            "non_subscriptions": {
                "onetime": [
                    {
                    "id": "cadba0c81b",
                    "is_sandbox": true,
                    "purchase_date": "2019-04-05T21:52:45Z",
                    "store": "app_store"
                    }
                ],
            },
        */
        foreach ($tokenPacks as $identifier => $purchasedPacksArray) {

            foreach ($purchasedPacksArray as $pack) {

                $orders = UserOrder::where([['user_id', '=', $userId], ['order_id', '=', $pack['id']]])->get();

                if (count($orders) == 0) {
                    // Create order

                    $revenueCatProduct = RevenueCatProducts::where('google_id', $identifier)->first();
                    if ($revenueCatProduct == null) {
                        $revenueCatProduct = RevenueCatProducts::where('apple_id', $identifier)->first();
                        if ($revenueCatProduct == null) {
                            Log::error('RevenueCat product not found. Identifier: ' . $identifier);
                            if ($fromApi) {
                                return response()->json(['message' => 'RevenueCat product not found.'], 412);
                            } else {
                                return null;
                            }
                        }
                    }

                    $gatewayProduct = $revenueCatProduct->gateway_product;
                    if ($gatewayProduct == null) {
                        Log::error('Gateway product not found for RevenueCat. Identifier: ' . $identifier);
                        if ($fromApi) {
                            return response()->json(['message' => 'Gateway product not found.'], 412);
                        } else {
                            return null;
                        }
                    }

                    $plan = $revenueCatProduct->plan;
                    if ($plan == null) {
                        Log::error('Plan not found for RevenueCat. Identifier: ' . $identifier);
                        if ($fromApi) {
                            return response()->json(['message' => 'Plan not found.'], 412);
                        } else {
                            return null;
                        }
                    }

                    $order = new UserOrder;
                    $order->order_id = $pack['id'];
                    $order->plan_id = $plan->id;
                    $order->type = 'prepaid';
                    $order->user_id = $userId;
                    $order->payment_type = 'RevenueCat';
                    $order->price = $plan->price; // users must set coupons at stores - we are not allowed from external source
                    $order->affiliate_earnings = ($plan->price * $settings->affiliate_commission_percentage) / 100;
                    $order->status = 'Success';
                    $order->country = $user->country ?? 'Unknown';
                    $order->save();

                    $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();

                    CreateActivity::for($user, __('Purchased'), $plan->name . ' ' . __('Token Pack'));
                } else {
                    /// Order already exists, do nothing
                }

            }

        }

        ///////////////////////////
        /// SUBSCRIPTIONS
        ///////////////////////////
        $subscriptions = $subscriber['subscriptions'];
        /*
            "rc_promo_pro_cat_monthly": {
                "auto_resume_date": null,
                "billing_issues_detected_at": null,
                "expires_date": "2019-08-26T01:02:16Z",
                "grace_period_expires_date": null,
                "is_sandbox": false,
                "original_purchase_date": "2019-07-26T01:02:16Z",
                "ownership_type": "FAMILY_SHARED",
                "period_type": "normal",
                "purchase_date": "2019-07-26T01:02:16Z",
                "refunded_at": null,
                "store": "promotional",
                "unsubscribe_detected_at": null
            }
        */

        /// We are going to use "purchase_date" instead of "original_purchase_date" because "original_purchase_date" is not updated when user renews the subscription

        foreach ($subscriptions as $identifier => $subs) {

            $orderId = (string) $subs['purchase_date'];
            $orderId = str_replace('-', '', $orderId);
            $orderId = str_replace(':', '', $orderId);
            $orderId = str_replace(' ', '', $orderId);
            $orderId = str_replace('T', '', $orderId);
            $orderId = str_replace('Z', '', $orderId);

            $revenueCatProduct = RevenueCatProducts::where('google_id', $identifier)->first();
            if ($revenueCatProduct == null) {
                $revenueCatProduct = RevenueCatProducts::where('apple_id', $identifier)->first();
                if ($revenueCatProduct == null) {
                    Log::error('RevenueCat product not found. Identifier: ' . $identifier);
                    if ($fromApi) {
                        return response()->json(['message' => 'RevenueCat product not found.'], 412);
                    } else {
                        return null;
                    }
                }
            }

            $gatewayProduct = $revenueCatProduct->gateway_product;
            if ($gatewayProduct == null) {
                Log::error('Gateway product not found for RevenueCat. Identifier: ' . $identifier);
                if ($fromApi) {
                    return response()->json(['message' => 'Gateway product not found.'], 412);
                } else {
                    return null;
                }
            }

            $plan = $revenueCatProduct->plan;
            if ($plan == null) {
                Log::error('Plan not found for RevenueCat. Identifier: ' . $identifier);
                if ($fromApi) {
                    return response()->json(['message' => 'Plan not found.'], 412);
                } else {
                    return null;
                }
            }

            $planId = $plan->id;

            $orders = UserOrder::where([['user_id', '=', $userId], ['order_id', '=', $orderId]])->get();

            if (count($orders) == 0) {
                // Create order

                $order = new UserOrder;
                $order->order_id = $orderId;
                $order->plan_id = $planId;
                $order->type = 'subscription';
                $order->user_id = $userId;
                $order->payment_type = 'RevenueCat';
                $order->price = $plan->price; // users must set coupons at stores - we are not allowed from external source
                $order->affiliate_earnings = ($plan->price * $settings->affiliate_commission_percentage) / 100;
                $order->status = 'Success';
                $order->country = $user->country ?? 'Unknown';
                $order->save();

                $status = 'cancelled';

                $isRefreshed = false;

                /// Check if there is currently active subscription (in case of refresh/renew, orderId will be updated but plan remains the same)
                /// This is to prevent multiple active subscriptions for the same plan
                $oldSubscription = Subscriptions::where([['user_id', '=', $userId], ['plan_id', '=', $planId], ['stripe_status', '=', 'active']])->first();
                if ($oldSubscription != null) {
                    // There is an active subscription, cancel it
                    $oldSubscription->stripe_status = 'cancelled';
                    $oldSubscription->save();
                    $isRefreshed = true;
                }

                if ($subs['unsubscribe_detected_at'] == null) {
                    // Subscription is active
                    $isTrial = $subs['period_type'] == 'trial';
                    $status = $subs['billing_issues_detected_at'] == null ? ($isTrial == true ? 'trialing' : 'active') : 'cancelled';
                    if ($subs['billing_issues_detected_at'] != null) {
                        Log::error('Billing issue detected at RevenueCat. User ID: ' . $userId . ' Subscription: ' . $identifier);
                    }
                    /// Plan is active, and we haven't added to orders before; so this is a new subscription. Hence add the plan to user's remaining words and images
                    $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);

                    CreateActivity::for($user, ! $isRefreshed ? __('Subscribed') : __('Renewed'), $plan->name . ' ' . __('Plan'));
                } else {
                    // Subscription is cancelled
                    if ($subs['billing_issues_detected_at'] != null) {
                        Log::error('Billing issue detected at RevenueCat. User ID: ' . $userId . ' Subscription: ' . $identifier);
                    }
                    $planFrequency = $plan->frequency == 'monthly' ? 'month' : 'year';
                    if (Carbon::parse($subs['unsubscribe_detected_at'])->isBefore(Carbon::parse($subs['purchase_date'])->add(1, $planFrequency))) {
                        /// Subscription is cancelled before the end date (user cancelled it)
                        /// Since user cancelled it, we need to remove the plan from user's remaining words and images
                        /// Check if subscription with orderId is still active (in case of cancelled before)
                        $subscription = Subscriptions::where([['user_id', '=', $userId], ['stripe_id', '=', $orderId]])->first();
                        if ($subscription != null) {
                            if ($subscription->stripe_status == 'active' || $subscription->stripe_status == 'trialing') {
                                /// This is to cancel the subscription only once (orderId is unique and it is active/trial)
                                $plan->total_words == -1 ? ($user->remaining_words = 0) : ($user->remaining_words -= $plan->total_words);
                                $plan->total_images == -1 ? ($user->remaining_images = 0) : ($user->remaining_images -= $plan->total_images);
                                if ($user->remaining_words < 0) {
                                    $user->remaining_words = 0;
                                }
                                if ($user->remaining_images < 0) {
                                    $user->remaining_images = 0;
                                }
                                CreateActivity::for($user, __('Cancelled'), 'Subscription plan');
                            }
                        }
                    }
                }

                /// check if subscription is already added
                $subscription = Subscriptions::where([['user_id', '=', $userId], ['stripe_id', '=', $orderId]])->first();
                if ($subscription != null) {
                    // Subscription is already added, update it
                    $subscription->stripe_status = $status;
                    $subscription->trial_ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->save();
                } else {
                    // Subscription is not added, add it
                    $subscription = new Subscriptions;
                    $subscription->user_id = $userId;
                    $subscription->name = $planId;
                    $subscription->stripe_id = $orderId;
                    $subscription->stripe_status = $status;
                    $subscription->stripe_price = $gatewayProduct->price_id;
                    $subscription->quantity = 1;
                    $subscription->trial_ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->plan_id = $planId;
                    $subscription->paid_with = 'revenuecat';
                    $subscription->save();

                    // $subscriptionItem = new SubscriptionItems();
                    // $subscriptionItem->subscription_id = $subscription->id;
                    // $subscriptionItem->stripe_id = $orderId;
                    // $subscriptionItem->stripe_product = $gatewayProduct->product_id;
                    // $subscriptionItem->stripe_price = $gatewayProduct->price_id;
                    // $subscriptionItem->quantity = 1;
                    // $subscriptionItem->save();
                }

                $user->save();
            } else {
                /// Order already exists, but maybe subscription is cancelled

                $isTrial = $subs['period_type'] == 'trial';
                $status = ($subs['billing_issues_detected_at'] == null && $subs['unsubscribe_detected_at'] == null) ? ($isTrial == true ? 'trialing' : 'active') : 'cancelled';

                if ($subs['unsubscribe_detected_at'] != null) {
                    // Subscription is cancelled
                    if ($subs['billing_issues_detected_at'] != null) {
                        Log::error('Billing issue detected at RevenueCat. User ID: ' . $userId . ' Subscription: ' . $identifier);
                    }
                    $planFrequency = $plan->frequency == 'monthly' ? 'month' : 'year';
                    if (Carbon::parse($subs['unsubscribe_detected_at'])->isBefore(Carbon::parse($subs['purchase_date'])->add(1, $planFrequency))) {
                        /// Subscription is cancelled before the end date (user cancelled it)
                        /// Since user cancelled it, we need to remove the plan from user's remaining words and images

                        /// Check if subscription with orderId is still active (in case of cancelled before)
                        $subscription = Subscriptions::where([['user_id', '=', $userId], ['stripe_id', '=', $orderId]])->first();
                        if ($subscription != null) {
                            if ($subscription->stripe_status == 'active' || $subscription->stripe_status == 'trialing') {
                                /// This is to cancel the subscription only once (orderId is unique and it is active/trial)
                                $plan->total_words == -1 ? ($user->remaining_words = 0) : ($user->remaining_words -= $plan->total_words);
                                $plan->total_images == -1 ? ($user->remaining_images = 0) : ($user->remaining_images -= $plan->total_images);
                                if ($user->remaining_words < 0) {
                                    $user->remaining_words = 0;
                                }
                                if ($user->remaining_images < 0) {
                                    $user->remaining_images = 0;
                                }
                                CreateActivity::for($user, __('Cancelled'), 'Subscription plan');
                            }
                        }
                    }
                }

                /// check if subscription is already added
                $subscription = Subscriptions::where([['user_id', '=', $userId], ['stripe_id', '=', $orderId]])->first();
                if ($subscription == null) {
                    // Subscription is added while creating order
                    Log::error('Subscription is added while creating order. But not found on checks. User ID: ' . $userId . ' Subscription: ' . $identifier);
                } else {
                    // Subscription is already added, update it
                    $subscription->stripe_status = $status;
                    $subscription->trial_ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->ends_at = Carbon::parse($subs['expires_date']);
                    $subscription->save();
                }

                $user->save();

            }

        }

        ///////////////////////////
        /// Prepare Result
        ///////////////////////////

        /// We have checked both subscriptions and token packs, now we need to check if there is any active subscription and return the result

        // Get current active subscription
        $activeSub = getCurrentActiveSubscription($userId);
        if ($activeSub != null) {
            if ($fromApi) {
                return response()->json(['message' => __('Active subscription found.'), 'status' => 'active'], 200);
            }

            return true;
        }
        if ($fromApi) {
            return response()->json(['message' => 'No active subscription found.'], 404);
        }

        return false;

    }

    public static function checkIfTrial()
    {
        $userId = Auth::user()->id;
        $activeSub = getCurrentActiveSubscription($userId);
        if ($activeSub != null) {
            return $activeSub->stripe_status == 'trialing';
        }

        return false;
    }

    public static function gatewayDefinitionArray(): array
    {
        return [
            'code'                  => 'revenuecat',
            'title'                 => 'RevenueCat',
            'link'                  => 'https://www.revenuecat.com/',
            'active'                => 1,
            'available'             => 1,
            'img'                   => '/assets/img/payments/revenuecat.png',
            'whiteLogo'             => 0,
            'mode'                  => 0,
            'sandbox_client_id'     => 0,
            'sandbox_client_secret' => 0,
            'sandbox_app_id'        => 0,
            'live_client_id'        => 1,
            'live_client_secret'    => 0,
            'live_app_id'           => 0,
            'currency'              => 0,
            'currency_locale'       => 0,
            'notify_url'            => 0,
            'base_url'              => 0,
            'sandbox_url'           => 0,
            'locale'                => 0,
            'validate_ssl'          => 0,
            'webhook_secret'        => 0,
            'logger'                => 0,
            'tax'                   => 1,              // Option in settings
            'bank_account_details'  => 0,
            'bank_account_other'    => 0,
        ];
    }
}