Completed
Push — development ( c6edbc...615590 )
by Ashutosh
09:59
created

InvoiceController::show()   A

Complexity

Conditions 2
Paths 6

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
cc 2
nc 6
nop 1
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
    /*
205
    *Edit Invoice Total.
206
    */
207
    public function invoiceTotalChange(Request $request)
208
    {
209
        $total = $request->input('total');
210
        $number = $request->input('number');
211
        $invoiceId = Invoice::where('number', $number)->value('id');
212
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
213
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
214
    }
215
216
    public function sendmailClientAgent($userid, $invoiceid)
217
    {
218
        try {
219
            $agent = \Input::get('agent');
220
            $client = \Input::get('client');
221
            if ($agent == 1) {
222
                $id = \Auth::user()->id;
223
                $this->sendMail($id, $invoiceid);
224
            }
225
            if ($client == 1) {
226
                $this->sendMail($userid, $invoiceid);
227
            }
228
        } catch (\Exception $ex) {
229
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
230
            app('log')->info($ex->getMessage());
231
            Bugsnag::notifyException($ex);
232
233
            throw new \Exception($ex->getMessage());
234
        }
235
    }
236
237
    /**
238
     * Generate invoice.
239
     *
240
     * @throws \Exception
241
     */
242
    public function generateInvoice()
243
    {
244
        try {
245
            // dd(\Cart::getContent());
246
            $tax_rule = new \App\Model\Payment\TaxOption();
247
            $rule = $tax_rule->findOrFail(1);
248
            $rounding = $rule->rounding;
249
250
            $user_id = \Auth::user()->id;
251
            if (\Auth::user()->currency == 'INR') {
252
                $grand_total = \Cart::getSubTotal();
253
            } else {
254
                foreach (\Cart::getContent() as $cart) {
255
256
                    // $grand_total = $cart->price;
257
                    $grand_total = \Cart::getSubTotal();
258
                }
259
            }
260
            // dd($grand_total);
261
262
            $number = rand(11111111, 99999999);
263
            $date = \Carbon\Carbon::now();
264
265
            if ($rounding == 1) {
266
                $grand_total = round($grand_total);
267
            }
268
            $content = \Cart::getContent();
269
            $attributes = [];
270
            foreach ($content as $key => $item) {
271
                $attributes[] = $item->attributes;
272
            }
273
274
            $symbol = $attributes[0]['currency'][0]['code'];
275
            //dd($symbol);
276
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
277
278
            foreach (\Cart::getContent() as $cart) {
279
                $this->createInvoiceItems($invoice->id, $cart);
280
            }
281
            //$this->sendMail($user_id, $invoice->id);
282
            return $invoice;
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('Can not Generate Invoice');
289
        }
290
    }
291
292
    public function createInvoiceItems($invoiceid, $cart)
293
    {
294
        try {
295
            $planid = 0;
296
            $product_name = $cart->name;
297
            $regular_price = $cart->price;
298
            $quantity = $cart->quantity;
299
            $domain = $this->domain($cart->id);
300
            $cart_cont = new \App\Http\Controllers\Front\CartController();
301
            if ($cart_cont->checkPlanSession() === true) {
302
                $planid = \Session::get('plan');
303
            }
304
            $user_currency = \Auth::user()->currency;
305
            $subtotal = $this->getSubtotal($user_currency, $cart);
306
307
            $tax_name = '';
308
            $tax_percentage = '';
309
310
            foreach ($cart->attributes['tax'] as $tax) {
311
                $tax_name .= $tax['name'].',';
312
                $tax_percentage .= $tax['rate'].',';
313
            }
314
315
            $invoiceItem = $this->invoiceItem->create([
316
                'invoice_id'     => $invoiceid,
317
                'product_name'   => $product_name,
318
                'regular_price'  => $regular_price,
319
                'quantity'       => $quantity,
320
                'tax_name'       => $tax_name,
321
                'tax_percentage' => $tax_percentage,
322
                'subtotal'       => $subtotal,
323
                'domain'         => $domain,
324
                'plan_id'        => $planid,
325
            ]);
326
327
            return $invoiceItem;
328
        } catch (\Exception $ex) {
329
            Bugsnag::notifyException($ex);
330
331
            throw new \Exception('Can not create Invoice Items');
332
        }
333
    }
