Completed
Push — development ( c63668...24f425 )
by Ashutosh
09:30
created

CartController::planCost()   B

Complexity

Conditions 6
Paths 23

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 33
rs 8.9297
c 0
b 0
f 0
cc 6
nc 23
nop 3
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 = $this->getMobileCodeByIso($location['countryCode']);
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
150
            return view('themes.default1.front.cart', compact('cartCollection', 'attributes'));
151
        } catch (\Exception $ex) {
152
            //dd($ex);
153
154
            return redirect()->back()->with('fails', $ex->getMessage());
155
        }
156
    }
157
158
    public function checkTax($productid, $user_state = '', $user_country = '')
159
    {
160
        try {
161
            $taxCondition = [];
162
            $tax_attribute = [];
163
            $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
164
            $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
165
                'name'   => 'null',
166
                'type'   => 'tax',
167
                'target' => 'item',
168
                'value'  => '0%',
169
            ]);
170
            $cont = new \App\Http\Controllers\Front\GetPageTemplateController();
171
            $location = $cont->getLocation();
172
173
            $country = $this->findCountryByGeoip($location['countryCode']);
174
            $states = $this->findStateByRegionId($location['countryCode']);
175
            $states = \App\Model\Common\State::pluck('state_subdivision_name', 'state_subdivision_code')->toArray();
176
            $state_code = $location['countryCode'].'-'.$location['region'];
177
            $state = $this->getStateByCode($state_code);
178
            $mobile_code = $this->getMobileCodeByIso($location['countryCode']);
179
            $country_iso = $location['countryCode'];
180
181
            $geoip_state = $this->getGeoipState($state_code, $user_state);
182
            $geoip_country = $this->getGeoipCountry($country_iso, $user_country);
183
184
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
185
                $tax_rule = $this->tax_option->findOrFail(1);
186
                $shop = $tax_rule->shop_inclusive;
187
                $cart = $tax_rule->cart_inclusive;
188
                $tax_enable = $this->tax_option->findOrFail(1)->tax_enable;
189
                //Check the state of user for calculating GST(cgst,igst,utgst,sgst)
190
                $user_state = TaxByState::where('state_code', $geoip_state)->first();
191
                $origin_state = $this->setting->first()->state; //Get the State of origin
192
                $tax_class_id = TaxProductRelation::where('product_id', $productid)->pluck('tax_class_id')->toArray();
