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

InvoiceController::sendMail()   A

Complexity

Conditions 2
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 2
nc 3
nop 2
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Front\CartController;
6
use App\Model\Common\Setting;
7
use App\Model\Common\Template;
8
use App\Model\Order\Invoice;
9
use App\Model\Order\InvoiceItem;
10
use App\Model\Order\Order;
11
use App\Model\Order\Payment;
12
use App\Model\Payment\Currency;
13
use App\Model\Payment\Plan;
14
use App\Model\Payment\PlanPrice;
15
use App\Model\Payment\Promotion;
16
use App\Model\Payment\Tax;
17
use App\Model\Payment\TaxByState;
18
use App\Model\Payment\TaxOption;
19
use App\Model\Product\Price;
20
use App\Model\Product\Product;
21
use App\User;
22
use Bugsnag;
23
use Illuminate\Http\Request;
24
use Input;
25
use Log;
26
27
class InvoiceController extends TaxRatesAndCodeExpiryController
28
{
29
    public $invoice;
30
    public $invoiceItem;
31
    public $user;
32
    public $template;
33
    public $setting;
34
    public $payment;
35
    public $product;
36
    public $price;
37
    public $promotion;
38
    public $currency;
39
    public $tax;
40
    public $tax_option;
41
    public $order;
42
    public $cartController;
43
44
    public function __construct()
45
    {
46
        $this->middleware('auth');
47
        $this->middleware('admin', ['except' => ['pdf']]);
48
49
        $invoice = new Invoice();
50
        $this->invoice = $invoice;
51
52
        $invoiceItem = new InvoiceItem();
53
        $this->invoiceItem = $invoiceItem;
54
55
        $user = new User();
56
        $this->user = $user;
57
58
        $template = new Template();
59
        $this->template = $template;
60
61
        $seting = new Setting();
62
        $this->setting = $seting;
63
64
        $payment = new Payment();
65
        $this->payment = $payment;
66
67
        $product = new Product();
68
        $this->product = $product;
69
70
        $price = new Price();
71
        $this->price = $price;
72
73
        $promotion = new Promotion();
74
        $this->promotion = $promotion;
75
76
        $currency = new Currency();
77
        $this->currency = $currency;
78
79
        $tax = new Tax();
80
        $this->tax = $tax;
81
82
        $tax_option = new TaxOption();
83
        $this->tax_option = $tax_option;
84
85
        $order = new Order();
86
        $this->order = $order;
87
88
        $tax_by_state = new TaxByState();
89
        $this->tax_by_state = new $tax_by_state();
90
91
        $cartController = new CartController();
92
        $this->cartController = $cartController;
93
    }
94
95
    public function index()
96
    {
97
        try {
98
            //dd($this->invoice->get());
99
            return view('themes.default1.invoice.index');
100
        } catch (\Exception $ex) {
101
            Bugsnag::notifyException($ex);
102
103
            return redirect()->back()->with('fails', $ex->getMessage());
104
        }
105
    }
106
107
    public function getInvoices()
108
    {
109
        $invoice = \DB::table('invoices');
110
        // $new_invoice = $invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at');
111
112
        return \DataTables::of($invoice->get())
113
                        ->addColumn('checkbox', function ($model) {
114
                            return "<input type='checkbox' class='invoice_checkbox' value=".$model->id.' name=select[] id=check>';
115
                        })
116
                        ->addColumn('user_id', function ($model) {
117
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
118
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
119
                            $id = $this->user->where('id', $model->user_id)->first()->id;
120
121
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
122
                        })
123
                         ->addColumn('number', function ($model) {
124
                             return ucfirst($model->number);
125
                         })
126
127
                        ->addColumn('date', function ($model) {
128
                            $date = date_create($model->created_at);
129
130
                            return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
131
                        })
132
                         ->addColumn('grand_total', function ($model) {
133
                             return ucfirst($model->number);
134
                         })
135
                          ->addColumn('status', function ($model) {
136
                              return ucfirst($model->status);
137
                          })
138
139
                        ->addColumn('action', function ($model) {
140
                            $action = '';
141
142
                            $check = $this->checkExecution($model->id);
143
                            if ($check == false) {
144
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-tasks' style='color:white;'> </i>&nbsp;&nbsp; Execute Order</a>";
145
                            }
146
147
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' style='color:white;'> </i>&nbsp;&nbsp;View</a>"
148
                                    ."   $action";
149
                        })
150
151
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
152
                        ->make(true);
153
    }
154
155
    public function show(Request $request)
156
    {
157
        try {
158
            $id = $request->input('invoiceid');
159
            $invoice = $this->invoice->where('id', $id)->first();
160
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
161
            $user = $this->user->find($invoice->user_id);
162
163
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
164
        } catch (\Exception $ex) {
165
            Bugsnag::notifyException($ex);
166
167
            return redirect()->back()->with('fails', $ex->getMessage());
168
        }
169
    }
170
171
    /**
172
     * not in use case.
173
     *
174
     * @param Request $request
175
     *
176
     * @return type
177
     */
178
    public function generateById(Request $request)
179
    {
180
        try {
181
            $clientid = $request->input('clientid');
182
            if ($clientid) {
183
                $user = new User();
184
                $user = $user->where('id', $clientid)->first();
185
                if (!$user) {
186
                    return redirect()->back()->with('fails', 'Invalid user');
187
                }
188
            } else {
189
                $user = '';
190
            }
191
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
192
            $currency = $this->currency->pluck('name', 'code')->toArray();
193
194
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
195
        } catch (\Exception $ex) {
196
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
197
            app('log')->info($ex->getMessage());
198
            Bugsnag::notifyException($ex);
199
200
            return redirect()->back()->with('fails', $ex->getMessage());
201
        }
202
    }
203
204
    public function invoiceGenerateByForm(Request $request, $user_id = '')
205
    {
206
        $qty = 1;
207
208
        try {
209
            if ($user_id == '') {
210
                $user_id = \Request::input('user');
211
            }
212
            $productid = $request->input('product');
213
            $code = $request->input('code');
214
            $total = $request->input('price');
215
            $plan = $request->input('plan');
216
            $description = $request->input('description');
217
            if ($request->has('domain')) {
218
                $domain = $request->input('domain');
219
                $this->setDomain($productid, $domain);
220
            }
221
            $controller = new \App\Http\Controllers\Front\CartController();
222
            $currency = $controller->currency($user_id);
223
            $number = rand(11111111, 99999999);
224
            $date = \Carbon\Carbon::now();
225
            $product = $this->product->find($productid);
226
            $cost = $controller->cost($productid, $user_id, $plan);
227
            if ($cost != $total) {
228
                $grand_total = $total;
229
            }
230
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
231
            $grand_total = $qty * $grand_total;
232
233
            $tax = $this->checkTax($product->id, $user_id);
234
            $tax_name = '';
235
            $tax_rate = '';
236
            if (!empty($tax)) {
237
                $tax_name = $tax[0];
238
                $tax_rate = $tax[1];
239
            }
240
241
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
242
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
243
244
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'currency' => $currency, 'status' => 'pending', 'description' => $description]);
245
246
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid, $code, $total, $currency, $qty, $plan, $user_id, $tax_name, $tax_rate);
247
            // dd($items);
