Completed
Push — development ( 50bb76...10afda )
by Ashutosh
08:23
created

InvoiceController::createInvoiceItemsByAdmin()   A

Complexity

Conditions 5
Paths 38

Size

Total Lines 50
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 50
rs 9.0168
c 0
b 0
f 0
cc 5
nc 38
nop 10

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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
416
417
    public function checkCode($code, $productid, $currency)
418
    {
419
        try {
420
            if ($code != '') {
421
                $promo = $this->promotion->where('code', $code)->first();
422
                //check promotion code is valid
423
                if (!$promo) {
424
                    throw new \Exception(\Lang::get('message.no-such-code'));
425
                }
426
                $relation = $promo->relation()->get();
427
                //check the relation between code and product
428
                if (count($relation) == 0) {
429
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
430
                }
431
                //check the usess
432
                $uses = $this->checkNumberOfUses($code);
433
                //dd($uses);
434
                if ($uses != 'success') {
435
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
436
                }
437
                //check for the expiry date
438
                $expiry = $this->checkExpiry($code);
439
                //dd($expiry);
440
                if ($expiry != 'success') {
441
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
442
                }
443
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
444
445
                return $value;
446
            } else {
447
                $product = $this->product->find($productid);
448
                $plans = Plan::where('product', $product)->pluck('id')->first();
449
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
450
451
                return $price;
452
            }
453
        } catch (\Exception $ex) {
454
            throw new \Exception(\Lang::get('message.check-code-error'));
455
        }
456
    }
457
458
 
459
460
    public function checkTax($productid, $userid)
461
    {
462
        try {
463
            $taxs = [];
464
            $taxs[0] = ['name' => 'null', 'rate' => 0];
465
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
466
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
467
            $product = $this->product->findOrFail($productid);
468
            $cartController = new CartController();
469
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
470
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
471
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
472
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
473
474
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
475
                     ->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
476
                    if ($taxClassId) {
477
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
478
                        $taxs = $rate['taxes'];
479
                        $rate = $rate['rate'];
480
                    } 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)
481
482
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
483
                        if ($taxClassId) { //if state equals the user State
484
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
485
                            $taxs = $rate['taxes'];
486
                            $rate = $rate['rate'];
487
                        }
488
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
489
490
                        return $taxs;
491
                    }
492
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
493
                } else {
494
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
495
                }
496
            }
497
498
            return $taxs;
499
        } catch (\Exception $ex) {
500
            throw new \Exception(\Lang::get('message.check-tax-error'));
501
        }
502
    }
503
504
    public function getRate($productid, $taxs, $userid)
505
    {
506
        $tax_attribute = [];
507
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
508
        $tax_value = '0';
509
510
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
511
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
512
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
513
        $origin_state = $this->setting->first()->state; //Get the State of origin
514
        $cartController = new CartController();
515
516
        $rate = 0;
517
        $name1 = 'CGST';
518
        $name2 = 'SGST';
519
        $name3 = 'IGST';
520
        $name4 = 'UTGST';
521
        $c_gst = 0;
522
        $s_gst = 0;
523
        $i_gst = 0;
524
        $ut_gst = 0;
525
        $state_code = '';
526
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
527
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
528
            $taxes = $tax['taxes'];
529
            $value = $tax['value'];
530
        } else {//If user from other Country
531
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
532
            $taxes = $tax['taxes'];
533
            $value = $tax['value'];
534
            $rate = $tax['rate'];
535
        }
536
537
        foreach ($taxes as $key => $tax) {
538
            if ($taxes[0]) {
539
                $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];
540
541
                $rate = $tax->rate;
542
543
                $tax_value = $value;
544
            } else {
545
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
546
                $tax_value = '0%';
547
            }
548
        }
549
550
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
551
    }
552
553
    /**
554
     * Remove the specified resource from storage.
555
     *
556
     * @param int $id
557
     *
558
     * @return \Response
559
     */
