Completed
Push — development ( c87275...b28f77 )
by Ashutosh
11:48
created

CartController::getValueForUnionTerritory()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 5
1
<?php
2
3
namespace App\Http\Controllers\Front;
4
5
use App\Http\Controllers\Common\TemplateController;
6
use App\Model\Common\Setting;
7
use App\Model\Payment\Currency;
8
use App\Model\Payment\PlanPrice;
9
use App\Model\Payment\Tax;
10
use App\Model\Payment\TaxByState;
11
use App\Model\Payment\TaxOption;
12
use App\Model\Payment\TaxProductRelation;
13
use App\Model\Product\Product;
14
use Bugsnag;
15
use Cart;
16
use Exception;
17
use Illuminate\Http\Request;
18
use Session;
19
20
class CartController extends BaseCartController
21
{
22
    public $templateController;
23
    public $product;
24
    public $currency;
25
    public $addons;
26
    public $addonRelation;
27
    public $licence;
28
    public $tax_option;
29
    public $tax_by_state;
30
    public $setting;
31
32
    public function __construct()
33
    {
34
        $templateController = new TemplateController();
35
        $this->templateController = $templateController;
36
37
        $product = new Product();
38
        $this->product = $product;
39
40
        $plan_price = new PlanPrice();
41
        $this->$plan_price = $plan_price;
42
43
        $currency = new Currency();
44
        $this->currency = $currency;
45
46
        $tax = new Tax();
47
        $this->tax = $tax;
48
49
        $setting = new Setting();
50
        $this->setting = $setting;
51
52
        $tax_option = new TaxOption();
53
        $this->tax_option = $tax_option;
54
55
        $tax_by_state = new TaxByState();
56
        $this->tax_by_state = new $tax_by_state();
57
58
        // $this->middleware('Inatall');
59
        // $this->middleware('admin');
60
    }
61
62
    public function productList(Request $request)
63
    {
64
        try {
65
            $cont = new \App\Http\Controllers\Front\GetPageTemplateController();
66
            $location = $cont->getLocation();
67
        } catch (\Exception $ex) {
68
            $location = false;
69
            $error = $ex->getMessage();
70
        }
71
72
        $country = $this->findCountryByGeoip($location['countryCode']);
73
        $states = $this->findStateByRegionId($location['countryCode']);
74
        $states = \App\Model\Common\State::pluck('state_subdivision_name', 'state_subdivision_code')->toArray();
75
        $state_code = $location['countryCode'].'-'.$location['region'];
76
        $state = $this->getStateByCode($state_code);
77
        $mobile_code = \App\Http\Controllers\Front\CartController::getMobileCodeByIso($location['countryCode']);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
78
        $currency = $cont->getCurrency($location);
79
80
        \Session::put('currency', $currency);
81
        if (!\Session::has('currency')) {
82
            \Session::put('currency', 'INR');
83
        }
84
85
        try {
86
            $page_controller = new PageController();
87
88
            return $page_controller->cart();
89
        } catch (\Exception $ex) {
90
            return redirect()->back()->with('fails', $ex->getMessage());
91
        }
92
    }
93
94
    public function cart(Request $request)
95
    {
96
        try {
97
            $plan = '';
98
99
            if ($request->has('subscription')) {
100
                $plan = $request->get('subscription');
101
102
                Session::put('plan', $plan);
103
            }
104
            $id = $request->input('id');
105
106
            if (!array_key_exists($id, Cart::getContent())) {
107
                $items = $this->addProduct($id);
108
109
                Cart::add($items);
110
            }
111
112
            return redirect('show/cart');
113
        } catch (\Exception $ex) {
114
            // dd($ex);
115
            return redirect()->back()->with('fails', $ex->getMessage());
116
        }
117
    }
118
119
    public function showCart()
120
    {
121
        try {
122
            $currency = 'INR';
123
            $cart_currency = 'INR';
124
            $attributes = [];
125
            $cartCollection = Cart::getContent();
126
            foreach ($cartCollection as $item) {
127
                $attributes[] = $item->attributes;
128
                $cart_currency = $attributes[0]['currency'];
129
                $currency = $attributes[0]['currency'];
130
                if (\Auth::user()) {
131
                    $cart_currency = $attributes[0]['currency'];
132
                    $user_currency = \Auth::user()->currency;
133
                    $user_country = \Auth::user()->country;
134
                    $user_state = \Auth::user()->state;
135
                    $currency = 'INR';
136
                    if ($user_currency == 1 || $user_currency == 'USD') {
137
                        $currency = 'USD';
138
                    }
139
                    if ($cart_currency != $currency) {
140
                        $id = $item->id;
141
                        Cart::remove($id);
142
                        $items = $this->addProduct($id);
143
144
                        Cart::add($items);
145
                        //
146
                    }
147
                }
148
            }
149
            return view('themes.default1.front.cart', compact('cartCollection', 'attributes'));
150
        } catch (\Exception $ex) {
151
            //dd($ex);
152
153
            return redirect()->back()->with('fails', $ex->getMessage());
154
        }
155
    }
156
157
    public function checkTax($productid, $user_state = '', $user_country = '')
158
    {
159
        try {
160
            $taxCondition = [];
161
            $tax_attribute = [];
162
            $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
163
            $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
164
                'name'   => 'null',
165
                'type'   => 'tax',
166
                'target' => 'item',
167
                'value'  => '0%',
168
            ]);
169
            $cont = new \App\Http\Controllers\Front\GetPageTemplateController();
170
            $location = $cont->getLocation();
171
172
            $country = $this->findCountryByGeoip($location['countryCode']);
173
            $states = $this->findStateByRegionId($location['countryCode']);
174
            $states = \App\Model\Common\State::pluck('state_subdivision_name', 'state_subdivision_code')->toArray();
175
            $state_code = $location['countryCode'].'-'.$location['region'];
176
            $state = $this->getStateByCode($state_code);
177
            $mobile_code = $this->getMobileCodeByIso($location['countryCode']);
178
            $country_iso = $location['countryCode'];
179
180
            $geoip_state = $this->getGeoipState($state_code, $user_state);
181
            $geoip_country = $this->getGeoipCountry($country_iso, $user_country);
182
183
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
184
                $tax_rule = $this->tax_option->findOrFail(1);
185
                $shop = $tax_rule->shop_inclusive;
186
                $cart = $tax_rule->cart_inclusive;
187
                $tax_enable = $this->tax_option->findOrFail(1)->tax_enable;
188
                //Check the state of user for calculating GST(cgst,igst,utgst,sgst)
189
                $user_state = TaxByState::where('state_code', $geoip_state)->first();
190
                $origin_state = $this->setting->first()->state; //Get the State of origin
191
                $tax_class_id = TaxProductRelation::where('product_id', $productid)->pluck('tax_class_id')->toArray();
192
193
                if ($tax_class_id) {//If the product is allowed for tax (Check in tax_product relation table)
194
                   if ($tax_enable == 1) {//If GST is Enabled
195
196
                       $state_code = '';
197
                       $c_gst = '';
198
                       $s_gst = '';
199
                       $i_gst = '';
200
                       $ut_gst = '';
201
                       $value = '';
202
                       $rate = '';
203
                       $status = 1;
204
205
                       if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
206
                           $c_gst = $user_state->c_gst;
207
                           $s_gst = $user_state->s_gst;
208
                           $i_gst = $user_state->i_gst;
209
                           $ut_gst = $user_state->ut_gst;
210
                           $state_code = $user_state->state_code;
211
212
                           if ($state_code == $origin_state) {//If user and origin state are same
213
                               $rateForSameState = $this->getTaxWhenIndianSameState($user_state,
214
                                $origin_state, $productid, $c_gst, $s_gst, $state_code, $status);
215
216
                               $taxes = $rateForSameState['taxes'];
217
                               $status = $rateForSameState['status'];
218
                               $value = $rateForSameState['value'];
219
                           } elseif ($state_code != $origin_state && $ut_gst == 'NULL') {//If user is from other state
220
                               $rateForOtherState = $this->getTaxWhenIndianOtherState($user_state,
221
                                $origin_state, $productid, $i_gst, $state_code, $status);
222
                               $taxes = $rateForOtherState['taxes'];
223
                               $status = $rateForOtherState['status'];
224
                               $value = $rateForOtherState['value'];
225
                           } elseif ($state_code != $origin_state && $ut_gst != 'NULL') {//if user from Union Territory
226
                               $rateForUnionTerritory = $this->getTaxWhenUnionTerritory($user_state,
227
                                $origin_state, $productid, $c_gst, $ut_gst, $state_code, $status);
228
                               $taxes = $rateForUnionTerritory['taxes'];
229
                               $status = $rateForUnionTerritory['status'];
230
                               $value = $rateForUnionTerritory['value'];
231
                           }
232
                       } else {//If user from other Country
233
                           $taxClassId = Tax::where('state', $geoip_state)
234
                           ->orWhere('country', $geoip_country)
235
                           ->pluck('tax_classes_id')->first();
236
                           if ($taxClassId) { //if state equals the user State or country equals user country
237
                               $taxForSpecificCountry = $this->getTaxForSpecificCountry($taxClassId,
238
                                $productid, $status);
239
                               $taxes = $taxForSpecificCountry['taxes'];
240
                               $status = $taxForSpecificCountry['status'];
241
                               $value = $taxForSpecificCountry['value'];
242
                               $rate = $taxForSpecificCountry['value'];
243
                           } else {//if Tax is selected for Any Country Any State
244
                               $taxClassId = Tax::where('country', '')
245
                               ->where('state', 'Any State')
246
                               ->pluck('tax_classes_id')->first();
247
                               if ($taxClassId) {
248
                                   $taxForAnyCountry = $this->getTaxForAnyCountry($taxClassId, $productid, $status);
249
                                   $taxes = $taxForAnyCountry['taxes'];
250
                                   $status = $taxForAnyCountry['status'];
251
                                   $value = $taxForAnyCountry['value'];
252
                                   $rate = $taxForAnyCountry['value'];
253
                               } else {
254
                                   $taxes = [0];
255
                               }
256
                           }
257
                       }
258
                       foreach ($taxes as $key => $tax) {
259
260
                                    //All the da a attribute that is sent to the checkout Page if tax_compound=0
261
                           if ($taxes[0]) {
262
                               $tax_attribute[$key] = ['name' => $tax->name, 'c_gst'=>$c_gst,
263
                               's_gst'                        => $s_gst, 'i_gst'=>$i_gst, 'ut_gst'=>$ut_gst,
264
                                'state'                       => $state_code, 'origin_state'=>$origin_state,
265
                                 'tax_enable'                 => $tax_enable, 'rate'=>$value, 'status'=>$status, ];
266
267
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
268
269
                                            'name'   => 'no compound',
270
                                            'type'   => 'tax',
271
                                            'target' => 'item',
272
                                            'value'  => $value,
273
                                          ]);
274
                           } else {
275
                               $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
276
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
277
                                           'name'   => 'null',
278
                                           'type'   => 'tax',
279
                                           'target' => 'item',
280
                                           'value'  => '0%',
281
                                         ]);
