Completed
Push — development ( d3ce46...64eb7f )
by Ashutosh
10:50
created

InvoiceController::payment()   B

Complexity

Conditions 6
Paths 21

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 30
rs 8.9617
c 0
b 0
f 0
cc 6
nc 21
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()
0 ignored issues
show
Coding Style introduced by
Function name "__construct" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
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
<<<<<<< HEAD
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_SL on line 502 at column 0
Loading history...
503
=======
504
            dd($ex);
505
506
>>>>>>> d3ce4660801cdc76373f588d6a1789df47973fe6
507
            throw new \Exception(\Lang::get('message.check-tax-error'));
508
        }
509
    }
510
511
    public function getRate($productid, $taxs, $userid)
512
    {
513
        $tax_attribute = [];
514
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
515
        $tax_value = '0';
516
517
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
518
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
519
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
520
        $origin_state = $this->setting->first()->state; //Get the State of origin
521
        $cartController = new CartController();
522
523
        $rate = 0;
524
        $name1 = 'CGST';
525
        $name2 = 'SGST';
526
        $name3 = 'IGST';
527
        $name4 = 'UTGST';
528
        $c_gst = 0;
529
        $s_gst = 0;
530
        $i_gst = 0;
531
        $ut_gst = 0;
532
        $state_code = '';
533
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
534
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
535
            $taxes = $tax['taxes'];
536
            $value = $tax['value'];
537
        } else {//If user from other Country
538
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
539
            $taxes = $tax['taxes'];
540
            $value = $tax['value'];
541
            $rate = $tax['rate'];
542
        }
543
544
        foreach ($taxes as $key => $tax) {
545
            if ($taxes[0]) {
546
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1,
547
                 'name2'                       => $name2, 'name3' => $name3, 'name4' => $name4,
548
                 'rate'                        => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst,
549
                 'rate3'                       => $i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code,
550
                  'origin_state'               => $origin_state, ];
551
552
                $rate = $tax->rate;
553
554
                $tax_value = $value;
555
            } else {
556
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
557
                $tax_value = '0%';
558
            }
559
        }
560
561
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
562
    }
563
564
    /**
565
     * Remove the specified resource from storage.
566
     *
567
     * @param int $id
568
     *
569
     * @return \Response
570
     */
571
    public function destroy(Request $request)
572
    {
573
        try {
574
            $ids = $request->input('select');
575
            if (!empty($ids)) {
576
                foreach ($ids as $id) {
577
                    $invoice = $this->invoice->where('id', $id)->first();
578
                    if ($invoice) {
579
                        $invoice->delete();
580
                    } else {
581
                        echo "<div class='alert alert-danger alert-dismissable'>
582
                    <i class='fa fa-ban'></i>
583
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
584
                    /* @scrutinizer ignore-type */
585
                    \Lang::get('message.failed').'
586
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
587
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
588
                </div>';
589
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
590
                    }
591
                }
592
                echo "<div class='alert alert-success alert-dismissable'>
593
                    <i class='fa fa-ban'></i>
594
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
595
                    /* @scrutinizer ignore-type */
596
                    \Lang::get('message.success').'
597
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
598
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
599
                </div>';
600
            } else {
601
                echo "<div class='alert alert-danger alert-dismissable'>
602
                    <i class='fa fa-ban'></i>
603
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
604
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
605
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
606
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
607
                </div>';
608
                //echo \Lang::get('message.select-a-row');
609
            }
610
        } catch (\Exception $e) {
611
            echo "<div class='alert alert-danger alert-dismissable'>
612
                    <i class='fa fa-ban'></i>
613
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
614
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
615
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
616
                        '.$e->getMessage().'
617
                </div>';
618
        }
619
    }
620
621
    public function updateInvoice($invoiceid)
622
    {
623
        try {
624
            $invoice = $this->invoice->findOrFail($invoiceid);
625
            $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...
626
            $total = array_sum($payment);
627
            if ($total < $invoice->grand_total) {
628
                $invoice->status = 'pending';
629
            }
630
            if ($total >= $invoice->grand_total) {
631
                $invoice->status = 'success';
632
            }
633
            if ($total > $invoice->grand_total) {
634
                $user = $invoice->user()->first();
635
                $balance = $total - $invoice->grand_total;
636
                $user->debit = $balance;
637
                $user->save();
638
            }
639
640
            $invoice->save();
641
        } catch (\Exception $ex) {
642
            Bugsnag::notifyException($ex);
643
644
            throw new \Exception($ex->getMessage());
645
        }
646
    }
647
648
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
649
    {
650
        try {
651
            $invoice = $this->invoice->find($invoiceid);
652
            $invoice_status = 'pending';
653
654
            $payment = $this->payment->create([
655
                'invoice_id'     => $invoiceid,
656
                'user_id'        => $invoice->user_id,
657
                'amount'         => $amount,
658
                'payment_method' => $payment_method,
659
                'payment_status' => $payment_status,
660
                'created_at'     => $payment_date,
661
            ]);
662
            $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...
663
            $total_paid = array_sum($all_payments);
664
            if ($total_paid >= $invoice->grand_total) {
665
                $invoice_status = 'success';
666
            }
667
            if ($invoice) {
668
                $invoice->status = $invoice_status;
669
                $invoice->save();
670
            }
671
672
            return $payment;
673
        } catch (\Exception $ex) {
674
            Bugsnag::notifyException($ex);
675
676
            throw new \Exception($ex->getMessage());
677
        }
678
    }
679
680
    public function pdf(Request $request)