248
            $result = $this->getMessage($items, $user_id);
249
        } catch (\Exception $ex) {
250
            app('log')->useDailyFiles(storage_path().'/laravel.log');
251
            app('log')->info($ex->getMessage());
252
            Bugsnag::notifyException($ex);
253
            $result = ['fails' => $ex->getMessage()];
254
        }
255
256
        return response()->json(compact('result'));
257
    }
258
259
    /*
260
    *Edit Invoice Total.
261
    */
262
    public function invoiceTotalChange(Request $request)
263
    {
264
        $total = $request->input('total');
265
        $number = $request->input('number');
266
        $invoiceId = Invoice::where('number', $number)->value('id');
267
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
268
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
269
    }
270
271
    public function sendmailClientAgent($userid, $invoiceid)
272
    {
273
        try {
274
            $agent = \Input::get('agent');
275
            $client = \Input::get('client');
276
            if ($agent == 1) {
277
                $id = \Auth::user()->id;
278
                $this->sendMail($id, $invoiceid);
279
            }
280
            if ($client == 1) {
281
                $this->sendMail($userid, $invoiceid);
282
            }
283
        } catch (\Exception $ex) {
284
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
285
            app('log')->info($ex->getMessage());
286
            Bugsnag::notifyException($ex);
287
288
            throw new \Exception($ex->getMessage());
289
        }
290
    }