193
194
                if ($tax_class_id) {//If the product is allowed for tax (Check in tax_product relation table)
195
                   if ($tax_enable == 1) {//If GST is Enabled
196
197
                       $state_code = '';
198
                       $c_gst = '';
199
                       $s_gst = '';
200
                       $i_gst = '';
201
                       $ut_gst = '';
202
                       $value = '';
203
                       $rate = '';
204
                       $status = 1;
205
206
                       if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
207
                           $c_gst = $user_state->c_gst;
208
                           $s_gst = $user_state->s_gst;
209
                           $i_gst = $user_state->i_gst;
210
                           $ut_gst = $user_state->ut_gst;
211
                           $state_code = $user_state->state_code;
212
213
                           if ($state_code == $origin_state) {//If user and origin state are same
214
                               $rateForSameState = $this->getTaxWhenIndianSameState($user_state,
215
                                $origin_state, $productid, $c_gst, $s_gst, $state_code, $status);
216
217
                               $taxes = $rateForSameState['taxes'];
218
                               $status = $rateForSameState['status'];
219
                               $value = $rateForSameState['value'];
220
                           } elseif ($state_code != $origin_state && $ut_gst == 'NULL') {//If user is from other state
221
                               $rateForOtherState = $this->getTaxWhenIndianOtherState($user_state,
222
                                $origin_state, $productid, $i_gst, $state_code, $status);
223
                               $taxes = $rateForOtherState['taxes'];
224
                               $status = $rateForOtherState['status'];
225
                               $value = $rateForOtherState['value'];
226
                           } elseif ($state_code != $origin_state && $ut_gst != 'NULL') {//if user from Union Territory
227
                               $rateForUnionTerritory = $this->getTaxWhenUnionTerritory($user_state,
228
                                $origin_state, $productid, $c_gst, $ut_gst, $state_code, $status);
229
                               $taxes = $rateForUnionTerritory['taxes'];
230
                               $status = $rateForUnionTerritory['status'];
231
                               $value = $rateForUnionTerritory['value'];
232
                           }
233
                       } else {//If user from other Country
234
                           $taxClassId = Tax::where('state', $geoip_state)
235
                           ->orWhere('country', $geoip_country)
236
                           ->pluck('tax_classes_id')->first();
237
                           if ($taxClassId) { //if state equals the user State or country equals user country
238
                               $taxForSpecificCountry = $this->getTaxForSpecificCountry($taxClassId,
239
                                $productid, $status);
240
                               $taxes = $taxForSpecificCountry['taxes'];
241
                               $status = $taxForSpecificCountry['status'];
242
                               $value = $taxForSpecificCountry['value'];
243
                               $rate = $taxForSpecificCountry['value'];
244
                           } else {//if Tax is selected for Any Country Any State
245
                               $taxClassId = Tax::where('country', '')
246
                               ->where('state', 'Any State')
247
                               ->pluck('tax_classes_id')->first();
248
                               if ($taxClassId) {
249
                                   $taxForAnyCountry = $this->getTaxForAnyCountry($taxClassId, $productid, $status);
250
                                   $taxes = $taxForAnyCountry['taxes'];
251
                                   $status = $taxForAnyCountry['status'];
252
                                   $value = $taxForAnyCountry['value'];
253
                                   $rate = $taxForAnyCountry['value'];
254
                               } else {
255
                                   $taxes = [0];
256
                               }
257
                           }
258
                       }
259
                       foreach ($taxes as $key => $tax) {
260
261
                                    //All the da a attribute that is sent to the checkout Page if tax_compound=0
262
                           if ($taxes[0]) {
263
                               $tax_attribute[$key] = ['name' => $tax->name, 'c_gst'=>$c_gst,
264
                               's_gst'                        => $s_gst, 'i_gst'=>$i_gst, 'ut_gst'=>$ut_gst,
265
                                'state'                       => $state_code, 'origin_state'=>$origin_state,
266
                                 'tax_enable'                 => $tax_enable, 'rate'=>$value, 'status'=>$status, ];
267
268
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
269
270
                                            'name'   => 'no compound',
271
                                            'type'   => 'tax',
272
                                            'target' => 'item',
273
                                            'value'  => $value,
274
                                          ]);
275
                           } else {
276
                               $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
277
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
278
                                           'name'   => 'null',
279
                                           'type'   => 'tax',
280
                                           'target' => 'item',
281
                                           'value'  => '0%',
282
                                         ]);
283
                           }
284
                       }
285
                   } elseif ($tax_enable == 0) {//If Tax enable is 0
286
                       $status = 1;
287
                       if ($this->tax_option->findOrFail(1)->tax_enable == 0) {
288
                           $taxClassId = Tax::where('country', '')
289
                           ->where('state', 'Any State')
290
                           ->pluck('tax_classes_id')->first(); //In case of India when
291
                           // other tax is available and tax is not enabled
292
                           if ($taxClassId) {
293
                               $taxes = $this->getTaxByPriority($taxClassId);
294
                               $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
295
                               if ($value == 0) {
296
                                   $status = 0;
297
                               }
298
                               $rate = $value;
299
                               foreach ($taxes as $key => $tax) {
300
                                   $tax_attribute[$key] = ['name' => $tax->name,
301
                                   'rate'                         => $value, 'tax_enable'=>0, 'status' => $status, ];
302
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
303
304
                                            'name'   => $tax->name,
305
                                            'type'   => 'tax',
306
                                            'target' => 'item',
307
                                            'value'  => $value,
308
                                        ]);
309
                               }
310
                           } else {//In case of other country
311
                               //when tax is available and tax is not enabled
312
                               //(Applicable when Global Tax class for any country and state is not there)
313
                               $taxClassId = Tax::where('state', $geoip_state)
314
                               ->orWhere('country', $geoip_country)
315
                               ->pluck('tax_classes_id')->first();
316
                               if ($taxClassId) { //if state equals the user State
317
                                   $taxes = $this->getTaxByPriority($taxClassId);
318
                                   $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
319
                                   if ($value == '') {
320
                                       $status = 0;
321
                                   }
322
                                   $rate = $value;
323
                               }
324
                               foreach ($taxes as $key => $tax) {
325
                                   $tax_attribute[$key] = ['name' => $tax->name,
326
                                   'rate'                         => $value, 'tax_enable'=>0, 'status' => $status, ];
327
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
328
329
                                            'name'   => $tax->name,
330
                                            'type'   => 'tax',
331
                                            'target' => 'item',
332
                                            'value'  => $value,
333
                                        ]);
