Completed
Push — development ( 5f50c9...3496bb )
by Ashutosh
11:44 queued 10s
created

InvoiceController::createInvoiceItemsByAdmin()   A

Complexity

Conditions 5
Paths 38

Size

Total Lines 51
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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>';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
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>";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 217 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
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>"
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 197 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
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
        if ($total == "")
211
        {
212
            $total = 0;
213
        }
214
         $number = $request->input('number');
215
        $invoiceId = Invoice::where('number', $number)->value('id');
216
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
217
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
218
    }
219
220
    public function sendmailClientAgent($userid, $invoiceid)
221
    {
222
        try {
223
            $agent = \Input::get('agent');
224
            $client = \Input::get('client');
225
            if ($agent == 1) {
226
                $id = \Auth::user()->id;
227
                $this->sendMail($id, $invoiceid);
228
            }
229
            if ($client == 1) {
230
                $this->sendMail($userid, $invoiceid);
231
            }
232
        } catch (\Exception $ex) {
233
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
234
            app('log')->info($ex->getMessage());
235
            Bugsnag::notifyException($ex);
236
237
            throw new \Exception($ex->getMessage());
238
        }
239
    }
240
241
    /**
242
     * Generate invoice.
243
     *
244
     * @throws \Exception
245
     */
246
    public function generateInvoice()
247
    {
248
        try {
249
            // dd(\Cart::getContent());
250
            $tax_rule = new \App\Model\Payment\TaxOption();
251
            $rule = $tax_rule->findOrFail(1);
252
            $rounding = $rule->rounding;
253
254
            $user_id = \Auth::user()->id;
255
            if (\Auth::user()->currency == 'INR') {
256
                $grand_total = \Cart::getSubTotal();
257
            } else {
258
                foreach (\Cart::getContent() as $cart) {
259
260
                    // $grand_total = $cart->price;
261
                    $grand_total = \Cart::getSubTotal();
262
                }
263
            }
264
            // dd($grand_total);
265
266
            $number = rand(11111111, 99999999);
267
            $date = \Carbon\Carbon::now();
268
269
            if ($rounding == 1) {
270
                $grand_total = round($grand_total);
271
            }
272
            $content = \Cart::getContent();
273
            $attributes = [];
274
            foreach ($content as $key => $item) {
275
                $attributes[] = $item->attributes;
276
            }
277
278
            $symbol = $attributes[0]['currency'][0]['code'];
279
            //dd($symbol);
280
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 186 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
281
282
            foreach (\Cart::getContent() as $cart) {
283
                $this->createInvoiceItems($invoice->id, $cart);
284
            }
285
            //$this->sendMail($user_id, $invoice->id);
286
            return $invoice;
287
        } catch (\Exception $ex) {
288
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
289
            app('log')->info($ex->getMessage());
290
            Bugsnag::notifyException($ex);
291
292
            throw new \Exception('Can not Generate Invoice');
293
        }
294
    }
295
296
    public function createInvoiceItems($invoiceid, $cart)
297
    {
298
        try {
299
            $planid = 0;
300
            $product_name = $cart->name;
301
            $regular_price = $cart->price;
302
            $quantity = $cart->quantity;
303
            $domain = $this->domain($cart->id);
304
            $cart_cont = new \App\Http\Controllers\Front\CartController();
305
            if ($cart_cont->checkPlanSession() === true) {
306
                $planid = \Session::get('plan');
307
            }
308
            $user_currency = \Auth::user()->currency;
309
            $subtotal = $this->getSubtotal($user_currency, $cart);
310
311
            $tax_name = '';
312
            $tax_percentage = '';
313
314
            foreach ($cart->attributes['tax'] as $tax) {
315
                $tax_name .= $tax['name'].',';
316
                $tax_percentage .= $tax['rate'].',';
317
            }
318
319
            $invoiceItem = $this->invoiceItem->create([
320
                'invoice_id'     => $invoiceid,
321
                'product_name'   => $product_name,
322
                'regular_price'  => $regular_price,
323
                'quantity'       => $quantity,
324
                'tax_name'       => $tax_name,
325
                'tax_percentage' => $tax_percentage,
326
                'subtotal'       => $subtotal,
327
                'domain'         => $domain,
328
                'plan_id'        => $planid,
329
            ]);
330
331
            return $invoiceItem;
332
        } catch (\Exception $ex) {
333
            Bugsnag::notifyException($ex);
334
335
            throw new \Exception('Can not create Invoice Items');
336
        }
337
    }