282
                           }
283
                       }
284
                   } elseif ($tax_enable == 0) {//If Tax enable is 0
285
                       $status = 1;
286
                       if ($this->tax_option->findOrFail(1)->tax_enable == 0) {
287
                           $taxClassId = Tax::where('country', '')
288
                           ->where('state', 'Any State')
289
                           ->pluck('tax_classes_id')->first(); //In case of India when
290
                           // other tax is available and tax is not enabled
291
                           if ($taxClassId) {
292
                               $taxes = $this->getTaxByPriority($taxClassId);
293
                               $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
294
                               if ($value == 0) {
295
                                   $status = 0;
296
                               }
297
                               $rate = $value;
298
                               foreach ($taxes as $key => $tax) {
299
                                   $tax_attribute[$key] = ['name' => $tax->name,
300
                                   'rate'                         => $value, 'tax_enable'=>0, 'status' => $status, ];
301
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
302
303
                                            'name'   => $tax->name,
304
                                            'type'   => 'tax',
305
                                            'target' => 'item',
306
                                            'value'  => $value,
307
                                        ]);
308
                               }
309
                           } else {//In case of other country
310
                               //when tax is available and tax is not enabled
311
                               //(Applicable when Global Tax class for any country and state is not there)
312
                               $taxClassId = Tax::where('state', $geoip_state)
313
                               ->orWhere('country', $geoip_country)
314
                               ->pluck('tax_classes_id')->first();
315
                               if ($taxClassId) { //if state equals the user State
316
                                   $taxes = $this->getTaxByPriority($taxClassId);
317
                                   $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
318
                                   if ($value == '') {
319
                                       $status = 0;
320
                                   }
321
                                   $rate = $value;
322
                               }
323
                               foreach ($taxes as $key => $tax) {
324
                                   $tax_attribute[$key] = ['name' => $tax->name,
325
                                   'rate'                         => $value, 'tax_enable'=>0, 'status' => $status, ];
326
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
327
328
                                            'name'   => $tax->name,
329
                                            'type'   => 'tax',
330
                                            'target' => 'item',
331
                                            'value'  => $value,
332
                                        ]);