291
292
    /**
293
     * Generate invoice.
294
     *
295
     * @throws \Exception
296
     */
297
    public function generateInvoice()
298
    {
299
        try {
300
            // dd(\Cart::getContent());
301
            $tax_rule = new \App\Model\Payment\TaxOption();
302
            $rule = $tax_rule->findOrFail(1);
303
            $rounding = $rule->rounding;
304
305
            $user_id = \Auth::user()->id;
306
            if (\Auth::user()->currency == 'INR') {
307
                $grand_total = \Cart::getSubTotal();
308
            } else {
309
                foreach (\Cart::getContent() as $cart) {
310
311
                    // $grand_total = $cart->price;
312
                    $grand_total = \Cart::getSubTotal();
313
                }
314
            }
315
            // dd($grand_total);
316
317
            $number = rand(11111111, 99999999);
318
            $date = \Carbon\Carbon::now();
319
320
            if ($rounding == 1) {
321
                $grand_total = round($grand_total);
322
            }
323
            $content = \Cart::getContent();
324
            $attributes = [];
325
            foreach ($content as $key => $item) {
326
                $attributes[] = $item->attributes;
327
            }
328
329
            $symbol = $attributes[0]['currency'][0]['code'];
330
            //dd($symbol);
331
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
332
333
            foreach (\Cart::getContent() as $cart) {
334
                $this->createInvoiceItems($invoice->id, $cart);
335
            }
336
            //$this->sendMail($user_id, $invoice->id);
337
            return $invoice;
338
        } catch (\Exception $ex) {
339
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
340
            app('log')->info($ex->getMessage());
341
            Bugsnag::notifyException($ex);
342
343
            throw new \Exception('Can not Generate Invoice');
344
        }
345
    }
346
347
    public function createInvoiceItems($invoiceid, $cart)
348
    {
349
        try {
350
            $planid = 0;
351
            $product_name = $cart->name;
352
            $regular_price = $cart->price;
353
            $quantity = $cart->quantity;
354
            $domain = $this->domain($cart->id);
355
            $cart_cont = new \App\Http\Controllers\Front\CartController();
356
            if ($cart_cont->checkPlanSession() === true) {
357
                $planid = \Session::get('plan');
358
            }
359
            $user_currency = \Auth::user()->currency;
360
            $subtotal = $this->getSubtotal($user_currency, $cart);
361
362
            $tax_name = '';
363
            $tax_percentage = '';
364
365
            foreach ($cart->attributes['tax'] as $tax) {
366
                $tax_name .= $tax['name'].',';
367
                $tax_percentage .= $tax['rate'].',';
368
            }
369
370
            $invoiceItem = $this->invoiceItem->create([
371
                'invoice_id'     => $invoiceid,
372
                'product_name'   => $product_name,
373
                'regular_price'  => $regular_price,
374
                'quantity'       => $quantity,
375
                'tax_name'       => $tax_name,
376
                'tax_percentage' => $tax_percentage,
377
                'subtotal'       => $subtotal,
378
                'domain'         => $domain,
379
                'plan_id'        => $planid,
380
            ]);
381
382
            return $invoiceItem;
383
        } catch (\Exception $ex) {
384
            Bugsnag::notifyException($ex);
385
386
            throw new \Exception('Can not create Invoice Items');
387
        }
388
    }
