Completed
Push — development ( fd290a...986f4f )
by Ashutosh
10:00
created

CartController::getCurrency()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
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
                \Cart::add($items);
109
                
110
            }
111
112
            return redirect('show/cart');
113
        } catch (\Exception $ex) {
114
           return redirect()->back()->with('fails', $ex->getMessage());
115
        }
116
    }
117
118
    public function showCart()
119
    {
120
        try {
121
            $currency = 'INR';
122
            $cart_currency = 'INR';
123
            $attributes = [];
124
            $cartCollection = Cart::getContent();
125
            foreach ($cartCollection as $item) {
126
                $attributes[] = $item->attributes;
127
                $cart_currency = $attributes[0]['currency'];
128
                $currency = $attributes[0]['currency'];
129
                if (\Auth::user()) {
130
                    $cart_currency = $attributes[0]['currency'];
131
                    $user_currency = \Auth::user()->currency;
132
                    $user_country = \Auth::user()->country;
133
                    $user_state = \Auth::user()->state;
134
                    $currency = 'INR';
135
                    if ($user_currency == 1 || $user_currency == 'USD') {
136
                        $currency = 'USD';
137
                    }
138
                    if ($cart_currency != $currency) {
139
                        $id = $item->id;
140
                        Cart::remove($id);
141
                        $items = $this->addProduct($id);
142
143
                        Cart::add($items);
144
                        //
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
             // dd($tax_attribute,$taxCondition);
348
            $currency_attribute = $this->addCurrencyAttributes($productid);
349
            return ['conditions' => $taxCondition,
350
            'attributes'         => ['tax' => $tax_attribute,
351
            'currency'                     => $currency_attribute, ], ];
352
        } catch (\Exception $ex) {
353
          Bugsnag::notifyException($ex);
354
          throw new \Exception('Can not check the tax');
355
        }
356
    }
357
358
    /**
359
     *   Get tax value for Same State.
360
     *
361
     * @param type $productid
362
     * @param type $c_gst
363
     * @param type $s_gst
364
     *                        return type
365
     */
366
    public function getValueForSameState($productid, $c_gst, $s_gst, $taxClassId, $taxes)
367
    {
368
        try {
369
            $value = '';
370
            $value = $taxes->toArray()[0]['active'] ?
371
372
                  (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
373
                        $c_gst + $s_gst.'%' : 0) : 0;
374
375
            return $value;
376
        } catch (Exception $ex) {
377
            Bugsnag::notifyException($ex);
378
379
            return redirect()->back()->with('fails', $ex->getMessage());
380
        }
381
    }
382
383
    /**
384
     *   Get tax value for Other States.
385
     *
386
     * @param type $productid
387
     * @param type $i_gst
388
     *                        return type
389
     */
390
    public function getValueForOtherState($productid, $i_gst, $taxClassId, $taxes)
391
    {
392
        $value = '';
393
        $value = $taxes->toArray()[0]['active'] ? //If the Current Class is active
394
              (TaxProductRelation::where('product_id', $productid)->where('tax_class_id', $taxClassId)->count() ?
395
                        $i_gst.'%' : 0) : 0; //IGST
396
397
        return $value;
398
    }
399
400
    /**
401
     *  Get tax value for Union Territory States.
402
     *
403
     * @param type $productid
404
     * @param type $c_gst
405
     * @param type $ut_gst
406
     *                        return type
407
     */
408
    public function getValueForUnionTerritory($productid, $c_gst, $ut_gst, $taxClassId, $taxes)
409
    {
410
        $value = '';
411
        $value = $taxes->toArray()[0]['active'] ?
412
             (TaxProductRelation::where('product_id', $productid)
413
              ->where('tax_class_id', $taxClassId)->count() ? $ut_gst + $c_gst.'%' : 0) : 0;
414
415
        return $value;
416
    }
417
418
    public function otherRate($productid)
419
    {
420
        $otherRate = '';
421
422
        return $otherRate;
423
    }
424
425
    public function getValueForOthers($productid, $taxClassId, $taxes)
426
    {
427
        $otherRate = 0;
428
        $status = $taxes->toArray()[0]['active'];
429
        if ($status && (TaxProductRelation::where('product_id', $productid)
430
          ->where('tax_class_id', $taxClassId)->count() > 0)) {
431
            $otherRate = Tax::where('tax_classes_id', $taxClassId)->first()->rate;
432
        }
433
        $value = $otherRate.'%';
434
435
        return $value;
436
    }
437
438
    public function cartRemove(Request $request)
439
    {
440
        $id = $request->input('id');
441
        Cart::remove($id);
442
443
        return 'success';
444
    }
445
446
    public function addCartBySlug($slug)
447
    {
448
        try {
449
            $sub = '';
450
            if ($slug == 'helpdesk-with-kb-pro-edition') {
451
                $id = 8;
452
                $sub = 13;
453
            }
454
            if ($slug == 'helpdesk-and-kb-community') {
455
                $id = 7;
456
            }
457
            $url = url("pricing?id=$id&subscription=$sub");
458
459
            return \Redirect::to($url);
460
        } catch (\Exception $ex) {
461
            return redirect()->back()->with('fails', $ex->getMessage());
462
        }
463
    }
464
465
    public function reduseQty(Request $request)
466
    {
467
        $id = $request->input('id');
468
        Cart::update($id, [
469
            'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
470
        ]);
471
472
        return 'success';
473
    }
474
475
    public function updateQty(Request $request)
476
    {
477
        $id = $request->input('productid');
478
        $qty = $request->input('qty');
479
        Cart::update($id, [
480
            'quantity' => [
481
                'relative' => false,
482
                'value'    => $qty,
483
            ],
484
        ]);
485
486
        return 'success';
487
    }
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
            return redirect()->back()->with('fails', $ex->getMessage());
551
        }
552
    }
553
554
    /**
555
     * @param type $tax_class_id
556
     *
557
     * @throws \Exception
558
     *
559
     * @return type
560
     */
561
    public function getTaxByPriority($taxClassId)
562
    {
563
        try {
564
            $taxe_relation = $this->tax->where('tax_classes_id', $taxClassId)->get();
565
566
            return $taxe_relation;
567
        } catch (\Exception $ex) {
568
            Bugsnag::notifyException($ex);
569
570
            throw new \Exception('error in get tax priority');
571
        }
572
    }
573
574
    /**
575
     * @param type $price
576
     *
577
     * @throws \Exception
578
     *
579
     * @return type
580
     */
581
    public static function rounding($price)
582
    {
583
        try {
584
            $tax_rule = new \App\Model\Payment\TaxOption();
585
            $rule = $tax_rule->findOrFail(1);
586
            $rounding = $rule->rounding;
587
588
            return $price;
589
        } catch (\Exception $ex) {
590
            Bugsnag::notifyException($ex);
591
            // throw new \Exception('error in get tax priority');
592
        }
593
    }
594
595
    /**
596
     * @return type
597
     */
598
    public function contactUs()
599
    {
600
        try {
601
            return view('themes.default1.front.contact');
602
        } catch (\Exception $ex) {
603
            return redirect()->back()->with('fails', $ex->getMessage());
604
        }
605
    }
606
607
    /**
608
     * @param Request $request
609
     *
610
     * @return type
611
     */
612
    public function postContactUs(Request $request)
613
    {
614
        $this->validate($request, [
615
            'name'    => 'required',
616
            'email'   => 'required|email',
617
            'message' => 'required',
618
        ]);
619
620
        $set = new \App\Model\Common\Setting();
621
        $set = $set->findOrFail(1);
622
623
        try {
624
            $from = $set->email;
625
            $fromname = $set->company;
626
            $toname = '';
627
            $to = '[email protected]';
628
            $data = '';
629
            $data .= 'Name: '.$request->input('name').'<br/s>';
630
            $data .= 'Email: '.$request->input('email').'<br/>';
631
            $data .= 'Message: '.$request->input('message').'<br/>';
632
            $data .= 'Mobile: '.$request->input('Mobile').'<br/>';
633
634
            $subject = 'Faveo billing enquiry';
635
            $this->templateController->Mailing($from, $to, $data, $subject, [], $fromname, $toname);
636
            //$this->templateController->Mailing($from, $to, $data, $subject);
637
            return redirect()->back()->with('success', 'Your message was sent successfully. Thanks.');
638
        } catch (\Exception $ex) {
639
            return redirect()->back()->with('fails', $ex->getMessage());
640
        }
641
    }
642
643
    /**
644
     * @param type $code
645
     *
646
     * @throws \Exception
647
     *
648
     * @return type
649
     */
650
    public static function getCountryByCode($code)
651
    {
652
        try {
653
            $country = \App\Model\Common\Country::where('country_code_char2', $code)->first();
654
            if ($country) {
655
                return $country->nicename;
656
            }
657
        } catch (\Exception $ex) {
658
            throw new \Exception($ex->getMessage());
659
        }
660
    }
661
662
    /**
663
     * @param type $name
664
     *
665
     * @throws \Exception
666
     *
667
     * @return string
668
     */
669
    public static function getTimezoneByName($name)
670
    {
671
        try {
672
            if ($name) {
673
                $timezone = \App\Model\Common\Timezone::where('name', $name)->first();
674
                if ($timezone) {
675
                    $timezone = $timezone->id;
676
                } else {
677
                    $timezone = '114';
678
                }
679
            } else {
680
                $timezone = '114';
681
            }
682
683
            return $timezone;
684
        } catch (\Exception $ex) {
685
            throw new \Exception($ex->getMessage());
686
        }
687
    }
688
689
    /**
690
     * @param type $code
691
     *
692
     * @throws \Exception
693
     *
694
     * @return type
695
     */
696
    public static function getStateByCode($code)
697
    {
698
        try {
699
            $result = ['id' => '', 'name' => ''];
700
701
            $subregion = \App\Model\Common\State::where('state_subdivision_code', $code)->first();
702
            if ($subregion) {
703
                $result = ['id' => $subregion->state_subdivision_code,
704
705
                     'name' => $subregion->state_subdivision_name, ];
706
            }
707
708
            return $result;
709
        } catch (\Exception $ex) {
710
            throw new \Exception($ex->getMessage());
711
        }
712
    }
713
714
    /**
715
     * @param type $id
716
     *
717
     * @throws \Exception
718
     *
719
     * @return type
720
     */
721
    public static function getStateNameById($id)
722
    {
723
        try {
724
            $name = '';
725
            $subregion = \App\Model\Common\State::where('state_subdivision_id', $id)->first();
726
            if ($subregion) {
727
                $name = $subregion->state_subdivision_name;
728
            }
729
730
            return $name;
731
        } catch (\Exception $ex) {
732
            throw new \Exception($ex->getMessage());
733
        }
734
    }
735
736
    /**
737
     * @param type $productid
738
     * @param type $price
739
     * @param type $cart
740
     * @param type $cart1
741
     * @param type $shop
742
     *
743
     * @return type
744
     */
745
    public static function calculateTax($productid, $price, $cart = 1, $cart1 = 0, $shop = 0)
746
    {
747
        try {
748
            $template_controller = new TemplateController();
749
            $result = $template_controller->checkTax($productid, $price, $cart, $cart1, $shop);
750
751
            $result = self::rounding($result);
752
753
            return $result;
754
        } catch (\Exception $ex) {
755
            return redirect()->back()->with('fails', $ex->getMessage());
756
        }
757
    }
758
759
    /**
760
     * @param type $rate
761
     * @param type $price
762
     *
763
     * @return type
764
     */
765
    public static function taxValue($rate, $price)
766
    {
767
        try {
768
            $result = '';
769
            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...
770
                $rate = str_replace('%', '', $rate);
771
                $tax = intval($price )* ($rate / 100);
772
                $result = $tax;
773
                 
774
                $result = self::rounding($result);
775
            }
776
777
            return $result;
778
        } catch (\Exception $ex) {
779
            return redirect()->back()->with('fails', $ex->getMessage());
780
        }
781
    }