333
                               }
334
                           }
335
                       }
336
                   }
337
                } else {
338
                    $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
339
                    $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
340
                'name'   => 'null',
341
                'type'   => 'tax',
342
                'target' => 'item',
343
                'value'  => '0%',
344
            ]);
345
                }
346
            }
347
348
            $currency_attribute = $this->addCurrencyAttributes($productid);
349
350
            return ['conditions' => $taxCondition,
351
            'attributes'         => ['tax' => $tax_attribute,
352
            'currency'                     => $currency_attribute, ], ];
353
        } catch (\Exception $ex) {
354
            Bugsnag::notifyException($ex);
355
356
            throw new \Exception('Can not check the tax');
357
        }
358
    }
359
360
    /**
361
     *   Get tax value for Same State.
362
     *
363
     * @param type $productid
364
     * @param type $c_gst
365
     * @param type $s_gst
366
     *                        return type
367
     */
368
    public function getValueForSameState($productid, $c_gst, $s_gst, $taxClassId, $taxes)
369
    {
370
        try {
371
            $value = '';
372
            $value = $taxes->toArray()[0]['active'] ?
373
374
                  (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
375
                        $c_gst + $s_gst.'%' : 0) : 0;
376
377
            return $value;
378
        } catch (Exception $ex) {
379
            Bugsnag::notifyException($ex);
380
381
            return redirect()->back()->with('fails', $ex->getMessage());
382
        }
383
    }