334
335
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
336
    {
337
        try {
338
            if ($amount > 0) {
339
                if ($userid == '') {
340
                    $userid = \Auth::user()->id;
341
                }
342
                if ($amount == 0) {
343
                    $payment_status = 'success';
344
                }
345
                $this->payment->create([
346
                    'parent_id'      => $parent_id,
347
                    'invoice_id'     => $invoiceid,
348
                    'user_id'        => $userid,
349
                    'amount'         => $amount,
350
                    'payment_method' => $payment_method,
351
                    'payment_status' => $payment_status,
352
                ]);
353
                $this->updateInvoice($invoiceid);
354
            }
355
        } catch (\Exception $ex) {
356
            Bugsnag::notifyException($ex);
357
358
            throw new \Exception($ex->getMessage());
359
        }
360
    }
361
362
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price, $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
363
    {
364
        try {
365
            $discount = '';
366
            $mode = '';
367
            $product = $this->product->findOrFail($productid);
368
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
369
            $price = $this->getPrice($price, $price_model);
370
            $subtotal = $qty * $price;
371
            //dd($subtotal);
372
            if ($code) {
373
                $subtotal = $this->checkCode($code, $productid, $currency);
374
                $mode = 'coupon';
375
                $discount = $price - $subtotal;
376
            }
377
            $userid = \Auth::user()->id;
378
            if (\Auth::user()->role == 'user') {
379
                $tax = $this->checkTax($product->id, $userid);
380
                $tax_name = '';
381
                $tax_rate = '';
382
                if (!empty($tax)) {
383
384
                    //dd($value);
385
                    $tax_name = $tax[0];
386
                    $tax_rate = $tax[1];
387
                }
388
            }
389
390
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
391
392
            $domain = $this->domain($productid);
393
            $items = $this->invoiceItem->create([
394
                'invoice_id'     => $invoiceid,
395
                'product_name'   => $product->name,
396
                'regular_price'  => $price,
397
                'quantity'       => $qty,
398
                'discount'       => $discount,
399
                'discount_mode'  => $mode,
400
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
401
                'tax_name'       => $tax_name,
402
                'tax_percentage' => $tax_rate,
403
                'domain'         => $domain,
404
                'plan_id'        => $planid,
405
            ]);
406
407
            return $items;
408
        } catch (\Exception $ex) {
409
            Bugsnag::notifyException($ex);
410
411
            return redirect()->back()->with('fails', $ex->getMessage());
412
        }
413
    }
414
415
    public function findCostAfterDiscount($promoid, $productid, $currency)
416
    {
417
        try {
418
            $promotion = $this->promotion->findOrFail($promoid);
419
            $product = $this->product->findOrFail($productid);
420
            $promotion_type = $promotion->type;
421
            $promotion_value = $promotion->value;
422
            $planId = Plan::where('product', $productid)->pluck('id')->first();
423
            // dd($planId);
424
            $product_price = PlanPrice::where('plan_id', $planId)->where('currency', $currency)->pluck('add_price')->first();
425
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
426
427
            return $updated_price;
428
        } catch (\Exception $ex) {
429
            Bugsnag::notifyException($ex);
430
431
            throw new \Exception(\Lang::get('message.find-discount-error'));
432
        }
433
    }
434
435
    public function findCost($type, $value, $price, $productid)
436
    {
437
        switch ($type) {
438
                case 1:
439
                    $percentage = $price * ($value / 100);
440
441
                     return $price - $percentage;
442
                case 2:
443
                    return $price - $value;
444
                case 3:
445
                    return $value;
446
                case 4:
447
                    return 0;
448
            }
449
    }
450
451
    public function checkCode($code, $productid, $currency)
