Completed
Push — development ( 55bb16...2dbf65 )
by Ashutosh
09:53
created

CartController::getStateNameById()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
nc 3
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\Plan;
9
use App\Model\Payment\PlanPrice;
10
use App\Model\Payment\Tax;
11
use App\Model\Payment\TaxByState;
12
use App\Model\Payment\TaxClass;
13
use App\Model\Payment\TaxOption;
14
use App\Model\Payment\TaxProductRelation;
15
use App\Model\Product\Product;
16
use Bugsnag;
17
use Cart;
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
        // $this->middleware('Inatall');
60
        // $this->middleware('admin');
61
    }
62
63
    public function productList(Request $request)
64
    {
65
        try {
66
            $cont = new \App\Http\Controllers\Front\GetPageTemplateController();
67
            $location = $cont->getLocation();
68
        } catch (\Exception $ex) {
69
            $location = false;
70
            $error = $ex->getMessage();
71
        }
72
73
        $country = \App\Http\Controllers\Front\CartController::findCountryByGeoip($location['countryCode']);
74
        $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($location['countryCode']);
75
        $states = \App\Model\Common\State::pluck('state_subdivision_name', 'state_subdivision_code')->toArray();
76
        $state_code = $location['countryCode'].'-'.$location['region'];
77
        $state = \App\Http\Controllers\Front\CartController::getStateByCode($state_code);
78
        $mobile_code = \App\Http\Controllers\Front\CartController::getMobileCodeByIso($location['countryCode']);
79
        $currency = $cont->getCurrency($location);
80
81
        \Session::put('currency', $currency);
82
        if (!\Session::has('currency')) {
83
            \Session::put('currency', 'INR');
84
        }
85
86
        try {
87
            $page_controller = new PageController();
88
89
            return $page_controller->cart();
90
        } catch (\Exception $ex) {
91
            return redirect()->back()->with('fails', $ex->getMessage());
92
        }
93
    }
94
95
    public function cart(Request $request)
96
    {
97
        try {
98
            $plan = '';
99
            if ($request->has('subscription')) {
100
                $plan = $request->get('subscription');
101
                Session::put('plan', $plan);
102
            }
103
            $id = $request->input('id');
104
105
            if (!array_key_exists($id, Cart::getContent())) {
106
                $items = $this->addProduct($id);
107
                Cart::add($items);
108
            }
109
110
            return redirect('show/cart');
111
        } catch (\Exception $ex) {
112
            return redirect()->back()->with('fails', $ex->getMessage());
113
        }
114
    }
115
116
    public function showCart()
117
    {
118
        try {
119
            $cartCollection = [];
120
            $items = (\Session::get('items'));
121
122
            $currency = 'INR';
123
            $cart_currency = 'INR';
124
            $attributes = [];
125
            $cartCollection = $this->getCartCollection($items);
126
            foreach ($cartCollection as $item) {
127
                $attributes[] = $item->attributes;
128
                $cart_currency = $attributes[0]['currency'];
129
                $currency = $attributes[0]['currency'];
130
                if (\Auth::user()) {
131
                    $cart_currency = $attributes[0]['currency'];
132
                    $user_currency = \Auth::user()->currency;
133
                    $user_country = \Auth::user()->country;
134
                    $user_state = \Auth::user()->state;
135
                    $currency = 'INR';
136
                    if ($user_currency == 1 || $user_currency == 'USD') {
137
                        $currency = 'USD';
138
                    }
139
                    if ($cart_currency != $currency) {
140
                        $id = $item->id;
141
                        Cart::remove($id);
142
                        $items = $this->addProduct($id);
143
144
                        Cart::add($items);
145
                    }
146
                }
147
            }
148
149
            return view('themes.default1.front.cart', compact('cartCollection', 'attributes'));
150
        } catch (\Exception $ex) {
151
            return redirect()->back()->with('fails', $ex->getMessage());
152
        }
153
    }
154
155
    public function checkTax($productid)
156
    {
157
        try {
158
            $tax_condition = array();
159
            $tax_attribute = array();
160
            $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
161
            $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
0 ignored issues
show
Comprehensibility Best Practice introduced by
$taxCondition was never initialized. Although not strictly required by PHP, it is generally a good practice to add $taxCondition = array(); before regardless.
Loading history...
162
                'name'   => 'null',
163
                'type'   => 'tax',
164
                'target' => 'item',
165
                'value'  => '0%',
166
            ]);