560
    public function destroy(Request $request)
561
    {
562
        try {
563
            $ids = $request->input('select');
564
            if (!empty($ids)) {
565
                foreach ($ids as $id) {
566
                    $invoice = $this->invoice->where('id', $id)->first();
567
                    if ($invoice) {
568
                        $invoice->delete();
569
                    } else {
570
                        echo "<div class='alert alert-danger alert-dismissable'>
571
                    <i class='fa fa-ban'></i>
572
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
573
                    \Lang::get('message.failed').'
574
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
575
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
576
                </div>';
577
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
578
                    }
579
                }
580
                echo "<div class='alert alert-success alert-dismissable'>
581
                    <i class='fa fa-ban'></i>
582
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
583
                    \Lang::get('message.success').'
584
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
585
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
586
                </div>';
587
            } else {
588
                echo "<div class='alert alert-danger alert-dismissable'>
589
                    <i class='fa fa-ban'></i>
590
                    <b>"./** @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
591
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
592
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
593
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
594
                </div>';
595
                //echo \Lang::get('message.select-a-row');
596
            }
597
        } catch (\Exception $e) {
598
            echo "<div class='alert alert-danger alert-dismissable'>
599
                    <i class='fa fa-ban'></i>
600
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
601
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
602
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
603
                        '.$e->getMessage().'
604
                </div>';
605
        }
606
    }
607
608
    public function updateInvoice($invoiceid)
609
    {
610
        try {
611
            $invoice = $this->invoice->findOrFail($invoiceid);
612
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
613
            $total = array_sum($payment);
614
            if ($total < $invoice->grand_total) {
615
                $invoice->status = 'pending';
616
            }
617
            if ($total >= $invoice->grand_total) {
618
                $invoice->status = 'success';
619
            }
620
            if ($total > $invoice->grand_total) {
621
                $user = $invoice->user()->first();
622
                $balance = $total - $invoice->grand_total;
623
                $user->debit = $balance;
624
                $user->save();
625
            }
626
627
            $invoice->save();
628
        } catch (\Exception $ex) {
629
            Bugsnag::notifyException($ex);
630
631
            throw new \Exception($ex->getMessage());
632
        }
633
    }
634
635
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
636
    {
637
        try {
638
            $invoice = $this->invoice->find($invoiceid);
639
            $invoice_status = 'pending';
640
641
            $payment = $this->payment->create([
642
                'invoice_id'     => $invoiceid,
643
                'user_id'        => $invoice->user_id,
644
                'amount'         => $amount,
645
                'payment_method' => $payment_method,
646
                'payment_status' => $payment_status,
647
                'created_at'     => $payment_date,
648
            ]);
649
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
650
            $total_paid = array_sum($all_payments);
651
            if ($total_paid >= $invoice->grand_total) {
652
                $invoice_status = 'success';
653
            }
654
            if ($invoice) {
655
                $invoice->status = $invoice_status;
656
                $invoice->save();
657
            }
658
659
            return $payment;
660
        } catch (\Exception $ex) {
661
            Bugsnag::notifyException($ex);
662
663
            throw new \Exception($ex->getMessage());
664
        }
665
    }
666
667
    public function pdf(Request $request)
668
    {
669
        try {
670
            $id = $request->input('invoiceid');
671
            if (!$id) {
672
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
673
            }
674
            $invoice = $this->invoice->where('id', $id)->first();
675
            if (!$invoice) {
676
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
677
            }
678
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
679
            if ($invoiceItems->count() == 0) {
680
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
681
            }
682
            $user = $this->user->find($invoice->user_id);
683
            if (!$user) {
684
                return redirect()->back()->with('fails', 'No User');
685
            }
686
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
687
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
688
689
            return $pdf->download($user->first_name.'-invoice.pdf');
690
        } catch (\Exception $ex) {
691
            Bugsnag::notifyException($ex);
692
693
            return redirect()->back()->with('fails', $ex->getMessage());
694
        }
695
    }