452
    {
453
        try {
454
            if ($code != '') {
455
                $promo = $this->promotion->where('code', $code)->first();
456
                //check promotion code is valid
457
                if (!$promo) {
458
                    throw new \Exception(\Lang::get('message.no-such-code'));
459
                }
460
                $relation = $promo->relation()->get();
461
                //check the relation between code and product
462
                if (count($relation) == 0) {
463
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
464
                }
465
                //check the usess
466
                $uses = $this->checkNumberOfUses($code);
467
                //dd($uses);
468
                if ($uses != 'success') {
469
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
470
                }
471
                //check for the expiry date
472
                $expiry = $this->checkExpiry($code);
473
                //dd($expiry);
474
                if ($expiry != 'success') {
475
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
476
                }
477
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
478
479
                return $value;
480
            } else {
481
                $product = $this->product->find($productid);
482
                $plans = Plan::where('product', $product)->pluck('id')->first();
483
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
484
485
                return $price;
486
            }
487
        } catch (\Exception $ex) {
488
            throw new \Exception(\Lang::get('message.check-code-error'));
489
        }
490
    }
491
492
    public function checkExpiry($code = '')
493
    {
494
        try {
495
            if ($code != '') {
496
                $promotion = $this->promotion->where('code', $code)->first();
497
                $start = $promotion->start;
498
                $end = $promotion->expiry;
499
                //dd($end);
500
                $now = \Carbon\Carbon::now();
501
                $getExpiryStatus = $this->getExpiryStatus($start, $end, $now);
502
503
                return $getExpiryStatus;
504
            } else {
505
            }
506
        } catch (\Exception $ex) {
507
            throw new \Exception(\Lang::get('message.check-expiry'));
508
        }
509
    }
510
511
    public function checkTax($productid, $userid)
512
    {
513
        try {
514
            $taxs = [];
515
            $taxs[0] = ['name' => 'null', 'rate' => 0];
516
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
517
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
518
            $product = $this->product->findOrFail($productid);
519
            $cartController = new CartController();
520
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
521
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
522
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
523
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
524
525
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
526
                     ->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
527
                    if ($taxClassId) {
528
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
529
                        $taxs = $rate['taxes'];
530
                        $rate = $rate['rate'];
531
                    } 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)
532
533
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
534
                        if ($taxClassId) { //if state equals the user State
535
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
536
                            $taxs = $rate['taxes'];
537
                            $rate = $rate['rate'];
538
                        }
539
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
540
541
                        return $taxs;
542
                    }
543
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
544
                } else {
545
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
546
                }
547
            }
548
549
            return $taxs;
550
        } catch (\Exception $ex) {
551
            throw new \Exception(\Lang::get('message.check-tax-error'));
552
        }
553
    }
554
555
    public function getRate($productid, $taxs, $userid)
556
    {
557
        $tax_attribute = [];
558
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
559
        $tax_value = '0';
560
561
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
562
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
563
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
564
        $origin_state = $this->setting->first()->state; //Get the State of origin
565
        $cartController = new CartController();
566
567
        $rate = 0;
568
        $name1 = 'CGST';
569
        $name2 = 'SGST';
570
        $name3 = 'IGST';
571
        $name4 = 'UTGST';
572
        $c_gst = 0;
573
        $s_gst = 0;
574
        $i_gst = 0;
575
        $ut_gst = 0;
576
        $state_code = '';
577
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
578
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
579
            $taxes = $tax['taxes'];
580
            $value = $tax['value'];
581
        } else {//If user from other Country
582
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
583
            $taxes = $tax['taxes'];
584
            $value = $tax['value'];
585
            $rate = $tax['rate'];
586
        }
587
588
        foreach ($taxes as $key => $tax) {
589
            if ($taxes[0]) {
590
                $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];
591
592
                $rate = $tax->rate;
593
594
                $tax_value = $value;
595
            } else {
596
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
597
                $tax_value = '0%';
598
            }
599
        }
600
601
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
602
    }
603
604
    /**
605
     * Remove the specified resource from storage.
606
     *
607
     * @param int $id
608
     *
609
     * @return \Response
610
     */