681
    {
682
        try {
683
            $id = $request->input('invoiceid');
684
            if (!$id) {
685
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
686
            }
687
            $invoice = $this->invoice->where('id', $id)->first();
688
            if (!$invoice) {
689
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
690
            }
691
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
692
            if ($invoiceItems->count() == 0) {
693
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
694
            }
695
            $user = $this->user->find($invoice->user_id);
696
            if (!$user) {
697
                return redirect()->back()->with('fails', 'No User');
698
            }
699
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
700
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
701
702
            return $pdf->download($user->first_name.'-invoice.pdf');
703
        } catch (\Exception $ex) {
704
            Bugsnag::notifyException($ex);
705
706
            return redirect()->back()->with('fails', $ex->getMessage());
707
        }
708
    }
709
710
    public function getExpiryStatus($start, $end, $now)
711
    {
712
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
713
        if ($whenDateNotSet) {
714
            return $whenDateNotSet;
715
        }
716
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
717
        if ($whenStartDateSet) {
718
            return $whenStartDateSet;
719
        }
720
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
721
        if ($whenEndDateSet) {
722
            return $whenEndDateSet;
723
        }
724
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
725
        if ($whenBothAreSet) {
726
            return $whenBothAreSet;
727
        }
728
    }
729
730
    public function payment(Request $request)
731
    {
732
        try {
733
            if ($request->has('invoiceid')) {
734
                $invoice_id = $request->input('invoiceid');
735
                $invoice = $this->invoice->find($invoice_id);
736
                //dd($invoice);
737
                $invoice_status = '';
738
                $payment_status = '';
739
                $payment_method = '';
740
                $domain = '';
741
                if ($invoice) {
742
                    $invoice_status = $invoice->status;
743
                    $items = $invoice->invoiceItem()->first();
744
                    if ($items) {
745
                        $domain = $items->domain;
746
                    }
747
                }
748
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
749
                if ($payment) {
750
                    $payment_status = $payment->payment_status;
751
                    $payment_method = $payment->payment_method;
752
                }
753
754
                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...
755
            }
756
757
            return redirect()->back();
758
        } catch (\Exception $ex) {
759
            Bugsnag::notifyException($ex);
760
761
            return redirect()->back()->with('fails', $ex->getMessage());
762
        }
763
    }
764
765
    public function findCostAfterDiscount($promoid, $productid, $currency)
766
    {
767
        try {
768
            $promotion = Promotion::findOrFail($promoid);
769
            $product = Product::findOrFail($productid);
770
            $promotion_type = $promotion->type;
771
            $promotion_value = $promotion->value;
772
            $planId = Plan::where('product', $productid)->pluck('id')->first();
773
            // dd($planId);
774
            $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...
775
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
776
777
            return $updated_price;
778
        } catch (\Exception $ex) {
779
            Bugsnag::notifyException($ex);
780
781
            throw new \Exception(\Lang::get('message.find-discount-error'));
782
        }
783
    }
784
785
    public function findCost($type, $value, $price, $productid)
786
    {
787
        switch ($type) {
788
                case 1:
789
                    $percentage = $price * ($value / 100);
790
791
                     return $price - $percentage;
792
                case 2:
793
                    return $price - $value;
794
                case 3:
795
                    return $value;
796
                case 4:
797
                    return 0;
798
            }
799
    }
800
801
    public function postRazorpayPayment($invoiceid, $grand_total)
802
    {
803
        try {
804
            $payment_method = 'Razorpay';
805
            $payment_status = 'success';
806
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
807
            $amount = $grand_total;
808
            $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...
809
810
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
811
        } catch (\Exception $ex) {
812
            return redirect()->back()->with('fails', $ex->getMessage());
813
        }
814
    }
815
816
    public function sendMail($userid, $invoiceid)
817
    {
818
        try {
819
            $invoice = $this->invoice->find($invoiceid);
820
            $number = $invoice->number;
821
            $total = $invoice->grand_total;
822
823
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
824
        } catch (\Exception $ex) {
825
            Bugsnag::notifyException($ex);
826
827
            throw new \Exception($ex->getMessage());
828
        }
829
    }
830
831
    public function deletePayment(Request $request)
832
    {
833
        try {
834
            $ids = $request->input('select');
835
            if (!empty($ids)) {
836
                foreach ($ids as $id) {
837
                    $payment = $this->payment->where('id', $id)->first();
838
                    if ($payment) {
839
                        $invoice = $this->invoice->find($payment->invoice_id);
840
                        if ($invoice) {
841
                            $invoice->status = 'pending';
842
                            $invoice->save();
843
                        }
844
                        $payment->delete();
845
                    } else {
846
                        echo "<div class='alert alert-danger alert-dismissable'>
847
                    <i class='fa fa-ban'></i>
848
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
849
                    './* @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> '.
859
                    /* @scrutinizer ignore-type */
860
                    \Lang::get('message.success').'
861
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
862
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
863
                </div>';
864
            } else {
865
                echo "<div class='alert alert-danger alert-dismissable'>
866
                    <i class='fa fa-ban'></i>
867
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
868
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
869
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
870
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
871
                </div>';
872
                //echo \Lang::get('message.select-a-row');
873
            }
874
        } catch (\Exception $e) {
875
            Bugsnag::notifyException($e);
876
            echo "<div class='alert alert-danger alert-dismissable'>
877
                    <i class='fa fa-ban'></i>
878
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
879
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
880
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
881
                        '.$e->getMessage().'
882
                </div>';
883
        }
884
    }
885
}
886