389
390
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
391
    {
392
        try {
393
            if ($amount > 0) {
394
                if ($userid == '') {
395
                    $userid = \Auth::user()->id;
396
                }
397
                if ($amount == 0) {
398
                    $payment_status = 'success';
399
                }
400
                $this->payment->create([
401
                    'parent_id'      => $parent_id,
402
                    'invoice_id'     => $invoiceid,
403
                    'user_id'        => $userid,
404
                    'amount'         => $amount,
405
                    'payment_method' => $payment_method,
406
                    'payment_status' => $payment_status,
407
                ]);
408
                $this->updateInvoice($invoiceid);
409
            }
410
        } catch (\Exception $ex) {
411
            Bugsnag::notifyException($ex);
412
413
            throw new \Exception($ex->getMessage());
414
        }
415
    }
416
417
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price, $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
418
    {
419
        try {
420
            $discount = '';
421
            $mode = '';
422
            $product = $this->product->findOrFail($productid);
423
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
424
            $price = $this->getPrice($price, $price_model);
425
            $subtotal = $qty * $price;
426
            //dd($subtotal);
427
            if ($code) {
428
                $subtotal = $this->checkCode($code, $productid, $currency);
429
                $mode = 'coupon';
430
                $discount = $price - $subtotal;
431
            }
432
            $userid = \Auth::user()->id;
433
            if (\Auth::user()->role == 'user') {
434
                $tax = $this->checkTax($product->id, $userid);
435
                $tax_name = '';
436
                $tax_rate = '';
437
                if (!empty($tax)) {
438
439
                    //dd($value);
440
                    $tax_name = $tax[0];
441
                    $tax_rate = $tax[1];
442
                }
443
            }
444
445
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
446
447
            $domain = $this->domain($productid);
448
            $items = $this->invoiceItem->create([
449
                'invoice_id'     => $invoiceid,
450
                'product_name'   => $product->name,
451
                'regular_price'  => $price,
452
                'quantity'       => $qty,
453
                'discount'       => $discount,
454
                'discount_mode'  => $mode,
455
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
456
                'tax_name'       => $tax_name,
457
                'tax_percentage' => $tax_rate,
458
                'domain'         => $domain,
459
                'plan_id'        => $planid,
460
            ]);
461
462
            return $items;
463
        } catch (\Exception $ex) {
464
            Bugsnag::notifyException($ex);
465
466
            return redirect()->back()->with('fails', $ex->getMessage());
467
        }
468
    }
469
470
    public function findCostAfterDiscount($promoid, $productid, $currency)
471
    {
472
        try {
473
            $promotion = $this->promotion->findOrFail($promoid);
474
            $product = $this->product->findOrFail($productid);
475
            $promotion_type = $promotion->type;
476
            $promotion_value = $promotion->value;
477
            $planId = Plan::where('product', $productid)->pluck('id')->first();
478
            // dd($planId);
479
            $product_price = PlanPrice::where('plan_id', $planId)->where('currency', $currency)->pluck('add_price')->first();
480
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
481
482
            return $updated_price;
483
        } catch (\Exception $ex) {
484
            Bugsnag::notifyException($ex);
485
486
            throw new \Exception(\Lang::get('message.find-discount-error'));
487
        }
488
    }
489
490
    public function findCost($type, $value, $price, $productid)
491
    {
492
        switch ($type) {
493
                case 1:
494
                    $percentage = $price * ($value / 100);
495
496
                     return $price - $percentage;
497
                case 2:
498
                    return $price - $value;
499
                case 3:
500
                    return $value;
501
                case 4:
502
                    return 0;
503
            }
504
    }
505
506
    public function checkNumberOfUses($code)
507
    {
508
        try {
509
            $promotion = $this->promotion->where('code', $code)->first();
510
            $uses = $promotion->uses;
511
            if ($uses == 0) {
512
                return 'success';
513
            }
514
            $used_number = $this->invoice->where('coupon_code', $code)->count();
515
            if ($uses >= $used_number) {
516
                return 'success';
517
            } else {
518
                return 'fails';
519
            }
520
        } catch (\Exception $ex) {
521
            Bugsnag::notifyException($ex);
522
523
            throw new \Exception(\Lang::get('message.find-cost-error'));
524
        }
525
    }
526
527
    public function checkCode($code, $productid, $currency)