611
    public function destroy(Request $request)
612
    {
613
        try {
614
            $ids = $request->input('select');
615
            if (!empty($ids)) {
616
                foreach ($ids as $id) {
617
                    $invoice = $this->invoice->where('id', $id)->first();
618
                    if ($invoice) {
619
                        $invoice->delete();
620
                    } else {
621
                        echo "<div class='alert alert-danger alert-dismissable'>
622
                    <i class='fa fa-ban'></i>
623
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
624
                    \Lang::get('message.failed').'
625
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
626
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
627
                </div>';
628
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
629
                    }
630
                }
631
                echo "<div class='alert alert-success alert-dismissable'>
632
                    <i class='fa fa-ban'></i>
633
                    <b>"./** @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './** @scrutinizer ignore-type */
634
                    \Lang::get('message.success').'
635
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
636
                        './** @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
637
                </div>';
638
            } else {
639
                echo "<div class='alert alert-danger alert-dismissable'>
640
                    <i class='fa fa-ban'></i>
641
                    <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

641
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
642
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
643
                        './** @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
644
                </div>';
645
                //echo \Lang::get('message.select-a-row');
646
            }
647
        } catch (\Exception $e) {
648
            echo "<div class='alert alert-danger alert-dismissable'>
649
                    <i class='fa fa-ban'></i>
650
                    <b>"./** @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
651
                    /** @scrutinizer ignore-type */\Lang::get('message.failed').'
652
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
653
                        '.$e->getMessage().'
654
                </div>';
655
        }
656
    }
657
658
    public function updateInvoice($invoiceid)
659
    {
660
        try {
661
            $invoice = $this->invoice->findOrFail($invoiceid);
662
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
663
            $total = array_sum($payment);
664
            if ($total < $invoice->grand_total) {
665
                $invoice->status = 'pending';
666
            }
667
            if ($total >= $invoice->grand_total) {
668
                $invoice->status = 'success';
669
            }
670
            if ($total > $invoice->grand_total) {
671
                $user = $invoice->user()->first();
672
                $balance = $total - $invoice->grand_total;
673
                $user->debit = $balance;
674
                $user->save();
675
            }
676
677
            $invoice->save();
678
        } catch (\Exception $ex) {
679
            Bugsnag::notifyException($ex);
680
681
            throw new \Exception($ex->getMessage());
682
        }
683
    }
684
685
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
686
    {
687
        try {
688
            $invoice = $this->invoice->find($invoiceid);
689
            $invoice_status = 'pending';
690
691
            $payment = $this->payment->create([
692
                'invoice_id'     => $invoiceid,
693
                'user_id'        => $invoice->user_id,
694
                'amount'         => $amount,
695
                'payment_method' => $payment_method,
696
                'payment_status' => $payment_status,
697
                'created_at'     => $payment_date,
698
            ]);
699
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
700
            $total_paid = array_sum($all_payments);
701
            if ($total_paid >= $invoice->grand_total) {
702
                $invoice_status = 'success';
703
            }
704
            if ($invoice) {
705
                $invoice->status = $invoice_status;
706
                $invoice->save();
707
            }
708
709
            return $payment;
710
        } catch (\Exception $ex) {
711
            Bugsnag::notifyException($ex);
712
713
            throw new \Exception($ex->getMessage());
714
        }
715
    }
716
717
    public function pdf(Request $request)
718
    {
719
        try {
720
            $id = $request->input('invoiceid');
721
            if (!$id) {
722
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
723
            }
724
            $invoice = $this->invoice->where('id', $id)->first();
725
            if (!$invoice) {
726
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
727
            }
728
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
729
            if ($invoiceItems->count() == 0) {
730
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
731
            }
732
            $user = $this->user->find($invoice->user_id);
733
            if (!$user) {
734
                return redirect()->back()->with('fails', 'No User');
735
            }
736
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
737
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
738
739
            return $pdf->download($user->first_name.'-invoice.pdf');
740
        } catch (\Exception $ex) {
741
            Bugsnag::notifyException($ex);
742
743
            return redirect()->back()->with('fails', $ex->getMessage());
744
        }
745
    }