782
783
    /**
784
     * @return type
785
     */
786
    public static function addons()
787
    {
788
        try {
789
            $items = Cart::getContent();
790
            $cart_productids = [];
791
            if (count($items) > 0) {
792
                foreach ($items as $key => $item) {
793
                    $cart_productids[] = $key;
794
                }
795
            }
796
            $_this = new self();
797
            $products = $_this->products($cart_productids);
798
799
            return $products;
800
        } catch (\Exception $ex) {
801
            return redirect()->back()->with('fails', $ex->getMessage());
802
        }
803
    }
804
805
    /**
806
     * @param type $ids
807
     *
808
     * @throws \Exception
809
     *
810
     * @return type
811
     */
812
    public function products($ids)
813
    {
814
        $parents_string = [];
815
        $parent = [];
816
        $productid = [];
817
818
        try {
819
            $parents = $this->product
820
                    ->whereNotNull('parent')
821
                    ->where('parent', '!=', 0)
822
                    ->where('category', 'addon')
823
                    ->pluck('parent', 'id')
824
                    ->toArray();
825
            foreach ($parents as $key => $parent) {
826
                if (is_array($parent)) {
827
                    $parent = implode(',', $parent);
828
                }
829
                $parents_string[$key] = $parent;
830
            }
831
            if (count($parents_string) > 0) {
832
                foreach ($parents_string as $key => $value) {
833
                    if (strpos($value, ',') !== false) {
834
                        $value = explode(',', $value);
835
                    }
836
                    $parent[$key] = $value;
837
                }
838
            }
839
840
            foreach ($parent as $key => $id) {
841
                if (in_array($id, $ids)) {
842
                    $productid[] = $key;
843
                }
844
                if (is_array($id)) {
845
                    foreach ($id as $i) {
846
                        if (in_array($i, $ids)) {
847
                            $productid[] = $key;
848
                        }
849
                    }
850
                }
851
            }
852
            $parent_products = $this->getProductById($productid);
853
854
            return $parent_products;
855
        } catch (\Exception $ex) {
856
            Bugsnag::notifyException($ex);
857
858
            throw new \Exception($ex->getMessage());
859
        }
860
    }
