Completed
Pull Request — development (#635)
by Ashutosh
09:42
created

CartController::taxValue()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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