Completed
Push — development ( 56ae57...4f43d9 )
by Ashutosh
11:03
created

InvoiceController::whenStartDateSet()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 9.2222
c 0
b 0
f 0
cc 6
nc 3
nop 3
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
    public function pdf(Request $request)
709
    {
710
        try {
711
            $id = $request->input('invoiceid');
712
            if (!$id) {
713
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
714
            }
715
            $invoice = $this->invoice->where('id', $id)->first();
716
            if (!$invoice) {
717
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
718
            }
719
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
720
            if ($invoiceItems->count() == 0) {
721
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
722
            }
723
            $user = $this->user->find($invoice->user_id);
724
            if (!$user) {
725
                return redirect()->back()->with('fails', 'No User');
726
            }
727
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
728
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
729
730
            return $pdf->download($user->first_name.'-invoice.pdf');
731
        } catch (\Exception $ex) {
732
            Bugsnag::notifyException($ex);
733
734
            return redirect()->back()->with('fails', $ex->getMessage());
735
        }
736
    }
737
738
    /**
739
     * Remove the specified resource from storage.
740
     *
741
     * @param int $id
742
     *
743
     * @return \Response
744
     */
745
    public function destroy(Request $request)
746
    {
747
        try {
748
            $ids = $request->input('select');
749
            if (!empty($ids)) {
750
                foreach ($ids as $id) {
751
                    $invoice = $this->invoice->where('id', $id)->first();
752
                    if ($invoice) {
753
                        $invoice->delete();
754
                    } else {
755
                        echo "<div class='alert alert-danger alert-dismissable'>
756
                    <i class='fa fa-ban'></i>
757
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
758
                    \Lang::get('message.failed').'
759
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
760
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
761
                </div>';
762
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
763
                    }
764
                }
765
                echo "<div class='alert alert-success alert-dismissable'>
766
                    <i class='fa fa-ban'></i>
767
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
768
                    \Lang::get('message.success').'
769
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
770
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
771
                </div>';
772
            } else {
773
                echo "<div class='alert alert-danger alert-dismissable'>
774
                    <i class='fa fa-ban'></i>
775
                    <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

775
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
776
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
777
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
778
                </div>';
779
                //echo \Lang::get('message.select-a-row');
780
            }
781
        } catch (\Exception $e) {
782
            echo "<div class='alert alert-danger alert-dismissable'>
783
                    <i class='fa fa-ban'></i>
784
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
785
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
786
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
787
                        '.$e->getMessage().'
788
                </div>';
789
        }
790
    }
791
792
    public function setDomain($productid, $domain)
793
    {
794
        try {
795
            if (\Session::has('domain'.$productid)) {
796
                \Session::forget('domain'.$productid);
797
            }
798
            \Session::put('domain'.$productid, $domain);
799
        } catch (\Exception $ex) {
800
            Bugsnag::notifyException($ex);
801
802
            throw new \Exception($ex->getMessage());
803
        }
804
    }
805
806
    public function domain($id)
807
    {
808
        try {
809
            if (\Session::has('domain'.$id)) {
810
                $domain = \Session::get('domain'.$id);
811
            } else {
812
                $domain = '';
813
            }
814
815
            return $domain;
816
        } catch (\Exception $ex) {
817
            Bugsnag::notifyException($ex);
818
        }
819
    }
820
821
    public function updateInvoice($invoiceid)
822
    {
823
        try {
824
            $invoice = $this->invoice->findOrFail($invoiceid);
825
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
826
            $total = array_sum($payment);
827
            if ($total < $invoice->grand_total) {
828
                $invoice->status = 'pending';
829
            }
830
            if ($total >= $invoice->grand_total) {
831
                $invoice->status = 'success';
832
            }
833
            if ($total > $invoice->grand_total) {
834
                $user = $invoice->user()->first();
835
                $balance = $total - $invoice->grand_total;
836
                $user->debit = $balance;
837
                $user->save();
838
            }
839
840
            $invoice->save();
841
        } catch (\Exception $ex) {
842
            Bugsnag::notifyException($ex);
843
844
            throw new \Exception($ex->getMessage());
845
        }
846
    }