167
            $cont = new \App\Http\Controllers\Front\GetPageTemplateController();
168
            $location = $cont->getLocation();
169
170
            $country = $this->findCountryByGeoip($location['countryCode']);
171
            $states = $this->findStateByRegionId($location['countryCode']);
172
            $states = \App\Model\Common\State::pluck('state_subdivision_name', 'state_subdivision_code')->toArray();
173
            $state_code = $location['countryCode'].'-'.$location['region'];
174
            $state = $this->getStateByCode($state_code);
175
            $mobile_code = $this->getMobileCodeByIso($location['countryCode']);
176
            $country_iso = $location['countryCode'];
177
            $geoip_country = '';
178
            $geoip_state = '';
179
            if (\Auth::user()) {
180
                $geoip_country = \Auth::user()->country;
181
                $geoip_state = \Auth::user()->state;
182
            }
183
            if ($geoip_country == '') {
184
                $geoip_country = \App\Http\Controllers\Front\CartController::findCountryByGeoip($country_iso);
185
            }
186
            $geoip_state_array = \App\Http\Controllers\Front\CartController::getStateByCode($state_code);
187
            if ($geoip_state == '') {
188
                if (array_key_exists('id', $geoip_state_array)) {
189
                    $geoip_state = $geoip_state_array['id'];
190
                }
191
            }
192
193
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
194
                $tax_rule = $this->tax_option->findOrFail(1);
195
                $shop = $tax_rule->shop_inclusive;
196
                $cart = $tax_rule->cart_inclusive;
197
                $tax_enable = $this->tax_option->findOrFail(1)->tax_enable;
198
                //Check the state of user for calculating GST(cgst,igst,utgst,sgst)
199
                $user_state = TaxByState::where('state_code', $geoip_state)->first();
200
                $origin_state = $this->setting->first()->state; //Get the State of origin
201
                $tax_class_id = TaxProductRelation::where('product_id', $productid)->pluck('tax_class_id')->toArray();