384
385
    /**
386
     *   Get tax value for Other States.
387
     *
388
     * @param type $productid
389
     * @param type $i_gst
390
     *                        return type
391
     */
392
    public function getValueForOtherState($productid, $i_gst, $taxClassId, $taxes)
393
    {
394
        $value = '';
395
        $value = $taxes->toArray()[0]['active'] ? //If the Current Class is active
396
              (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
397
                        $i_gst.'%' : 0) : 0; //IGST
398
399
        return $value;
400
    }
401
402
    /**
403
     *  Get tax value for Union Territory States.
404
     *
405
     * @param type $productid
406
     * @param type $c_gst
407
     * @param type $ut_gst
408
     *                        return type
409
     */
410
    public function getValueForUnionTerritory($productid, $c_gst, $ut_gst, $taxClassId, $taxes)
411
    {
412
        $value = '';
413
        $value = $taxes->toArray()[0]['active'] ?
414
             (TaxProductRelation::where('product_id', $productid)
415
              ->where('tax_class_id', $taxClassId)->count() ? $ut_gst + $c_gst.'%' : 0) : 0;
416
417
        return $value;
418
    }
419
420
    public function otherRate($productid)
421
    {
422
        $otherRate = '';
423
424
        return $otherRate;
425
    }
426
427
    public function getValueForOthers($productid, $taxClassId, $taxes)
428
    {
429
        $otherRate = 0;
430
        $status = $taxes->toArray()[0]['active'];
431
        if ($status && (TaxProductRelation::where('product_id', $productid)
432
          ->where('tax_class_id', $taxClassId)->count() > 0)) {
433
            $otherRate = Tax::where('tax_classes_id', $taxClassId)->first()->rate;
434
        }
435
        $value = $otherRate.'%';
436
437
        return $value;
438
    }
439
440
    public function cartRemove(Request $request)
441
    {
442
        $id = $request->input('id');
443
        Cart::remove($id);
444
445
        return 'success';
446
    }
447
448
    public function reduseQty(Request $request)
449
    {
450
        $id = $request->input('id');
451
        Cart::update($id, [
452
            'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
453
        ]);
454
455
        return 'success';
456
    }
457
458
    public function updateQty(Request $request)
459
    {
460
        $id = $request->input('productid');
461
        $qty = $request->input('qty');
462
        Cart::update($id, [
463
            'quantity' => [
464
                'relative' => false,
465
                'value'    => $qty,
466
            ],
467
        ]);
468
469
        return 'success';
470
    }
471
472
    /**
473
     * @return type
474
     */