847
848
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
849
    {
850
        try {
851
            $invoice = $this->invoice->find($invoiceid);
852
            $invoice_status = 'pending';
853
854
            $payment = $this->payment->create([
855
                'invoice_id'     => $invoiceid,
856
                'user_id'        => $invoice->user_id,
857
                'amount'         => $amount,
858
                'payment_method' => $payment_method,
859
                'payment_status' => $payment_status,
860
                'created_at'     => $payment_date,
861
            ]);
862
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
863
            $total_paid = array_sum($all_payments);
864
            if ($total_paid >= $invoice->grand_total) {
865
                $invoice_status = 'success';
866
            }
867
            if ($invoice) {
868
                $invoice->status = $invoice_status;
869
                $invoice->save();
870
            }
871
872
            return $payment;
873
        } catch (\Exception $ex) {
874
            Bugsnag::notifyException($ex);
875
876
            throw new \Exception($ex->getMessage());
877
        }
878
    }
879
880
    public function payment(Request $request)
881
    {
882
        try {
883
            if ($request->has('invoiceid')) {
884
                $invoice_id = $request->input('invoiceid');
885
                $invoice = $this->invoice->find($invoice_id);
886
                //dd($invoice);
887
                $invoice_status = '';
888
                $payment_status = '';
889
                $payment_method = '';
890
                $domain = '';
891
                if ($invoice) {
892
                    $invoice_status = $invoice->status;
893
                    $items = $invoice->invoiceItem()->first();
894
                    if ($items) {
895
                        $domain = $items->domain;
896
                    }
897
                }
898
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
899
                if ($payment) {
900
                    $payment_status = $payment->payment_status;
901
                    $payment_method = $payment->payment_method;
902
                }
903
904
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
905
            }
906
907
            return redirect()->back();
908
        } catch (\Exception $ex) {
909
            Bugsnag::notifyException($ex);
910
911
            return redirect()->back()->with('fails', $ex->getMessage());
912
        }
913
    }
914
915
    public function postPayment($invoiceid, Request $request)
916
    {
917
        $this->validate($request, [
918
            'payment_method' => 'required',
919
            'amount'         => 'required|numeric',
920
            'payment_date'   => 'required|date_format:Y-m-d',
921
        ]);
922
923
        try {
924
            $payment_method = $request->input('payment_method');
925
            $payment_status = 'success';
926
            $payment_date = $request->input('payment_date');
927
            $amount = $request->input('amount');
928
            $payment = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
929
930
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
931
        } catch (\Exception $ex) {
932
            Bugsnag::notifyException($ex);
933
934
            return redirect()->back()->with('fails', $ex->getMessage());
935
        }
936
    }
937
938
    public function postRazorpayPayment($invoiceid, $grand_total)
939
    {
940
        try {
941
            $payment_method = 'Razorpay';
942
            $payment_status = 'success';
943
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
944
            $amount = $grand_total;
945
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
946
947
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
948
        } catch (\Exception $ex) {
949
            return redirect()->back()->with('fails', $ex->getMessage());
950
        }
951
    }
952
953
    public function sendMail($userid, $invoiceid)
954
    {
955
        try {
956
            $invoice = $this->invoice->find($invoiceid);
957
            $number = $invoice->number;
958
            $total = $invoice->grand_total;
959
960
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
961
        } catch (\Exception $ex) {
962
            Bugsnag::notifyException($ex);
963
964
            throw new \Exception($ex->getMessage());
965
        }
966
    }
967
968
    public function deletePayment(Request $request)
969
    {
970
        try {
971
            $ids = $request->input('select');
972
            if (!empty($ids)) {
973
                foreach ($ids as $id) {
974
                    $payment = $this->payment->where('id', $id)->first();
975
                    if ($payment) {
976
                        $invoice = $this->invoice->find($payment->invoice_id);
977
                        if ($invoice) {
978
                            $invoice->status = 'pending';
979
                            $invoice->save();
980
                        }
981
                        $payment->delete();
982
                    } else {
983
                        echo "<div class='alert alert-danger alert-dismissable'>
984
                    <i class='fa fa-ban'></i>
985
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
986
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
987
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
988
                </div>';
989
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
990
                    }
991
                }
992
                echo "<div class='alert alert-success alert-dismissable'>
993
                    <i class='fa fa-ban'></i>
994
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
995
                    \Lang::get('message.success').'
996
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
997
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
998
                </div>';
999
            } else {
1000
                echo "<div class='alert alert-danger alert-dismissable'>
1001
                    <i class='fa fa-ban'></i>
1002
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
1003
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
1004
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
1005
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
1006
                </div>';
1007
                //echo \Lang::get('message.select-a-row');
1008
            }
1009
        } catch (\Exception $e) {
1010
            Bugsnag::notifyException($e);
1011
            echo "<div class='alert alert-danger alert-dismissable'>
1012
                    <i class='fa fa-ban'></i>
1013
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
1014
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
1015
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
1016
                        '.$e->getMessage().'
1017
                </div>';
1018
        }
1019
    }