334
                               }
335
                           }
336
                       }
337
                   }
338
                } else {
339
                    $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
340
                    $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
341
                'name'   => 'null',
342
                'type'   => 'tax',
343
                'target' => 'item',
344
                'value'  => '0%',
345
            ]);
346
                }
347
            }
348
349
            $currency_attribute = $this->addCurrencyAttributes($productid);
350
351
            return ['conditions' => $taxCondition,
352
            'attributes'         => ['tax' => $tax_attribute,
353
            'currency'                     => $currency_attribute, ], ];
354
        } catch (\Exception $ex) {
355
            Bugsnag::notifyException($ex);
356
357
            throw new \Exception('Can not check the tax');
358
        }
359
    }
360
361
    /**
362
     *   Get tax value for Same State.
363
     *
364
     * @param type $productid
365
     * @param type $c_gst
366
     * @param type $s_gst
367
     *                        return type
368
     */
369
    public function getValueForSameState($productid, $c_gst, $s_gst, $taxClassId, $taxes)
370
    {
371
        try {
372
            $value = '';
373
            $value = $taxes->toArray()[0]['active'] ?
374
375
                  (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
376
                        $c_gst + $s_gst.'%' : 0) : 0;
377
378
            return $value;
379
        } catch (Exception $ex) {
380
            Bugsnag::notifyException($ex);
381
382
            return redirect()->back()->with('fails', $ex->getMessage());
383
        }
384
    }
385
386
    /**
387
     *   Get tax value for Other States.
388
     *
389
     * @param type $productid
390
     * @param type $i_gst
391
     *                        return type
392
     */
393
    public function getValueForOtherState($productid, $i_gst, $taxClassId, $taxes)
394
    {
395
        $value = '';
396
        $value = $taxes->toArray()[0]['active'] ? //If the Current Class is active
397
              (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
398
                        $i_gst.'%' : 0) : 0; //IGST
399
400
        return $value;
401
    }
402
403
    /**
404
     *  Get tax value for Union Territory States.
405
     *
406
     * @param type $productid
407
     * @param type $c_gst
408
     * @param type $ut_gst
409
     *                        return type
410
     */
411
    public function getValueForUnionTerritory($productid, $c_gst, $ut_gst, $taxClassId, $taxes)
412
    {
413
        $value = '';
414
        $value = $taxes->toArray()[0]['active'] ?
415
             (TaxProductRelation::where('product_id', $productid)
416
              ->where('tax_class_id', $taxClassId)->count() ? $ut_gst + $c_gst.'%' : 0) : 0;
417
418
        return $value;
419
    }
420
421
    public function otherRate($productid)
422
    {
423
        $otherRate = '';
424
425
        return $otherRate;
426
    }
427
428
    public function getValueForOthers($productid, $taxClassId, $taxes)
429
    {
430
        $otherRate = 0;
431
        $status = $taxes->toArray()[0]['active'];
432
        if ($status && (TaxProductRelation::where('product_id', $productid)
433
          ->where('tax_class_id', $taxClassId)->count() > 0)) {
434
            $otherRate = Tax::where('tax_classes_id', $taxClassId)->first()->rate;
435
        }
436
        $value = $otherRate.'%';
437
438
        return $value;
439
    }
440
441
    public function cartRemove(Request $request)
442
    {
443
        $id = $request->input('id');
444
        Cart::remove($id);
445
446
        return 'success';
447
    }
448
449
    public function reduseQty(Request $request)
450
    {
451
        $id = $request->input('id');
452
        Cart::update($id, [
453
            'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
454
        ]);
455
456
        return 'success';
457
    }
458
459
    public function updateQty(Request $request)
460
    {
461
        $id = $request->input('productid');
462
        $qty = $request->input('qty');
463
        Cart::update($id, [
464
            'quantity' => [
465
                'relative' => false,
466
                'value'    => $qty,
467
            ],
468
        ]);
469
470
        return 'success';
471
    }
472
473
    /**
474
     * @return type
475
     */
476
    public function clearCart()
477
    {
478
        foreach (Cart::getContent() as $item) {
479
            if (\Session::has('domain'.$item->id)) {
480
                \Session::forget('domain'.$item->id);
481
            }
482
        }
483
        $this->removePlanSession();
484
        $renew_control = new \App\Http\Controllers\Order\RenewController();
485
        $renew_control->removeSession();
486
        Cart::clear();
487
488
        return redirect('show/cart');
489
    }