528
    {
529
        try {
530
            if ($code != '') {
531
                $promo = $this->promotion->where('code', $code)->first();
532
                //check promotion code is valid
533
                if (!$promo) {
534
                    throw new \Exception(\Lang::get('message.no-such-code'));
535
                }
536
                $relation = $promo->relation()->get();
537
                //check the relation between code and product
538
                if (count($relation) == 0) {
539
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
540
                }
541
                //check the usess
542
                $uses = $this->checkNumberOfUses($code);
543
                //dd($uses);
544
                if ($uses != 'success') {
545
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
546
                }
547
                //check for the expiry date
548
                $expiry = $this->checkExpiry($code);
549
                //dd($expiry);
550
                if ($expiry != 'success') {
551
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
552
                }
553
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
554
555
                return $value;
556
            } else {
557
                $product = $this->product->find($productid);
558
                $plans = Plan::where('product', $product)->pluck('id')->first();
559
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
560
561
                return $price;
562
            }
563
        } catch (\Exception $ex) {
564
            throw new \Exception(\Lang::get('message.check-code-error'));
565
        }
566
    }
567
568
    public function getPromotionDetails($code)
569
    {
570
        $promo = $this->promotion->where('code', $code)->first();
571
        //check promotion code is valid
572
        if (!$promo) {
573
            throw new \Exception(\Lang::get('message.no-such-code'));
574
        }
575
        $relation = $promo->relation()->get();
576
        //check the relation between code and product
577
        if (count($relation) == 0) {
578
            throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
579
        }
580
        //check the usess
581
        $uses = $this->checkNumberOfUses($code);
582
        //dd($uses);
583
        if ($uses != 'success') {
584
            throw new \Exception(\Lang::get('message.usage-of-code-completed'));
585
        }
586
        //check for the expiry date
587
        $expiry = $this->checkExpiry($code);
588
        //dd($expiry);
589
        if ($expiry != 'success') {
590
            throw new \Exception(\Lang::get('message.usage-of-code-expired'));
591
        }
592
593
        return $promo;
594
    }
595
596
    public function checkExpiry($code = '')
597
    {
598
        try {
599
            if ($code != '') {
600
                $promotion = $this->promotion->where('code', $code)->first();
601
                $start = $promotion->start;
602
                $end = $promotion->expiry;
603
                //dd($end);
604
                $now = \Carbon\Carbon::now();
605
                $getExpiryStatus = $this->getExpiryStatus($start, $end, $now);
606
607
                return $getExpiryStatus;
608
            } else {
609
            }
610
        } catch (\Exception $ex) {
611
            throw new \Exception(\Lang::get('message.check-expiry'));
612
        }
613
    }
614
615
    public function checkTax($productid, $userid)
616
    {
617
        try {
618
            $taxs = [];
619
            $taxs[0] = ['name' => 'null', 'rate' => 0];
620
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
621
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
622
            $product = $this->product->findOrFail($productid);
623
            $cartController = new CartController();
624
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
625
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
626
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
627
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
628
629
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
630
                     ->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
631
                    if ($taxClassId) {
632
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
633
                        $taxs = $rate['taxes'];
634
                        $rate = $rate['rate'];
635
                    } elseif ($geoip_country != 'IN') {//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)
636
637
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
638
                        if ($taxClassId) { //if state equals the user State
639
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
640
                            $taxs = $rate['taxes'];
641
                            $rate = $rate['rate'];
642
                        }
643
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
644
645
                        return $taxs;
646
                    }
647
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
648
                } else {
649
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
650
                }
651
            }
652
653
            return $taxs;
654
        } catch (\Exception $ex) {
655
            throw new \Exception(\Lang::get('message.check-tax-error'));
656
        }
657
    }
658
659
    public function getRate($productid, $taxs, $userid)
660
    {
661
        $tax_attribute = [];
662
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
663
        $tax_value = '0';
664
665
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
666
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
667
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
668
        $origin_state = $this->setting->first()->state; //Get the State of origin
669
        $cartController = new CartController();
670
671
        $rate = 0;
672
        $name1 = 'CGST';
673
        $name2 = 'SGST';
674
        $name3 = 'IGST';
675
        $name4 = 'UTGST';
676
        $c_gst = 0;
677
        $s_gst = 0;
678
        $i_gst = 0;
679
        $ut_gst = 0;
680
        $state_code = '';
681
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
682
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
683
            $taxes = $tax['taxes'];
684
            $value = $tax['value'];
685
        } else {//If user from other Country
686
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
687
            $taxes = $tax['taxes'];
688
            $value = $tax['value'];
689
            $rate = $tax['rate'];
690
        }