202
203
                if ($tax_class_id) {//If the product is allowed for tax (Check in tax_product relation table)
204
                   if ($tax_enable == 1) {//If GST is Enabled
205
206
                             $state_code = '';
207
                       $c_gst = '';
208
                       $s_gst = '';
209
                       $i_gst = '';
210
                       $ut_gst = '';
211
                       $value = '';
212
                       $rate = '';
213
                       $status = 1;
214
215
                       if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
216
217
                           $c_gst = $user_state->c_gst;
218
                           $s_gst = $user_state->s_gst;
219
                           $i_gst = $user_state->i_gst;
220
                           $ut_gst = $user_state->ut_gst;
221
                           $state_code = $user_state->state_code;
222
                           if ($state_code == $origin_state) {//If user and origin state are same
223
224
                               $taxClassId = TaxClass::where('name', 'Intra State GST')->pluck('id')->toArray(); //Get the class Id  of state
225
                               if ($taxClassId) {
226
                                   $taxes = $this->getTaxByPriority($taxClassId);
227
                                   $value = $this->getValueForSameState($productid, $c_gst, $s_gst, $taxClassId, $taxes);
228
229
                                   if ($value == '') {
230
                                       $status = 0;
231
                                   }
232
                               } else {
233
                                   $taxes = [0];
234
                               }
235
                           } elseif ($state_code != $origin_state && $ut_gst == 'NULL') {//If user is from other state
236
237
                               $taxClassId = TaxClass::where('name', 'Inter State GST')->pluck('id')->toArray(); //Get the class Id  of state
238
                               if ($taxClassId) {
239
                                   $taxes = $this->getTaxByPriority($taxClassId);
240
                                   $value = $this->getValueForOtherState($productid, $i_gst, $taxClassId, $taxes);
241
                                   if ($value == '') {
242
                                       $status = 0;
243
                                   }
244
                               } else {
245
                                   $taxes = [0];
246
                               }
247
                           } elseif ($state_code != $origin_state && $ut_gst != 'NULL') {//if user from Union Territory
248
                        $taxClassId = TaxClass::where('name', 'Union Territory GST')->pluck('id')->toArray(); //Get the class Id  of state
249
                        if ($taxClassId) {
250
                            $taxes = $this->getTaxByPriority($taxClassId);
251
                            $value = $this->getValueForUnionTerritory($productid, $c_gst, $ut_gst, $taxClassId, $taxes);
252
                            if ($value == '') {
253
                                $status = 0;
254
                            }
255
                        } else {
256
                            $taxes = [0];
257
                        }
258
                           }
259
                       } else {//If user from other Country
260
                           $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
261
262
                           if ($taxClassId) { //if state equals the user State or country equals user country
263
264
                               $taxes = $this->getTaxByPriority($taxClassId);
265
                               $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
266
                               if ($value == '') {
267
                                   $status = 0;
268
                               }
269
                               $rate = $value;
270
                           } else {//if Tax is selected for Any Country Any State
271
                               $taxClassId = Tax::where('country', '')->where('state', 'Any State')->pluck('tax_classes_id')->first();
272
                               if ($taxClassId) {
273
                                   $taxes = $this->getTaxByPriority($taxClassId);
274
                                   $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
275
                                   if ($value == '') {
276
                                       $status = 0;
277
                                   }
278
                                   $rate = $value;
279
                               } else {
280
                                   $taxes = [0];
281
                               }
282
                           }
283
                       }
284
                       foreach ($taxes as $key => $tax) {
285
286
                                    //All the da a attribute that is sent to the checkout Page if tax_compound=0
287
                           if ($taxes[0]) {
288
                               $tax_attribute[$key] = ['name' => $tax->name, 'c_gst'=>$c_gst, 's_gst'=>$s_gst, 'i_gst'=>$i_gst, 'ut_gst'=>$ut_gst, 'state'=>$state_code, 'origin_state'=>$origin_state, 'tax_enable'=>$tax_enable, 'rate'=>$value, 'status'=>$status];
289
290
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
291
292
                                            'name'   => 'no compound',
293
                                            'type'   => 'tax',
294
                                            'target' => 'item',
295
                                            'value'  => $value,
296
                                          ]);
297
                           } else {
298
                               $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
299
                               $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
300
                                           'name'   => 'null',
301
                                           'type'   => 'tax',
302
                                           'target' => 'item',
303
                                           'value'  => '0%',
304
                                         ]);
305
                           }
306
                       }
307
                   } elseif ($tax_enable == 0) {//If Tax enable is 0
308
                       $status = 1;
309
                       if ($this->tax_option->findOrFail(1)->tax_enable == 0) {
310
                           $taxClassId = Tax::where('country', '')->where('state', 'Any State')->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
311
                           if ($taxClassId) {
312
                               $taxes = $this->getTaxByPriority($taxClassId);
313
                               $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
314
                               if ($value == 0) {
315
                                   $status = 0;
316
                               }
317
                               $rate = $value;
318
                               foreach ($taxes as $key => $tax) {
319
                                   $tax_attribute[$key] = ['name' => $tax->name, 'rate' => $value, 'tax_enable'=>0, 'status' => $status];
320
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
321
322
                                            'name'   => $tax->name,
323
                                            'type'   => 'tax',
324
                                            'target' => 'item',
325
                                            'value'  => $value,
326
                                        ]);
327
                               }
328
                           } else {//In case of other country when tax is available and tax is not enabled(Applicable when Global Tax class for any country and state is not there)
329
                               $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
330
                               if ($taxClassId) { //if state equals the user State
331
                                   $taxes = $this->getTaxByPriority($taxClassId);
332
                                   $value = $this->getValueForOthers($productid, $taxClassId, $taxes);
333
                                   if ($value == '') {
334
                                       $status = 0;
335
                                   }
336
                                   $rate = $value;
337
                               }
338
                               foreach ($taxes as $key => $tax) {
339
                                   $tax_attribute[$key] = ['name' => $tax->name, 'rate' => $value, 'tax_enable'=>0, 'status' => $status];
340
                                   $taxCondition[$key] = new \Darryldecode\Cart\CartCondition([
341
342
                                            'name'   => $tax->name,
343
                                            'type'   => 'tax',
344
                                            'target' => 'item',
345
                                            'value'  => $value,
346
                                        ]);
347
                               }
348
                           }
349
                       }
350
                   }