490
491
    /**
492
     * @param type $id
493
     * @param type $key
494
     * @param type $value
495
     */
496
    public function cartUpdate($id, $key, $value)
497
    {
498
        try {
499
            Cart::update(
500
                    $id, [
501
                $key => $value, // new item name
502
                    ]
503
            );
504
        } catch (\Exception $ex) {
505
            return redirect()->back()->with('fails', $ex->getMessage());
506
        }
507
    }
508
509
    /**
510
     * @param type $id
511
     *
512
     * @return array
513
     */
514
    public function addCurrencyAttributes($id)
515
    {
516
        try {
517
            $currency = $this->currency();
518
            $product = $this->product->where('id', $id)->first();
519
            if ($product) {
520
                $productCurrency = $this->currency();
521
                $currency = $this->currency->where('code', $productCurrency)->get()->toArray();
522
            } else {
523
                $currency = [];
524
            }
525
526
            return $currency;
527
        } catch (\Exception $ex) {
528
            //catch exception here
529
        }
530
    }
531
532
    /**
533
     * @return type
534
     */
535
    public function addCouponUpdate()
536
    {
537
        try {
538
            $code = \Input::get('coupon');
539
            $cart = Cart::getContent();
540
            foreach ($cart as $item) {
541
                $id = $item->id;
542
            }
543
            $promo_controller = new \App\Http\Controllers\Payment\PromotionController();
544
            $result = $promo_controller->checkCode($code, $id);
545
            if ($result == 'success') {
546
                return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
547
            }
548
549
            return redirect()->back();
550
        } catch (\Exception $ex) {
551
            return redirect()->back()->with('fails', $ex->getMessage());
552
        }
553
    }
554
555
    /**
556
     * @param type $tax_class_id
557
     *
558
     * @throws \Exception
559
     *
560
     * @return type
561
     */
562
    public function getTaxByPriority($taxClassId)
563
    {
564
        try {
565
            $taxe_relation = $this->tax->where('tax_classes_id', $taxClassId)->get();
566
567
            return $taxe_relation;
568
        } catch (\Exception $ex) {
569
            Bugsnag::notifyException($ex);
570
571
            throw new \Exception('error in get tax priority');
572
        }
573
    }
574
575
    /**
576
     * @param type $price
577
     *
578
     * @throws \Exception
579
     *
580
     * @return type
581
     */
582
    public static function rounding($price)
583
    {
584
        try {
585
            $tax_rule = new \App\Model\Payment\TaxOption();
586
            $rule = $tax_rule->findOrFail(1);
587
            $rounding = $rule->rounding;
588
            if ($rounding == 1) {
589
                return round($price);
590
            } else {
591
                return $price;
592
            }
593
        } catch (\Exception $ex) {
594
            Bugsnag::notifyException($ex);
595
            // throw new \Exception('error in get tax priority');
596
        }
597
    }
598
599
    /**
600
     * @return type
601
     */
602
    public function contactUs()
603
    {
604
        try {
605
            return view('themes.default1.front.contact');
606
        } catch (\Exception $ex) {
607
            return redirect()->back()->with('fails', $ex->getMessage());
608
        }
609
    }
610
611
    /**
612
     * @param Request $request
613
     *
614
     * @return type
615
     */
616
    public function postContactUs(Request $request)
617
    {
618
        $this->validate($request, [
619
            'name'    => 'required',
620
            'email'   => 'required|email',
621
            'message' => 'required',
622
        ]);
623
624
        $set = new \App\Model\Common\Setting();
625
        $set = $set->findOrFail(1);
626
627
        try {
628
            $from = $set->email;
629
            $fromname = $set->company;
630
            $toname = '';
631
            $to = '[email protected]';
632
            $data = '';
633
            $data .= 'Name: '.$request->input('name').'<br/s>';
634
            $data .= 'Email: '.$request->input('email').'<br/>';
635
            $data .= 'Message: '.$request->input('message').'<br/>';
636
            $data .= 'Mobile: '.$request->input('Mobile').'<br/>';
637
638
            $subject = 'Faveo billing enquiry';
639
            $this->templateController->Mailing($from, $to, $data, $subject, [], $fromname, $toname);
640
            //$this->templateController->Mailing($from, $to, $data, $subject);
641
            return redirect()->back()->with('success', 'Your message was sent successfully. Thanks.');
642
        } catch (\Exception $ex) {
643
            return redirect()->back()->with('fails', $ex->getMessage());
644
        }
645
    }