691
692
        foreach ($taxes as $key => $tax) {
693
            if ($taxes[0]) {
694
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1, 'name2'=> $name2, 'name3' => $name3, 'name4' => $name4, 'rate' => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst, 'rate3'=>$i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code, 'origin_state'=>$origin_state];
695
696
                $rate = $tax->rate;
697
698
                $tax_value = $value;
699
            } else {
700
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
701
                $tax_value = '0%';
702
            }
703
        }
704
705
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
706
    }
707
708
    
709
710
    /**
711
     * Remove the specified resource from storage.
712
     *
713
     * @param int $id
714
     *
715
     * @return \Response
716
     */
717
    public function destroy(Request $request)
718
    {
719
        try {
720
            $ids = $request->input('select');
721
            if (!empty($ids)) {
722
                foreach ($ids as $id) {
723
                    $invoice = $this->invoice->where('id', $id)->first();
724
                    if ($invoice) {
725
                        $invoice->delete();
726
                    } else {
727
                        echo "<div class='alert alert-danger alert-dismissable'>
728
                    <i class='fa fa-ban'></i>
729
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
730
                    \Lang::get('message.failed').'
731
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
732
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
733
                </div>';
734
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
735
                    }
736
                }
737
                echo "<div class='alert alert-success alert-dismissable'>
738
                    <i class='fa fa-ban'></i>
739
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
740
                    \Lang::get('message.success').'
741
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
742
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
743
                </div>';
744
            } else {
745
                echo "<div class='alert alert-danger alert-dismissable'>
746
                    <i class='fa fa-ban'></i>
747
                    <b>".\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
0 ignored issues
show
Bug introduced by
Are you sure Lang::get('message.alert') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

747
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
748
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
749
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
750
                </div>';
751
                //echo \Lang::get('message.select-a-row');
752
            }
753
        } catch (\Exception $e) {
754
            echo "<div class='alert alert-danger alert-dismissable'>
755
                    <i class='fa fa-ban'></i>
756
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
757
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
758
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
759
                        '.$e->getMessage().'
760
                </div>';
761
        }
762
    }
763
764
765
766
    public function updateInvoice($invoiceid)
767
    {
768
        try {
769
            $invoice = $this->invoice->findOrFail($invoiceid);
770
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
771
            $total = array_sum($payment);
772
            if ($total < $invoice->grand_total) {
773
                $invoice->status = 'pending';
774
            }
775
            if ($total >= $invoice->grand_total) {
776
                $invoice->status = 'success';
777
            }
778
            if ($total > $invoice->grand_total) {
779
                $user = $invoice->user()->first();
780
                $balance = $total - $invoice->grand_total;
781
                $user->debit = $balance;
782
                $user->save();
783
            }
784
785
            $invoice->save();
786
        } catch (\Exception $ex) {
787
            Bugsnag::notifyException($ex);
788
789
            throw new \Exception($ex->getMessage());
790
        }
791
    }
792
793
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
794
    {
795
        try {
796
            $invoice = $this->invoice->find($invoiceid);
797
            $invoice_status = 'pending';
798
799
            $payment = $this->payment->create([
800
                'invoice_id'     => $invoiceid,
801
                'user_id'        => $invoice->user_id,
802
                'amount'         => $amount,
803
                'payment_method' => $payment_method,
804
                'payment_status' => $payment_status,
805
                'created_at'     => $payment_date,
806
            ]);
807
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
808
            $total_paid = array_sum($all_payments);
809
            if ($total_paid >= $invoice->grand_total) {
810
                $invoice_status = 'success';
811
            }
812
            if ($invoice) {
813
                $invoice->status = $invoice_status;
814
                $invoice->save();
815
            }
816
817
            return $payment;
818
        } catch (\Exception $ex) {
819
            Bugsnag::notifyException($ex);
820
821
            throw new \Exception($ex->getMessage());
822
        }
823
    }