351
                } else {
352
                    $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
353
                    $taxCondition[0] = new \Darryldecode\Cart\CartCondition([
354
                'name'   => 'null',
355
                'type'   => 'tax',
356
                'target' => 'item',
357
                'value'  => '0%',
358
            ]);
359
                }
360
            }
361
362
            $currency_attribute = $this->addCurrencyAttributes($productid);
363
364
            return ['conditions' => $taxCondition, 'attributes' => ['tax' => $tax_attribute, 'currency' => $currency_attribute]];
365
        } catch (\Exception $ex) {
366
            Bugsnag::notifyException($ex);
367
368
            throw new \Exception('Can not check the tax');
369
        }
370
    }
371
372
373
374
   
375
376
    /**
377
     * @param type $price
378
     *
379
     * @throws \Exception
380
     *
381
     * @return type
382
     */
383
    public static function rounding($price)
384
    {
385
        try {
386
            $tax_rule = new \App\Model\Payment\TaxOption();
387
            $rule = $tax_rule->findOrFail(1);
388
            $rounding = $rule->rounding;
389
            if ($rounding == 1) {
390
                // $price = str_replace(',', '', $price);
391
392
                return round($price);
393
            } else {
394
                return $price;
395
            }
396
        } catch (\Exception $ex) {
397
            Bugsnag::notifyException($ex);
398
        }
399
    }
400
401
    /**
402
     * @return type
403
     */
404
    public function contactUs()
405
    {
406
        try {
407
            return view('themes.default1.front.contact');
408
        } catch (\Exception $ex) {
409
            return redirect()->back()->with('fails', $ex->getMessage());
410
        }
411
    }
412
413
    /**
414
     * @param type $code
415
     *
416
     * @throws \Exception
417
     *
418
     * @return type
419
     */
420
    public static function getCountryByCode($code)
421
    {
422
        try {
423
            $country = \App\Model\Common\Country::where('country_code_char2', $code)->first();
424
            if ($country) {
425
                return $country->country_name;
426
            }
427
        } catch (\Exception $ex) {
428
            throw new \Exception($ex->getMessage());
429
        }
430
    }
431
432
    /**
433
     * @param type $name
434
     *
435
     * @throws \Exception
436
     *
437
     * @return string
438
     */
439
    public static function getTimezoneByName($name)
440
    {
441
        try {
442
            if ($name) {
443
                $timezone = \App\Model\Common\Timezone::where('name', $name)->first();
444
                if ($timezone) {
445
                    $timezone = $timezone->id;
446
                } else {
447
                    $timezone = '114';
448
                }
449
            } else {
450
                $timezone = '114';
451
            }
452
453
            return $timezone;
454
        } catch (\Exception $ex) {
455
            throw new \Exception($ex->getMessage());
456
        }
457
    }
458
459
    /**
460
     * @param type $code
461
     *
462
     * @throws \Exception
463
     *
464
     * @return type
465
     */
466
    public static function getStateByCode($code)
467
    {
468
        try {
469
            $result = ['id' => '', 'name' => ''];
470
            $subregion = \App\Model\Common\State::where('state_subdivision_code', $code)->first();
471
            if ($subregion) {
472
                $result = ['id' => $subregion->state_subdivision_code, 'name' => $subregion->state_subdivision_name];
473
                //return ['id' => $subregion->state_subdivision_code, 'name' => $subregion->state_subdivision_name];
474
            }
475
476
            return $result;
477
        } catch (\Exception $ex) {
478
            throw new \Exception($ex->getMessage());
479
        }
480
    }
481
482
    /**
483
     * @param type $id
484
     *
485
     * @throws \Exception
486
     *
487
     * @return type
488
     */
489
    public static function getStateNameById($id)
490
    {
491
        try {
492
            $name = '';
493
            $subregion = \App\Model\Common\State::where('state_subdivision_id', $id)->first();
494
            if ($subregion) {
495
                $name = $subregion->state_subdivision_name;
496
            }
497
498
            return $name;
499
        } catch (\Exception $ex) {
500
            throw new \Exception($ex->getMessage());
501
        }
502
    }
503
504
    /**
505
     * @param type $productid
506
     * @param type $price
507
     * @param type $cart
508
     * @param type $cart1
509
     * @param type $shop
510
     *
511
     * @return type
512
     */