475
    public function clearCart()
476
    {
477
        foreach (Cart::getContent() as $item) {
478
            if (\Session::has('domain'.$item->id)) {
479
                \Session::forget('domain'.$item->id);
480
            }
481
        }
482
        $this->removePlanSession();
483
        $renew_control = new \App\Http\Controllers\Order\RenewController();
484
        $renew_control->removeSession();
485
        Cart::clear();
486
487
        return redirect('show/cart');
488
    }
489
490
    /**
491
     * @param type $id
492
     * @param type $key
493
     * @param type $value
494
     */
495
    public function cartUpdate($id, $key, $value)
496
    {
497
        try {
498
            Cart::update(
499
                    $id, [
500
                $key => $value, // new item name
501
                    ]
502
            );
503
        } catch (\Exception $ex) {
504
            return redirect()->back()->with('fails', $ex->getMessage());
505
        }
506
    }
507
508
    /**
509
     * @param type $id
510
     *
511
     * @return array
512
     */
513
    public function addCurrencyAttributes($id)
514
    {
515
        try {
516
            $currency = $this->currency();
517
            $product = $this->product->where('id', $id)->first();
518
            if ($product) {
519
                $productCurrency = $this->currency();
520
                $currency = $this->currency->where('code', $productCurrency)->get()->toArray();
521
            } else {
522
                $currency = [];
523
            }
524
525
            return $currency;
526
        } catch (\Exception $ex) {
527
            //catch exception here
528
        }
529
    }
530
531
    /**
532
     * @return type
533
     */
534
    public function addCouponUpdate()
535
    {
536
        try {
537
            $code = \Input::get('coupon');
538
            $cart = Cart::getContent();
539
            foreach ($cart as $item) {
540
                $id = $item->id;
541
            }
542
            $promo_controller = new \App\Http\Controllers\Payment\PromotionController();
543
            $result = $promo_controller->checkCode($code, $id);
544
            if ($result == 'success') {
545
                return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
546
            }
547
548
            return redirect()->back();
549
        } catch (\Exception $ex) {
550
            dd($ex);
551
552
            return redirect()->back()->with('fails', $ex->getMessage());
553
        }
554
    }
555
556
    /**
557
     * @param type $tax_class_id
558
     *
559
     * @throws \Exception
560
     *
561
     * @return type
562
     */
563
    public function getTaxByPriority($taxClassId)
564
    {
565
        try {
566
            $taxe_relation = $this->tax->where('tax_classes_id', $taxClassId)->get();
567
568
            return $taxe_relation;
569
        } catch (\Exception $ex) {
570
            Bugsnag::notifyException($ex);
571
572
            throw new \Exception('error in get tax priority');
573
        }
574
    }
575
576
    /**
577
     * @param type $price
578
     *
579
     * @throws \Exception
580
     *
581
     * @return type
582
     */
583
    public static function rounding($price)
584
    {
585
        try {
586
            $tax_rule = new \App\Model\Payment\TaxOption();
587
            $rule = $tax_rule->findOrFail(1);
588
            $rounding = $rule->rounding;
589
            if ($rounding == 1) {
590
                // $price = str_replace(',', '', $price);
591
592
                return round($price);
593
            } else {
594
                return $price;
595
            }
596
        } catch (\Exception $ex) {
597
            dd($ex);
598
            Bugsnag::notifyException($ex);
599
            // throw new \Exception('error in get tax priority');
600
        }
601
    }
602
603
    /**
604
     * @return type
605
     */
606
    public function contactUs()
607
    {
608
        try {
609
            return view('themes.default1.front.contact');
610
        } catch (\Exception $ex) {
611
            return redirect()->back()->with('fails', $ex->getMessage());
612
        }
613
    }
614
615
    /**
616
     * @param Request $request
617
     *
618
     * @return type
619
     */
620
    public function postContactUs(Request $request)