338
339
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
340
    {
341
        try {
342
            if ($amount > 0) {
343
                if ($userid == '') {
344
                    $userid = \Auth::user()->id;
345
                }
346
                if ($amount == 0) {
347
                    $payment_status = 'success';
348
                }
349
                $this->payment->create([
350
                    'parent_id'      => $parent_id,
351
                    'invoice_id'     => $invoiceid,
352
                    'user_id'        => $userid,
353
                    'amount'         => $amount,
354
                    'payment_method' => $payment_method,
355
                    'payment_status' => $payment_status,
356
                ]);
357
                $this->updateInvoice($invoiceid);
358
            }
359
        } catch (\Exception $ex) {
360
            Bugsnag::notifyException($ex);
361
362
            throw new \Exception($ex->getMessage());
363
        }
364
    }
365
366
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price,
367
        $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
368
    {
369
        try {
370
            $discount = '';
371
            $mode = '';
372
            $product = $this->product->findOrFail($productid);
373
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
374
            $price = $this->getPrice($price, $price_model);
375
            $subtotal = $qty * $price;
376
            //dd($subtotal);
377
            if ($code) {
378
                $subtotal = $this->checkCode($code, $productid, $currency);
379
                $mode = 'coupon';
380
                $discount = $price - $subtotal;
381
            }
382
            $userid = \Auth::user()->id;
383
            if (\Auth::user()->role == 'user') {
384
                $tax = $this->checkTax($product->id, $userid);
385
                $tax_name = '';
386
                $tax_rate = '';
387
                if (!empty($tax)) {
388
389
                    //dd($value);
390
                    $tax_name = $tax[0];
391
                    $tax_rate = $tax[1];
392
                }
393
            }
394
395
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
396
397
            $domain = $this->domain($productid);
398
            $items = $this->invoiceItem->create([
399
                'invoice_id'     => $invoiceid,
400
                'product_name'   => $product->name,
401
                'regular_price'  => $price,
402
                'quantity'       => $qty,
403
                'discount'       => $discount,
404
                'discount_mode'  => $mode,
405
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
406
                'tax_name'       => $tax_name,
407
                'tax_percentage' => $tax_rate,
408
                'domain'         => $domain,
409
                'plan_id'        => $planid,
410
            ]);
411
412
            return $items;
413
        } catch (\Exception $ex) {
414
            Bugsnag::notifyException($ex);
415
416
            return redirect()->back()->with('fails', $ex->getMessage());
417
        }
418
    }
419
420
    public function checkCode($code, $productid, $currency)
421
    {
422
        try {
423
            if ($code != '') {
424
                $promo = $this->promotion->where('code', $code)->first();
425
                //check promotion code is valid
426
                if (!$promo) {
427
                    throw new \Exception(\Lang::get('message.no-such-code'));
428
                }
429
                $relation = $promo->relation()->get();
430
                //check the relation between code and product
431
                if (count($relation) == 0) {
432
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
433
                }
434
                //check the usess
435
                $cont = new \App\Http\Controllers\Payment\PromotionController();
436
                $uses = $cont->checkNumberOfUses($code);
437
                if ($uses != 'success') {
438
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
439
                }
440
                //check for the expiry date
441
                $expiry = $this->checkExpiry($code);
442
                if ($expiry != 'success') {
443
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
444
                }
445
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
446
447
                return $value;
448
            } else {
449
                $product = $this->product->find($productid);
450
                $plans = Plan::where('product', $product)->pluck('id')->first();
451
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
452
453
                return $price;
454
            }
455
        } catch (\Exception $ex) {
456
            throw new \Exception($ex->getMessage());
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
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
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
481
                        // when tax is available and tax is not enabled(Applicable
482
                        //when Global Tax class for any country and state is not there)
483
484
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 142 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
485
                        if ($taxClassId) { //if state equals the user State
486
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
487
                            $taxs = $rate['taxes'];
488
                            $rate = $rate['rate'];
489
                        }
490
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
491
492
                        return $taxs;
493
                    }
494
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
495
                } else {
496
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
497
                }