746
747
    public function getExpiryStatus($start, $end, $now)
748
    {
749
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
750
        if ($whenDateNotSet) {
751
            return $whenDateNotSet;
752
        }
753
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
754
        if ($whenStartDateSet) {
755
            return $whenStartDateSet;
756
        }
757
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
758
        if ($whenEndDateSet) {
759
            return $whenEndDateSet;
760
        }
761
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
762
        if ($whenBothAreSet) {
763
            return $whenBothAreSet;
764
        }
765
    }
766
767
    public function payment(Request $request)
768
    {
769
        try {
770
            if ($request->has('invoiceid')) {
771
                $invoice_id = $request->input('invoiceid');
772
                $invoice = $this->invoice->find($invoice_id);
773
                //dd($invoice);
774
                $invoice_status = '';
775
                $payment_status = '';
776
                $payment_method = '';
777
                $domain = '';
778
                if ($invoice) {
779
                    $invoice_status = $invoice->status;
780
                    $items = $invoice->invoiceItem()->first();
781
                    if ($items) {
782
                        $domain = $items->domain;
783
                    }
784
                }
785
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
786
                if ($payment) {
787
                    $payment_status = $payment->payment_status;
788
                    $payment_method = $payment->payment_method;
789
                }
790
791
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
792
            }
793
794
            return redirect()->back();
795
        } catch (\Exception $ex) {
796
            Bugsnag::notifyException($ex);
797
798
            return redirect()->back()->with('fails', $ex->getMessage());
799
        }
800
    }
801
802
    public function postRazorpayPayment($invoiceid, $grand_total)
803
    {
804
        try {
805
            $payment_method = 'Razorpay';
806
            $payment_status = 'success';
807
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
808
            $amount = $grand_total;
809
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
810
811
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
812
        } catch (\Exception $ex) {
813
            return redirect()->back()->with('fails', $ex->getMessage());
814
        }
815
    }
816
817
    public function sendMail($userid, $invoiceid)
818
    {
819
        try {
820
            $invoice = $this->invoice->find($invoiceid);
821
            $number = $invoice->number;
822
            $total = $invoice->grand_total;
823
824
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
825
        } catch (\Exception $ex) {
826
            Bugsnag::notifyException($ex);
827
828
            throw new \Exception($ex->getMessage());
829
        }
830
    }
831
832
    public function deletePayment(Request $request)
833
    {
834
        try {
835
            $ids = $request->input('select');
836
            if (!empty($ids)) {
837
                foreach ($ids as $id) {
838
                    $payment = $this->payment->where('id', $id)->first();
839
                    if ($payment) {
840
                        $invoice = $this->invoice->find($payment->invoice_id);
841
                        if ($invoice) {
842
                            $invoice->status = 'pending';
843
                            $invoice->save();
844
                        }
845
                        $payment->delete();
846
                    } else {
847
                        echo "<div class='alert alert-danger alert-dismissable'>
848
                    <i class='fa fa-ban'></i>
849
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
850
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
851
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
852
                </div>';
853
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
854
                    }
855
                }
856
                echo "<div class='alert alert-success alert-dismissable'>
857
                    <i class='fa fa-ban'></i>
858
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
859
                    \Lang::get('message.success').'
860
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
861
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
862
                </div>';
863
            } else {
864
                echo "<div class='alert alert-danger alert-dismissable'>
865
                    <i class='fa fa-ban'></i>
866
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
867
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
868
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
869
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
870
                </div>';
871
                //echo \Lang::get('message.select-a-row');
872
            }
873
        } catch (\Exception $e) {
874
            Bugsnag::notifyException($e);
875
            echo "<div class='alert alert-danger alert-dismissable'>
876
                    <i class='fa fa-ban'></i>
877
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
878
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
879
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
880
                        '.$e->getMessage().'
881
                </div>';
882
        }
883
    }
884
}
885