861
862
    /**
863
     * @param type $ids
864
     *
865
     * @throws \Exception
866
     *
867
     * @return type
868
     */
869
    public function getProductById($ids)
870
    {
871
        try {
872
            $products = [];
873
            if (count($ids) > 0) {
874
                $products = $this->product
875
                        ->whereIn('id', $ids)
876
                        ->get();
877
            }
878
879
            return $products;
880
        } catch (\Exception $ex) {
881
            dd($ex);
882
883
            throw new \Exception($ex->getMessage());
884
        }
885
    }
886
887
888
889
    /**
890
     * @param type $userid
891
     *
892
     * @throws \Exception
893
     *
894
     * @return string
895
     */
896
    public function currency($userid = '')
897
    {
898
        try {
899
            $currency = 'INR';
900
            if ($this->checkCurrencySession() === true) {
901
                $currency = Session::get('currency');
902
            }
903
904
            if (\Auth::user()) {
905
                $currency = \Auth::user()->currency;
906
                if ($currency == 'USD' || $currency == '1') {
907
                    $currency = 'USD';
908
                }
909
            }
910
            if ($userid != '') {
911
                $currency = $this->getCurrency($userid);
912
            }
913
914
            return $currency;
915
        } catch (\Exception $ex) {
916
            throw new \Exception($ex->getMessage());
917
        }
918
    }