498
            }
499
500
            return $taxs;
501
        } catch (\Exception $ex) {
502
            throw new \Exception(\Lang::get('message.check-tax-error'));
503
        }
504
    }
505
506
    public function getRate($productid, $taxs, $userid)
507
    {
508
        $tax_attribute = [];
509
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
510
        $tax_value = '0';
511
512
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
513
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
514
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
515
        $origin_state = $this->setting->first()->state; //Get the State of origin
516
        $cartController = new CartController();
517
518
        $rate = 0;
519
        $name1 = 'CGST';
520
        $name2 = 'SGST';
521
        $name3 = 'IGST';
522
        $name4 = 'UTGST';
523
        $c_gst = 0;
524
        $s_gst = 0;
525
        $i_gst = 0;
526
        $ut_gst = 0;
527
        $state_code = '';
528
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
529
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
530
            $taxes = $tax['taxes'];
531
            $value = $tax['value'];
532
        } else {//If user from other Country
533
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
534
            $taxes = $tax['taxes'];
535
            $value = $tax['value'];
536
            $rate = $tax['rate'];
537
        }
538
539
        foreach ($taxes as $key => $tax) {
540
            if ($taxes[0]) {
541
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1,
542
                 'name2'                       => $name2, 'name3' => $name3, 'name4' => $name4,
543
                 'rate'                        => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst,
544
                 'rate3'                       => $i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code,
545
                  'origin_state'               => $origin_state, ];
546
547
                $rate = $tax->rate;
548
549
                $tax_value = $value;
550
            } else {
551
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
552
                $tax_value = '0%';
553
            }
554
        }
555
556
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
557
    }
558
559
    /**
560
     * Remove the specified resource from storage.
561
     *
562
     * @param int $id
563
     *
564
     * @return \Response
565
     */
566
    public function destroy(Request $request)
567
    {
568
        try {
569
            $ids = $request->input('select');
570
            if (!empty($ids)) {
571
                foreach ($ids as $id) {
572
                    $invoice = $this->invoice->where('id', $id)->first();
573
                    if ($invoice) {
574
                        $invoice->delete();
575
                    } else {
576
                        echo "<div class='alert alert-danger alert-dismissable'>
577
                    <i class='fa fa-ban'></i>
578
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
579
                    /* @scrutinizer ignore-type */
580
                    \Lang::get('message.failed').'
581
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
582
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
583
                </div>';
584
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
585
                    }
586
                }
587
                echo "<div class='alert alert-success alert-dismissable'>
588
                    <i class='fa fa-ban'></i>
589
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
590
                    /* @scrutinizer ignore-type */
591
                    \Lang::get('message.success').'
592
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
593
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
594
                </div>';
595
            } else {
596
                echo "<div class='alert alert-danger alert-dismissable'>
597
                    <i class='fa fa-ban'></i>
598
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
599
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
600
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
601
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
602
                </div>';
603
                //echo \Lang::get('message.select-a-row');
604
            }
605
        } catch (\Exception $e) {
606
            echo "<div class='alert alert-danger alert-dismissable'>
607
                    <i class='fa fa-ban'></i>
608
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
609
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
610
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
611
                        '.$e->getMessage().'
612
                </div>';
613
        }
614
    }