1020
1021
    public function deleleById($id)
1022
    {
1023
        try {
1024
            $invoice = $this->invoice->find($id);
1025
            if ($invoice) {
1026
                $invoice->delete();
1027
            } else {
1028
                return redirect()->back()->with('fails', 'Can not delete');
1029
            }
1030
1031
            return redirect()->back()->with('success', "Invoice $invoice->number has Deleted Successfully");
1032
        } catch (\Exception $e) {
1033
            Bugsnag::notifyException($e);
1034
1035
            return redirect()->back()->with('fails', $e->getMessage());
1036
        }
1037
    }
1038
1039
    public function paymentDeleleById($id)
1040
    {
1041
        try {
1042
            $invoice_no = '';
1043
            $payment = $this->payment->find($id);
1044
            if ($payment) {
1045
                $invoice_id = $payment->invoice_id;
1046
                $invoice = $this->invoice->find($invoice_id);
1047
                if ($invoice) {
1048
                    $invoice_no = $invoice->number;
1049
                }
1050
                $payment->delete();
1051
            } else {
1052
                return redirect()->back()->with('fails', 'Can not delete');
1053
            }
1054
1055
            return redirect()->back()->with('success', "Payment for invoice no: $invoice_no has Deleted Successfully");
1056
        } catch (\Exception $e) {
1057
            Bugsnag::notifyException($e);
1058
1059
            return redirect()->back()->with('fails', $e->getMessage());
1060
        }
1061
    }
1062
1063
    public function getExpiryStatus($start, $end, $now)
1064
    {
1065
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
1066
        if ($whenDateNotSet) {
1067
            return $whenDateNotSet;
1068
        }
1069
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
1070
        if ($whenStartDateSet) {
1071
            return $whenStartDateSet;
1072
        }
1073
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
1074
        if ($whenEndDateSet) {
1075
            return $whenEndDateSet;
1076
        }
1077
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
1078
        if ($whenBothAreSet) {
1079
            return $whenBothAreSet;
1080
        }
1081
    }
1082
1083
    public function currency($invoiceid)
1084
    {
1085
        $invoice = $this->invoice->find($invoiceid);
1086
        $currency_code = $invoice->currency;
1087
        $cur = ' ';
1088
        if ($invoice->grand_total == 0) {
1089
            return $cur;
1090
        }
1091
        $currency = $this->currency->where('code', $currency_code)->first();
1092
        if ($currency) {
1093
            $cur = $currency->symbol;
1094
            if (!$cur) {
1095
                $cur = $currency->code;
1096
            }
1097
        }
1098
1099
        return $cur;
1100
    }
1101
1102
    
1103
    public function whenDateNotSet($start, $end)
1104
    {
1105
        //both not set, always true
1106
        if (($start == null || $start == '0000-00-00 00:00:00') &&
1107
         ($end == null || $end == '0000-00-00 00:00:00')) {
1108
            return 'success';
1109
        }
1110
    }
1111
1112
    public function whenStartDateSet($start, $end, $now)
1113
    {
1114
        //only starting date set, check the date is less or equel to today
1115
        if (($start != null || $start != '0000-00-00 00:00:00')
1116
         && ($end == null || $end == '0000-00-00 00:00:00')) {
1117
            if ($start <= $now) {
1118
                return 'success';
1119
            }
1120
        }
1121
    }
1122
1123
    public function whenEndDateSet($start, $end, $now)
1124
    {
1125
        //only ending date set, check the date is greater or equel to today
1126
        if (($end != null || $end != '0000-00-00 00:00:00') && ($start == null || $start == '0000-00-00 00:00:00')) {
1127
            if ($end >= $now) {
1128
                return 'success';
1129
            }
1130
        }
1131
    }
1132
1133
    public function whenBothSet($start, $end, $now)
1134
    {
1135
        //both set
1136
        if (($end != null || $start != '0000-00-00 00:00:00') && ($start != null || $start != '0000-00-00 00:00:00')) {
1137
            if ($end >= $now && $start <= $now) {
1138
                return 'success';
1139
            }
1140
        }
1141
    }
1142
}
1143