621
    {
622
        $this->validate($request, [
623
            'name'    => 'required',
624
            'email'   => 'required|email',
625
            'message' => 'required',
626
        ]);
627
628
        $set = new \App\Model\Common\Setting();
629
        $set = $set->findOrFail(1);
630
631
        try {
632
            $from = $set->email;
633
            $fromname = $set->company;
634
            $toname = '';
635
            $to = '[email protected]';
636
            $data = '';
637
            $data .= 'Name: '.$request->input('name').'<br/s>';
638
            $data .= 'Email: '.$request->input('email').'<br/>';
639
            $data .= 'Message: '.$request->input('message').'<br/>';
640
            $data .= 'Mobile: '.$request->input('Mobile').'<br/>';
641
642
            $subject = 'Faveo billing enquiry';
643
            $this->templateController->Mailing($from, $to, $data, $subject, [], $fromname, $toname);
644
            //$this->templateController->Mailing($from, $to, $data, $subject);
645
            return redirect()->back()->with('success', 'Your message was sent successfully. Thanks.');
646
        } catch (\Exception $ex) {
647
            return redirect()->back()->with('fails', $ex->getMessage());
648
        }
649
    }
650
651
    /**
652
     * @param type $code
653
     *
654
     * @throws \Exception
655
     *
656
     * @return type
657
     */
658
    public static function getCountryByCode($code)
659
    {
660
        try {
661
            $country = \App\Model\Common\Country::where('country_code_char2', $code)->first();
662
            if ($country) {
663
                return $country->country_name;
664
            }
665
        } catch (\Exception $ex) {
666
            throw new \Exception($ex->getMessage());
667
        }
668
    }
669
670
    /**
671
     * @param type $name
672
     *
673
     * @throws \Exception
674
     *
675
     * @return string
676
     */
677
    public static function getTimezoneByName($name)
678
    {
679
        try {
680
            if ($name) {
681
                $timezone = \App\Model\Common\Timezone::where('name', $name)->first();
682
                if ($timezone) {
683
                    $timezone = $timezone->id;
684
                } else {
685
                    $timezone = '114';
686
                }
687
            } else {
688
                $timezone = '114';
689
            }
690
691
            return $timezone;
692
        } catch (\Exception $ex) {
693
            throw new \Exception($ex->getMessage());
694
        }
695
    }
696
697
    /**
698
     * @param type $code
699
     *
700
     * @throws \Exception
701
     *
702
     * @return type
703
     */
704
    public static function getStateByCode($code)
705
    {
706
        try {
707
            $result = ['id' => '', 'name' => ''];
708
709
            $subregion = \App\Model\Common\State::where('state_subdivision_code', $code)->first();
710
            if ($subregion) {
711
                $result = ['id' => $subregion->state_subdivision_code,
712
713
                     'name' => $subregion->state_subdivision_name, ];
714
            }
715
716
            return $result;
717
        } catch (\Exception $ex) {
718
            throw new \Exception($ex->getMessage());
719
        }
720
    }
721
722
    /**
723
     * @param type $id
724
     *
725
     * @throws \Exception
726
     *
727
     * @return type
728
     */
729
    public static function getStateNameById($id)
730
    {
731
        try {
732
            $name = '';
733
            $subregion = \App\Model\Common\State::where('state_subdivision_id', $id)->first();
734
            if ($subregion) {
735
                $name = $subregion->state_subdivision_name;
736
            }
737
738
            return $name;
739
        } catch (\Exception $ex) {
740
            throw new \Exception($ex->getMessage());
741
        }
742
    }
743
744
    /**
745
     * @param type $productid
746
     * @param type $price
747
     * @param type $cart
748
     * @param type $cart1
749
     * @param type $shop
750
     *
751
     * @return type
752
     */
753
    public static function calculateTax($productid, $price, $cart = 1, $cart1 = 0, $shop = 0)
754
    {
755
        try {
756
            $template_controller = new TemplateController();
757
            $result = $template_controller->checkTax($productid, $price, $cart, $cart1, $shop);
758
759
            $result = self::rounding($result);
760
761
            return $result;
762
        } catch (\Exception $ex) {
763
            return redirect()->back()->with('fails', $ex->getMessage());
764
        }
765
    }
766
767
    /**
768
     * @param type $rate
769
     * @param type $price
770
     *
771
     * @return type
772
     */
773
    public static function taxValue($rate, $price)
774
    {
775
        try {
776
            $tax = $price * ($rate / 100);
777
            $result = $tax;
778
779
            $result = self::rounding($result);
780
781
            return $result;
782
        } catch (\Exception $ex) {
783
            return redirect()->back()->with('fails', $ex->getMessage());
784
        }
785
    }
786
787
    /**
788
     * @return type
789
     */
790
    public static function addons()