824
825
    public function payment(Request $request)
826
    {
827
        try {
828
            if ($request->has('invoiceid')) {
829
                $invoice_id = $request->input('invoiceid');
830
                $invoice = $this->invoice->find($invoice_id);
831
                //dd($invoice);
832
                $invoice_status = '';
833
                $payment_status = '';
834
                $payment_method = '';
835
                $domain = '';
836
                if ($invoice) {
837
                    $invoice_status = $invoice->status;
838
                    $items = $invoice->invoiceItem()->first();
839
                    if ($items) {
840
                        $domain = $items->domain;
841
                    }
842
                }
843
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
844
                if ($payment) {
845
                    $payment_status = $payment->payment_status;
846
                    $payment_method = $payment->payment_method;
847
                }
848
849
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
850
            }
851
852
            return redirect()->back();
853
        } catch (\Exception $ex) {
854
            Bugsnag::notifyException($ex);
855
856
            return redirect()->back()->with('fails', $ex->getMessage());
857
        }
858
    }
859
860
    public function postRazorpayPayment($invoiceid, $grand_total)
861
    {
862
        try {
863
            $payment_method = 'Razorpay';
864
            $payment_status = 'success';
865
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
866
            $amount = $grand_total;
867
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
868
869
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
870
        } catch (\Exception $ex) {
871
            return redirect()->back()->with('fails', $ex->getMessage());
872
        }
873
    }
874
875
    public function sendMail($userid, $invoiceid)
876
    {
877
        try {
878
            $invoice = $this->invoice->find($invoiceid);
879
            $number = $invoice->number;
880
            $total = $invoice->grand_total;
881
882
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
883
        } catch (\Exception $ex) {
884
            Bugsnag::notifyException($ex);
885
886
            throw new \Exception($ex->getMessage());
887
        }
888
    }
889
890
    public function deletePayment(Request $request)
891
    {
892
        try {
893
            $ids = $request->input('select');
894
            if (!empty($ids)) {
895
                foreach ($ids as $id) {
896
                    $payment = $this->payment->where('id', $id)->first();
897
                    if ($payment) {
898
                        $invoice = $this->invoice->find($payment->invoice_id);
899
                        if ($invoice) {
900
                            $invoice->status = 'pending';
901
                            $invoice->save();
902
                        }
903
                        $payment->delete();
904
                    } else {
905
                        echo "<div class='alert alert-danger alert-dismissable'>
906
                    <i class='fa fa-ban'></i>
907
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
908
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
909
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
910
                </div>';
911
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
912
                    }
913
                }
914
                echo "<div class='alert alert-success alert-dismissable'>
915
                    <i class='fa fa-ban'></i>
916
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
917
                    \Lang::get('message.success').'
918
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
919
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
920
                </div>';
921
            } else {
922
                echo "<div class='alert alert-danger alert-dismissable'>
923
                    <i class='fa fa-ban'></i>
924
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
925
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
926
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
927
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
928
                </div>';
929
                //echo \Lang::get('message.select-a-row');
930
            }
931
        } catch (\Exception $e) {
932
            Bugsnag::notifyException($e);
933
            echo "<div class='alert alert-danger alert-dismissable'>
934
                    <i class='fa fa-ban'></i>
935
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
936
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
937
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
938
                        '.$e->getMessage().'
939
                </div>';
940
        }
941
    }
942
943
944
  
945
946
    public function currency($invoiceid)
947
    {
948
        $invoice = $this->invoice->find($invoiceid);
949
        $currency_code = $invoice->currency;
950
        $cur = ' ';
951
        if ($invoice->grand_total == 0) {
952
            return $cur;
953
        }
954
        $currency = $this->currency->where('code', $currency_code)->first();
955
        if ($currency) {
956
            $cur = $currency->symbol;
957
            if (!$cur) {
958
                $cur = $currency->code;
959
            }
960
        }
961
962
        return $cur;
963
    }
964
}
965