615
616
    public function updateInvoice($invoiceid)
617
    {
618
        try {
619
            $invoice = $this->invoice->findOrFail($invoiceid);
620
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
621
            $total = array_sum($payment);
622
            if ($total < $invoice->grand_total) {
623
                $invoice->status = 'pending';
624
            }
625
            if ($total >= $invoice->grand_total) {
626
                $invoice->status = 'success';
627
            }
628
            if ($total > $invoice->grand_total) {
629
                $user = $invoice->user()->first();
630
                $balance = $total - $invoice->grand_total;
631
                $user->debit = $balance;
632
                $user->save();
633
            }
634
635
            $invoice->save();
636
        } catch (\Exception $ex) {
637
            Bugsnag::notifyException($ex);
638
639
            throw new \Exception($ex->getMessage());
640
        }
641
    }
642
643
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
644
    {
645
        try {
646
            $invoice = $this->invoice->find($invoiceid);
647
            $invoice_status = 'pending';
648
649
            $payment = $this->payment->create([
650
                'invoice_id'     => $invoiceid,
651
                'user_id'        => $invoice->user_id,
652
                'amount'         => $amount,
653
                'payment_method' => $payment_method,
654
                'payment_status' => $payment_status,
655
                'created_at'     => $payment_date,
656
            ]);
657
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 140 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
658
            $total_paid = array_sum($all_payments);
659
            if ($total_paid >= $invoice->grand_total) {
660
                $invoice_status = 'success';
661
            }
662
            if ($invoice) {
663
                $invoice->status = $invoice_status;
664
                $invoice->save();
665
            }
666
667
            return $payment;
668
        } catch (\Exception $ex) {
669
            Bugsnag::notifyException($ex);
670
671
            throw new \Exception($ex->getMessage());
672
        }
673
    }
674
675
    public function pdf(Request $request)
676
    {
677
        try {
678
            $id = $request->input('invoiceid');
679
            if (!$id) {
680
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
681
            }
682
            $invoice = $this->invoice->where('id', $id)->first();
683
            if (!$invoice) {
684
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
685
            }
686
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
687
            if ($invoiceItems->count() == 0) {
688
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
689
            }
690
            $user = $this->user->find($invoice->user_id);
691
            if (!$user) {
692
                return redirect()->back()->with('fails', 'No User');
693
            }
694
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
695
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
696
697
            return $pdf->download($user->first_name.'-invoice.pdf');
698
        } catch (\Exception $ex) {
699
            Bugsnag::notifyException($ex);
700
701
            return redirect()->back()->with('fails', $ex->getMessage());
702
        }
703
    }
704
705
    public function getExpiryStatus($start, $end, $now)
706
    {
707
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
708
        if ($whenDateNotSet) {
709
            return $whenDateNotSet;
710
        }
711
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
712
        if ($whenStartDateSet) {
713
            return $whenStartDateSet;
714
        }
715
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
716
        if ($whenEndDateSet) {
717
            return $whenEndDateSet;
718
        }
719
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
720
        if ($whenBothAreSet) {
721
            return $whenBothAreSet;
722
        }
723
    }
724
725
    public function payment(Request $request)
726
    {
727
        try {
728
            if ($request->has('invoiceid')) {
729
                $invoice_id = $request->input('invoiceid');
730
                $invoice = $this->invoice->find($invoice_id);
731
                //dd($invoice);
732
                $invoice_status = '';
733
                $payment_status = '';
734
                $payment_method = '';
735
                $domain = '';
736
                if ($invoice) {
737
                    $invoice_status = $invoice->status;
738
                    $items = $invoice->invoiceItem()->first();
739
                    if ($items) {
740
                        $domain = $items->domain;
741
                    }
742
                }
743
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
744
                if ($payment) {
745
                    $payment_status = $payment->payment_status;
746
                    $payment_method = $payment->payment_method;
747
                }
748
749
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 161 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
750
            }
751
752
            return redirect()->back();
753
        } catch (\Exception $ex) {
754
            Bugsnag::notifyException($ex);
755
756
            return redirect()->back()->with('fails', $ex->getMessage());
757
        }
758
    }