791
    {
792
        try {
793
            $items = Cart::getContent();
794
            $cart_productids = [];
795
            if (count($items) > 0) {
796
                foreach ($items as $key => $item) {
797
                    $cart_productids[] = $key;
798
                }
799
            }
800
            $_this = new self();
801
            $products = $_this->products($cart_productids);
802
803
            return $products;
804
        } catch (\Exception $ex) {
805
            return redirect()->back()->with('fails', $ex->getMessage());
806
        }
807
    }
808
809
    /**
810
     * @param type $ids
811
     *
812
     * @throws \Exception
813
     *
814
     * @return type
815
     */
816
    public function products($ids)
817
    {
818
        $parents_string = [];
819
        $parent = [];
820
        $productid = [];
821
822
        try {
823
            $parents = $this->product
824
                    ->whereNotNull('parent')
825
                    ->where('parent', '!=', 0)
826
                    ->where('category', 'addon')
827
                    ->pluck('parent', 'id')
828
                    ->toArray();
829
            foreach ($parents as $key => $parent) {
830
                if (is_array($parent)) {
831
                    $parent = implode(',', $parent);
832
                }
833
                $parents_string[$key] = $parent;
834
            }
835
            if (count($parents_string) > 0) {
836
                foreach ($parents_string as $key => $value) {
837
                    if (strpos($value, ',') !== false) {
838
                        $value = explode(',', $value);
839
                    }
840
                    $parent[$key] = $value;
841
                }
842
            }
843
844
            foreach ($parent as $key => $id) {
845
                if (in_array($id, $ids)) {
846
                    $productid[] = $key;
847
                }
848
                if (is_array($id)) {
849
                    foreach ($id as $i) {
850
                        if (in_array($i, $ids)) {
851
                            $productid[] = $key;
852
                        }
853
                    }
854
                }
855
            }
856
            $parent_products = $this->getProductById($productid);
857
858
            return $parent_products;
859
        } catch (\Exception $ex) {
860
            Bugsnag::notifyException($ex);
861
862
            throw new \Exception($ex->getMessage());
863
        }
864
    }
865
866
    /**
867
     * @param type $ids
868
     *
869
     * @throws \Exception
870
     *
871
     * @return type
872
     */
873
    public function getProductById($ids)
874
    {
875
        try {
876
            $products = [];
877
            if (count($ids) > 0) {
878
                $products = $this->product
879
                        ->whereIn('id', $ids)
880
                        ->get();
881
            }
882
883
            return $products;
884
        } catch (\Exception $ex) {
885
            dd($ex);
886
887
            throw new \Exception($ex->getMessage());
888
        }
889
    }
890
891
    /**
892
     * @param type $iso
893
     *
894
     * @throws \Exception
895
     *
896
     * @return type
897
     */
898
    public static function getMobileCodeByIso($iso)
899
    {
900
        try {
901
            $code = '';
902
            if ($iso != '') {
903
                $mobile = \DB::table('mobile')->where('iso', $iso)->first();
904
                if ($mobile) {
905
                    $code = $mobile->phonecode;
906
                }
907
            }
908
909
            return $code;
910
        } catch (\Exception $ex) {
911
            throw new \Exception($ex->getMessage());
912
        }
913
    }
914
915
    /**
916
     * @param type $userid
917
     *
918
     * @throws \Exception
919
     *
920
     * @return string
921
     */
922
    public function currency($userid = '')
923
    {
924
        try {
925
            $currency = 'INR';
926
            if ($this->checkCurrencySession() === true) {
927
                $currency = Session::get('currency');
928
            }
929
930
            if (\Auth::user()) {
931
                $currency = \Auth::user()->currency;
932
                if ($currency == 'USD' || $currency == '1') {
933
                    $currency = 'USD';
934
                }
935
            }
936
            if ($userid != '') {
937
               $currency = $this->getCurrency($userid);
938
            }
939
            return $currency;
940
        } catch (\Exception $ex) {
941
            throw new \Exception($ex->getMessage());
942
        }
943
    }
944
945
    public function getCurrency($userid)
946
    {
947
      $user = new \App\User();
948
      $currency = $user->find($userid)->currency;
949
      if ($currency == 'USD' || $currency == '1') {
950
          $currency = 'USD';
951
      } else {
952
          $currency = 'INR';
953
      }
954
      return $currency;
955
    }
956
957
    /**
958
     * @throws \Exception
959
     */