646
647
    /**
648
     * @param type $code
649
     *
650
     * @throws \Exception
651
     *
652
     * @return type
653
     */
654
    public static function getCountryByCode($code)
655
    {
656
        try {
657
            $country = \App\Model\Common\Country::where('country_code_char2', $code)->first();
658
            if ($country) {
659
                return $country->country_name;
660
            }
661
        } catch (\Exception $ex) {
662
            throw new \Exception($ex->getMessage());
663
        }
664
    }
665
666
    /**
667
     * @param type $name
668
     *
669
     * @throws \Exception
670
     *
671
     * @return string
672
     */
673
    public static function getTimezoneByName($name)
674
    {
675
        try {
676
            if ($name) {
677
                $timezone = \App\Model\Common\Timezone::where('name', $name)->first();
678
                if ($timezone) {
679
                    $timezone = $timezone->id;
680
                } else {
681
                    $timezone = '114';
682
                }
683
            } else {
684
                $timezone = '114';
685
            }
686
687
            return $timezone;
688
        } catch (\Exception $ex) {
689
            throw new \Exception($ex->getMessage());
690
        }
691
    }
692
693
    /**
694
     * @param type $code
695
     *
696
     * @throws \Exception
697
     *
698
     * @return type
699
     */
700
    public static function getStateByCode($code)
701
    {
702
        try {
703
            $result = ['id' => '', 'name' => ''];
704
705
            $subregion = \App\Model\Common\State::where('state_subdivision_code', $code)->first();
706
            if ($subregion) {
707
                $result = ['id' => $subregion->state_subdivision_code,
708
709
                     'name' => $subregion->state_subdivision_name, ];
710
            }
711
712
            return $result;
713
        } catch (\Exception $ex) {
714
            throw new \Exception($ex->getMessage());
715
        }
716
    }
717
718
    /**
719
     * @param type $id
720
     *
721
     * @throws \Exception
722
     *
723
     * @return type
724
     */
725
    public static function getStateNameById($id)
726
    {
727
        try {
728
            $name = '';
729
            $subregion = \App\Model\Common\State::where('state_subdivision_id', $id)->first();
730
            if ($subregion) {
731
                $name = $subregion->state_subdivision_name;
732
            }
733
734
            return $name;
735
        } catch (\Exception $ex) {
736
            throw new \Exception($ex->getMessage());
737
        }
738
    }
739
740
    /**
741
     * @param type $productid
742
     * @param type $price
743
     * @param type $cart
744
     * @param type $cart1
745
     * @param type $shop
746
     *
747
     * @return type
748
     */
749
    public static function calculateTax($productid, $price, $cart = 1, $cart1 = 0, $shop = 0)
750
    {
751
        try {
752
            $template_controller = new TemplateController();
753
            $result = $template_controller->checkTax($productid, $price, $cart, $cart1, $shop);
754
755
            $result = self::rounding($result);
756
757
            return $result;
758
        } catch (\Exception $ex) {
759
            return redirect()->back()->with('fails', $ex->getMessage());
760
        }
761
    }
762
763
    /**
764
     * @param type $rate
765
     * @param type $price
766
     *
767
     * @return type
768
     */
769
    public static function taxValue($rate, $price)
770
    {
771
        try {
772
            $result = '';
773
            if ($rate) {
1 ignored issue
show
introduced by
$rate is of type App\Http\Controllers\Front\type, thus it always evaluated to true.
Loading history...
774
                $rate = str_replace('%', '', $rate);
775
                $tax = $price * ($rate / 100);
776
                $result = $tax;
777
778
                $result = self::rounding($result);
779
            }
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
940
            return $currency;
941
        } catch (\Exception $ex) {
942
            throw new \Exception($ex->getMessage());
943
        }
944
    }
945
946
    public function getCurrency($userid)
947
    {
948
        $user = new \App\User();
949
        $currency = $user->find($userid)->currency;
950
        if ($currency == 'USD' || $currency == '1') {
951
            $currency = 'USD';
952
        } else {
953
            $currency = 'INR';
954
        }
955
956
        return $currency;
957
    }
958
959
    /**
960
     * @throws \Exception
961
     */
962
    public function removePlanSession()