759
760
    public function findCostAfterDiscount($promoid, $productid, $currency)
761
    {
762
        try {
763
            $promotion = Promotion::findOrFail($promoid);
764
            $product = Product::findOrFail($productid);
765
            $promotion_type = $promotion->type;
766
            $promotion_value = $promotion->value;
767
            $planId = Plan::where('product', $productid)->pluck('id')->first();
768
            // dd($planId);
769
            $product_price = PlanPrice::where('plan_id', $planId)->where('currency', $currency)->pluck('add_price')->first();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
770
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
771
772
            return $updated_price;
773
        } catch (\Exception $ex) {
774
            Bugsnag::notifyException($ex);
775
776
            throw new \Exception(\Lang::get('message.find-discount-error'));
777
        }
778
    }
779
780
    public function findCost($type, $value, $price, $productid)
781
    {
782
        switch ($type) {
783
                case 1:
784
                    $percentage = $price * ($value / 100);
785
786
                     return $price - $percentage;
787
                case 2:
788
                    return $price - $value;
789
                case 3:
790
                    return $value;
791
                case 4:
792
                    return 0;
793
            }
794
    }
795
796
    public function postRazorpayPayment($invoiceid, $grand_total)
797
    {
798
        try {
799
            $payment_method = 'Razorpay';
800
            $payment_status = 'success';
801
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
802
            $amount = $grand_total;
803
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
804
805
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
806
        } catch (\Exception $ex) {
807
            return redirect()->back()->with('fails', $ex->getMessage());
808
        }
809
    }
810
811
    public function sendMail($userid, $invoiceid)
812
    {
813
        try {
814
            $invoice = $this->invoice->find($invoiceid);
815
            $number = $invoice->number;
816
            $total = $invoice->grand_total;
817
818
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
819
        } catch (\Exception $ex) {
820
            Bugsnag::notifyException($ex);
821
822
            throw new \Exception($ex->getMessage());
823
        }
824
    }
825
826
    public function deletePayment(Request $request)
827
    {
828
        try {
829
            $ids = $request->input('select');
830
            if (!empty($ids)) {
831
                foreach ($ids as $id) {
832
                    $payment = $this->payment->where('id', $id)->first();
833
                    if ($payment) {
834
                        $invoice = $this->invoice->find($payment->invoice_id);
835
                        if ($invoice) {
836
                            $invoice->status = 'pending';
837
                            $invoice->save();
838
                        }
839
                        $payment->delete();
840
                    } else {
841
                        echo "<div class='alert alert-danger alert-dismissable'>
842
                    <i class='fa fa-ban'></i>
843
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
844
                    './* @scrutinizer ignore-type */\Lang::get('message.failed').'
845
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
846
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
847
                </div>';
848
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
849
                    }
850
                }
851
                echo "<div class='alert alert-success alert-dismissable'>
852
                    <i class='fa fa-ban'></i>
853
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
854
                    /* @scrutinizer ignore-type */
855
                    \Lang::get('message.success').'
856
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
857
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
858
                </div>';
859
            } else {
860
                echo "<div class='alert alert-danger alert-dismissable'>
861
                    <i class='fa fa-ban'></i>
862
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
863
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
864
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
865
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
866
                </div>';
867
                //echo \Lang::get('message.select-a-row');
868
            }
869
        } catch (\Exception $e) {
870
            Bugsnag::notifyException($e);
871
            echo "<div class='alert alert-danger alert-dismissable'>
872
                    <i class='fa fa-ban'></i>
873
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
874
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
875
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
876
                        '.$e->getMessage().'
877
                </div>';
878
        }
879
    }
880
}
881