960
    public function removePlanSession()
961
    {
962
        try {
963
            if (Session::has('plan')) {
964
                Session::forget('plan');
965
            }
966
        } catch (\Exception $ex) {
967
            throw new \Exception($ex->getMessage());
968
        }
969
    }
970
971
    /**
972
     * @throws \Exception
973
     *
974
     * @return bool
975
     */
976
    public function checkPlanSession()
977
    {
978
        try {
979
            if (Session::has('plan')) {
980
                return true;
981
            }
982
983
            return false;
984
        } catch (\Exception $ex) {
985
            throw new \Exception($ex->getMessage());
986
        }
987
    }
988
989
    /**
990
     * @param type $productid
991
     * @param type $userid
992
     * @param type $planid
993
     *
994
     * @return type
995
     */
996
    public function cost($productid, $userid = '', $planid = '')
997
    {
998
        try {
999
            $cost = $this->planCost($productid, $userid, $planid);
1000
            if ($cost == 0) {
1001
                $cost = $this->productCost($productid, $userid);
1002
            }
1003
1004
            return self::rounding($cost);
1005
        } catch (\Exception $ex) {
1006
            // throw new \Exception($ex->getMessage());
1007
        }
1008
    }
1009
1010
    /**
1011
     * @param type $productid
1012
     * @param type $userid
1013
     *
1014
     * @throws \Exception
1015
     *
1016
     * @return type
1017
     */
1018
    public function productCost($productid, $userid = '')
1019
    {
1020
        try {
1021
            $sales = 0;
1022
            $currency = $this->currency($userid);
1023
            $product = $this->product->find($productid);
1024
            $price = $product->price()->where('currency', $currency)->first();
1025
            if ($price) {
1026
                $sales = $price->sales_price;
1027
                if ($sales == 0) {
1028
                    $sales = $price->price;
1029
                }
1030
            }
1031
            //}
1032
1033
            return $sales;
1034
        } catch (\Exception $ex) {
1035
            throw new \Exception($ex->getMessage());
1036
        }
1037
    }
1038
1039
    /**
1040
     * @param type $productid
1041
     * @param type $userid
1042
     * @param type $planid
1043
     *
1044
     * @throws \Exception
1045
     *
1046
     * @return type
1047
     */
1048
    public function planCost($productid, $userid, $planid = '')
1049
    {
1050
        try {
1051
            $cost = 0;
1052
            $subscription = $this->allowSubscription($productid);
1053
            if ($this->checkPlanSession() === true) {
1054
                $planid = Session::get('plan');
1055
            }
1056
1057
            if ($subscription === true) {
1058
                $plan = new \App\Model\Payment\Plan();
1059
                $plan = $plan->where('id', $planid)->where('product', $productid)->first();
1060
1061
                if ($plan) {
1062
                    $currency = $this->currency($userid);
1063
                    $price = $plan->planPrice()
1064
                                    ->where('currency', $currency)
1065
                                    ->first()
1066
                            ->add_price;
1067
                    $days = $plan->days;
1068
                    $months = $days / 30 / 12;
1069
                    $cost = round($months) * $price;
1070
                }
1071
            }
1072
1073
            return $cost;
1074
        } catch (\Exception $ex) {
1075
            throw new \Exception($ex->getMessage());
1076
        }
1077
    }
1078
1079
    /**
1080
     * @throws \Exception
1081
     *
1082
     * @return bool
1083
     */
1084
    public function checkCurrencySession()
1085
    {
1086
        try {
1087
            if (Session::has('currency')) {
1088
                return true;
1089
            }
1090
1091
            return false;
1092
        } catch (\Exception $ex) {
1093
            throw new \Exception($ex->getMessage());
1094
        }
1095
    }
1096
1097
    /**
1098
     * @param type $productid
1099
     *
1100
     * @throws \Exception
1101
     *
1102
     * @return bool
1103
     */
1104
    public function allowSubscription($productid)
1105
    {
1106
        try {
1107
            $reponse = false;
1108
            $product = $this->product->find($productid);
1109
            if ($product) {
1110
                if ($product->subscription == 1) {
1111
                    $reponse = true;
1112
                }
1113
            }
1114
1115
            return $reponse;
1116
        } catch (\Exception $ex) {
1117
            throw new \Exception($ex->getMessage());
1118
        }
1119
    }
1120
}
1121