696
697
    public function getExpiryStatus($start, $end, $now)
698
    {
699
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
700
        if ($whenDateNotSet) {
701
            return $whenDateNotSet;
702
        }
703
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
704
        if ($whenStartDateSet) {
705
            return $whenStartDateSet;
706
        }
707
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
708
        if ($whenEndDateSet) {
709
            return $whenEndDateSet;
710
        }
711
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
712
        if ($whenBothAreSet) {
713
            return $whenBothAreSet;
714
        }
715
    }
716
717
    public function payment(Request $request)
718
    {
719
        try {
720
            if ($request->has('invoiceid')) {
721
                $invoice_id = $request->input('invoiceid');
722
                $invoice = $this->invoice->find($invoice_id);
723
                //dd($invoice);
724
                $invoice_status = '';
725
                $payment_status = '';
726
                $payment_method = '';
727
                $domain = '';
728
                if ($invoice) {
729
                    $invoice_status = $invoice->status;
730
                    $items = $invoice->invoiceItem()->first();
731
                    if ($items) {
732
                        $domain = $items->domain;
733
                    }
734
                }
735
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
736
                if ($payment) {
737
                    $payment_status = $payment->payment_status;
738
                    $payment_method = $payment->payment_method;
739
                }
740
741
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
742
            }
743
744
            return redirect()->back();
745
        } catch (\Exception $ex) {
746
            Bugsnag::notifyException($ex);
747
748
            return redirect()->back()->with('fails', $ex->getMessage());
749
        }
750
    }
751
752
    public function postRazorpayPayment($invoiceid, $grand_total)
753
    {
754
        try {
755
            $payment_method = 'Razorpay';
756
            $payment_status = 'success';
757
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
758
            $amount = $grand_total;
759
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
760
761
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
762
        } catch (\Exception $ex) {
763
            return redirect()->back()->with('fails', $ex->getMessage());
764
        }
765
    }
766
767
    public function sendMail($userid, $invoiceid)
768
    {
769
        try {
770
            $invoice = $this->invoice->find($invoiceid);
771
            $number = $invoice->number;
772
            $total = $invoice->grand_total;
773
774
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
775
        } catch (\Exception $ex) {
776
            Bugsnag::notifyException($ex);
777
778
            throw new \Exception($ex->getMessage());
779
        }
780
    }
781
782
    public function deletePayment(Request $request)
783
    {
784
        try {
785
            $ids = $request->input('select');
786
            if (!empty($ids)) {
787
                foreach ($ids as $id) {
788
                    $payment = $this->payment->where('id', $id)->first();
789
                    if ($payment) {
790
                        $invoice = $this->invoice->find($payment->invoice_id);
791
                        if ($invoice) {
792
                            $invoice->status = 'pending';
793
                            $invoice->save();
794
                        }
795
                        $payment->delete();
796
                    } else {
797
                        echo "<div class='alert alert-danger alert-dismissable'>
798
                    <i class='fa fa-ban'></i>
799
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
800
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
801
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
802
                </div>';
803
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
804
                    }
805
                }
806
                echo "<div class='alert alert-success alert-dismissable'>
807
                    <i class='fa fa-ban'></i>
808
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
809
                    \Lang::get('message.success').'
810
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
811
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
812
                </div>';
813
            } else {
814
                echo "<div class='alert alert-danger alert-dismissable'>
815
                    <i class='fa fa-ban'></i>
816
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
817
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
818
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
819
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
820
                </div>';
821
                //echo \Lang::get('message.select-a-row');
822
            }
823
        } catch (\Exception $e) {
824
            Bugsnag::notifyException($e);
825
            echo "<div class='alert alert-danger alert-dismissable'>
826
                    <i class='fa fa-ban'></i>
827
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
828
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
829
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
830
                        '.$e->getMessage().'
831
                </div>';
832
        }
833
    }
834
}
835