919
920
    public function getCurrency($userid)
921
    {
922
        $user = new \App\User();
923
        $currency = $user->find($userid)->currency;
924
        if ($currency == 'USD' || $currency == '1') {
925
            $currency = 'USD';
926
        } else {
927
            $currency = 'INR';
928
        }
929
930
        return $currency;
931
    }
932
933
934
935
    /**
936
     * @param type $productid
937
     * @param type $userid
938
     * @param type $planid
939
     *
940
     * @return type
941
     */
942
    public function cost($productid, $userid = '', $planid = '')
943
    {
944
        try {
945
            $cost = $this->planCost($productid, $userid, $planid);
946
            if ($cost == 0) {
947
                $cost = $this->productCost($productid, $userid);
948
            }
949
950
            return self::rounding($cost);
951
        } catch (\Exception $ex) {
952
            // throw new \Exception($ex->getMessage());
953
        }
954
    }
955
956
    /**
957
     * @param type $productid
958
     * @param type $userid
959
     *
960
     * @throws \Exception
961
     *
962
     * @return type
963
     */
964
    public function productCost($productid, $userid = '')
965
    {
966
        try {
967
            $sales = 0;
968
            $currency = $this->currency($userid);
969
            $product = $this->product->find($productid);
970
            $price = $product->price()->where('currency', $currency)->first();
971
            if ($price) {
972
                $sales = $price->sales_price;
973
                if ($sales == 0) {
974
                    $sales = $price->price;
975
                }
976
            }
977
            //}
978
979
            return $sales;
980
        } catch (\Exception $ex) {
981
            throw new \Exception($ex->getMessage());
982
        }
983
    }