963
    {
964
        try {
965
            if (Session::has('plan')) {
966
                Session::forget('plan');
967
            }
968
        } catch (\Exception $ex) {
969
            throw new \Exception($ex->getMessage());
970
        }
971
    }
972
973
    /**
974
     * @throws \Exception
975
     *
976
     * @return bool
977
     */
978
    public function checkPlanSession()
979
    {
980
        try {
981
            if (Session::has('plan')) {
982
                return true;
983
            }
984
985
            return false;
986
        } catch (\Exception $ex) {
987
            throw new \Exception($ex->getMessage());
988
        }
989
    }
990
991
    /**
992
     * @param type $productid
993
     * @param type $userid
994
     * @param type $planid
995
     *
996
     * @return type
997
     */
998
    public function cost($productid, $userid = '', $planid = '')
999
    {
1000
        try {
1001
            $cost = $this->planCost($productid, $userid, $planid);
1002
            if ($cost == 0) {
1003
                $cost = $this->productCost($productid, $userid);
1004
            }
1005
1006
            return self::rounding($cost);
1007
        } catch (\Exception $ex) {
1008
            // throw new \Exception($ex->getMessage());
1009
        }
1010
    }
1011
1012
    /**
1013
     * @param type $productid
1014
     * @param type $userid
1015
     *
1016
     * @throws \Exception
1017
     *
1018
     * @return type
1019
     */
1020
    public function productCost($productid, $userid = '')
1021
    {
1022
        try {
1023
            $sales = 0;
1024
            $currency = $this->currency($userid);
1025
            $product = $this->product->find($productid);
1026
            $price = $product->price()->where('currency', $currency)->first();
1027
            if ($price) {
1028
                $sales = $price->sales_price;
1029
                if ($sales == 0) {
1030
                    $sales = $price->price;
1031
                }
1032
            }
1033
            //}
1034
1035
            return $sales;
1036
        } catch (\Exception $ex) {
1037
            throw new \Exception($ex->getMessage());
1038
        }
1039
    }
1040
1041
    /**
1042
     * @param type $productid
1043
     * @param type $userid
1044
     * @param type $planid
1045
     *
1046
     * @throws \Exception
1047
     *
1048
     * @return type
1049
     */
1050
    public function planCost($productid, $userid, $planid = '')
1051
    {
1052
        try {
1053
            $cost = 0;
1054
            $subscription = $this->allowSubscription($productid);
1055
            if ($this->checkPlanSession() === true) {
1056
                $planid = Session::get('plan');
1057
            }
1058
1059
            if ($subscription === true) {
1060
                $plan = new \App\Model\Payment\Plan();
1061
                $plan = $plan->where('id', $planid)->where('product', $productid)->first();
1062
1063
                if ($plan) {
1064
                    $currency = $this->currency($userid);
1065
                    $price = $plan->planPrice()
1066
                                    ->where('currency', $currency)
1067
                                    ->first()
1068
                            ->add_price;
1069
                    $days = $plan->days;
1070
                    if ($days >= '365'){
1071
                    $months = $days / 30 / 12;
1072
                    }else{
1073
                      $months = $days /30;
1074
                    }
1075
                   
1076
                    $cost = round($months) * $price;
1077
                }
1078
            }
1079
1080
            return $cost;
1081
        } catch (\Exception $ex) {
1082
            throw new \Exception($ex->getMessage());
1083
        }
1084
    }
1085
1086
    /**
1087
     * @throws \Exception
1088
     *
1089
     * @return bool
1090
     */
1091
    public function checkCurrencySession()
1092
    {
1093
        try {
1094
            if (Session::has('currency')) {
1095
                return true;
1096
            }
1097
1098
            return false;
1099
        } catch (\Exception $ex) {
1100
            throw new \Exception($ex->getMessage());
1101
        }
1102
    }
1103
1104
    /**
1105
     * @param type $productid
1106
     *
1107
     * @throws \Exception
1108
     *
1109
     * @return bool
1110
     */
1111
    public function allowSubscription($productid)
1112
    {
1113
        try {
1114
            $reponse = false;
1115
            $product = $this->product->find($productid);
1116
            if ($product) {
1117
                if ($product->subscription == 1) {
1118
                    $reponse = true;
1119
                }
1120
            }
1121
1122
            return $reponse;
1123
        } catch (\Exception $ex) {
1124
            throw new \Exception($ex->getMessage());
1125
        }
1126
    }
1127
}
1128