513
    public static function calculateTax($productid, $price, $cart = 1, $cart1 = 0, $shop = 0)
514
    {
515
        try {
516
            $template_controller = new TemplateController();
517
            $result = $template_controller->checkTax($productid, $price, $cart, $cart1, $shop);
518
519
            $result = self::rounding($result);
520
521
            return $result;
522
        } catch (\Exception $ex) {
523
            return redirect()->back()->with('fails', $ex->getMessage());
524
        }
525
    }
526
527
    /**
528
     * @param type $rate
529
     * @param type $price
530
     *
531
     * @return type
532
     */
533
    public static function taxValue($rate, $price)
534
    {
535
        try {
536
            $rate = str_replace('%', '', $rate);
537
            $tax = $price * ($rate / 100);
538
            $result = $tax;
539
540
            $result = self::rounding($result);
541
542
            return $result;
543
        } catch (\Exception $ex) {
544
            return redirect()->back()->with('fails', $ex->getMessage());
545
        }
546
    }
547
548
   
549
    /**
550
     * @param type $productid
551
     * @param type $userid
552
     * @param type $planid
553
     *
554
     * @return type
555
     */
556
    public function cost($productid, $userid = '', $planid = '')
557
    {
558
        try {
559
            $cost = $this->planCost($productid, $userid, $planid);
560
            if ($cost == 0) {
561
                $cost = $this->productCost($productid, $userid);
562
            }
563
564
            return self::rounding($cost);
565
        } catch (\Exception $ex) {
566
            // throw new \Exception($ex->getMessage());
567
        }
568
    }
569
570
    /**
571
     * @param type $productid
572
     * @param type $userid
573
     *
574
     * @throws \Exception
575
     *
576
     * @return type
577
     */
578
    public function productCost($productid, $userid = '')
579
    {
580
        try {
581
            $sales = 0;
582
            $currency = $this->currency($userid);
583
            $product = $this->product->find($productid);
584
585
            // $price = $product->price()->where('currency', $currency)->first();
586
            $plan_id = Plan::where('product', $productid)->pluck('id')->first();
587
            $price = PlanPrice::where('plan_id', $plan_id)->where('currency', $currency)->pluck('add_price')->first();
588
            if ($price) {
589
                $sales = $price;
590
                // if ($sales == 0) {
591
                //     $sales = $price->price;
592
                // }
593
            }
594
            //}
595
596
            return $sales;
597
        } catch (\Exception $ex) {
598
            throw new \Exception($ex->getMessage());
599
        }
600
    }
601
602
    /**
603
     * @param type $productid
604
     * @param type $userid
605
     * @param type $planid
606
     *
607
     * @throws \Exception
608
     *
609
     * @return type
610
     */
611
    public function planCost($productid, $userid, $planid = '')
612
    {
613
        try {
614
            $cost = 0;
615
            $subscription = $this->allowSubscription($productid);
616
            if ($this->checkPlanSession() === true) {
617
                $planid = Session::get('plan');
618
            }
619
620
            if ($subscription === true) {
621
                $plan = new \App\Model\Payment\Plan();
622
                $plan = $plan->where('id', $planid)->where('product', $productid)->first();
623
                $items = (\Session::get('items'));
624
625
                if ($plan) {
626
                    $currency = $this->currency($userid);
627
                    $price = $plan->planPrice()
628
                                    ->where('currency', $currency)
629
                                    ->first()
630
                            ->add_price;
631
                    $days = $plan->days;
632
                    $months = $days / 30 / 12;
633
                    if ($items != null) {
634
                        $cost = $items[$productid]['price'];
635
                    } else {
636
                        $cost = round($months) * $price;
637
                    }
638
                }
639
            }
640
641
            return $cost;
642
        } catch (\Exception $ex) {
643
            throw new \Exception($ex->getMessage());
644
        }
645
    }
646
647
   
648
    /**
649
     * @throws \Exception
650
     *
651
     * @return bool
652
     */
653
    public function checkCurrencySession()
654
    {
655
        try {
656
            if (Session::has('currency')) {
657
                return true;
658
            }
659
660
            return false;
661
        } catch (\Exception $ex) {
662
            throw new \Exception($ex->getMessage());
663
        }
664
    }
665
}
666