984
985
    /**
986
     * @param type $productid
987
     * @param type $userid
988
     * @param type $planid
989
     *
990
     * @throws \Exception
991
     *
992
     * @return type
993
     */
994
    public function planCost($productid, $userid, $planid = '')
995
    {
996
        try {
997
            $cost = 0;
998
            if ($this->checkPlanSession() === true) {
999
                $planid = Session::get('plan');
1000
            }
1001
1002
            $plan = new \App\Model\Payment\Plan();
1003
            $plan = $plan->where('id', $planid)->where('product', $productid)->first();
1004
1005
            if ($plan) {
1006
                $currency = $this->currency($userid);
1007
                $price = $plan->planPrice()
1008
                                    ->where('currency', $currency)
1009
                                    ->first()
1010
                            ->add_price;
1011
                $days = $plan->days;
1012
                if ($days >= '365') {
1013
                    $months = $days / 30 / 12;
1014
                } else {
1015
                    $months = $days / 30;
1016
                }
1017
                $price = intval($price);
1018
                $cost = round($months) * $price;
1019
            }
1020
1021
            return $cost;
1022
        } catch (\Exception $ex) {
1023
            throw new \Exception($ex->getMessage());
1024
        }
1025
    }
1026
1027
    /**
1028
     * @throws \Exception
1029
     *
1030
     * @return bool
1031
     */
1032
    public function checkCurrencySession()
1033
    {
1034
        try {
1035
            if (Session::has('currency')) {
1036
                return true;
1037
            }
1038
1039
            return false;
1040
        } catch (\Exception $ex) {
1041
            throw new \Exception($ex->getMessage());
1042
        }
1043
    }
1044
1045
    /**
1046
     * @param type $productid
1047
     *
1048
     * @throws \Exception
1049
     *
1050
     * @return bool
1051
     */
1052
    public function allowSubscription($productid)
1053
    {
1054
        try {
1055
            $reponse = false;
1056
            $product = $this->product->find($productid);
1057
            if ($product) {
1058
                if ($product->subscription == 1) {
1059
                    $reponse = true;
1060
                }
1061
            }
1062
1063
            return $reponse;
1064
        } catch (\Exception $ex) {
1065
            throw new \Exception($ex->getMessage());
1066
        }
1067
    }
1068
}
1069