Test Setup Failed
Push — development ( ac5058...9fa3be )
by Ashutosh
11:12
created

InvoiceController::pdf()   A

Complexity

Conditions 6
Paths 16

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 27
rs 9.0444
c 0
b 0
f 0
cc 6
nc 16
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Front\CartController;
6
use App\Model\Common\Setting;
7
use App\Model\Common\Template;
8
use App\Model\Order\Invoice;
9
use App\Model\Order\InvoiceItem;
10
use App\Model\Order\Order;
11
use App\Model\Order\Payment;
12
use App\Model\Payment\Currency;
13
use App\Model\Payment\Plan;
14
use App\Model\Payment\PlanPrice;
15
use App\Model\Payment\Promotion;
16
use App\Model\Payment\Tax;
17
use App\Model\Payment\TaxByState;
18
use App\Model\Payment\TaxOption;
19
use App\Model\Product\Price;
20
use App\Model\Product\Product;
21
use App\User;
22
use Bugsnag;
23
use Illuminate\Http\Request;
24
use Input;
25
use Log;
26
27
class InvoiceController extends TaxRatesAndCodeExpiryController
28
{
29
    public $invoice;
30
    public $invoiceItem;
31
    public $user;
32
    public $template;
33
    public $setting;
34
    public $payment;
35
    public $product;
36
    public $price;
37
    public $promotion;
38
    public $currency;
39
    public $tax;
40
    public $tax_option;
41
    public $order;
42
    public $cartController;
43
44
    public function __construct()
45
    {
46
        $this->middleware('auth');
47
        $this->middleware('admin', ['except' => ['pdf']]);
48
49
        $invoice = new Invoice();
50
        $this->invoice = $invoice;
51
52
        $invoiceItem = new InvoiceItem();
53
        $this->invoiceItem = $invoiceItem;
54
55
        $user = new User();
56
        $this->user = $user;
57
58
        $template = new Template();
59
        $this->template = $template;
60
61
        $seting = new Setting();
62
        $this->setting = $seting;
63
64
        $payment = new Payment();
65
        $this->payment = $payment;
66
67
        $product = new Product();
68
        $this->product = $product;
69
70
        $price = new Price();
71
        $this->price = $price;
72
73
        $promotion = new Promotion();
74
        $this->promotion = $promotion;
75
76
        $currency = new Currency();
77
        $this->currency = $currency;
78
79
        $tax = new Tax();
80
        $this->tax = $tax;
81
82
        $tax_option = new TaxOption();
83
        $this->tax_option = $tax_option;
84
85
        $order = new Order();
86
        $this->order = $order;
87
88
        $tax_by_state = new TaxByState();
89
        $this->tax_by_state = new $tax_by_state();
90
91
        $cartController = new CartController();
92
        $this->cartController = $cartController;
93
    }
94
95
    public function index()
96
    {
97
        try {
98
            //dd($this->invoice->get());
99
            return view('themes.default1.invoice.index');
100
        } catch (\Exception $ex) {
101
            Bugsnag::notifyException($ex);
102
103
            return redirect()->back()->with('fails', $ex->getMessage());
104
        }
105
    }
106
107
    public function getInvoices()
108
    {
109
        $invoice = \DB::table('invoices');
110
        // $new_invoice = $invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at');
111
112
        return \DataTables::of($invoice->get())
113
                        ->addColumn('checkbox', function ($model) {
114
                            return "<input type='checkbox' class='invoice_checkbox' value=".$model->id.' name=select[] id=check>';
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
        $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]);
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...
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')
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...
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 = '')
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...
363
    {
364
        try {
365
            $discount = '';
366
            $mode = '';
367
            $product = $this->product->findOrFail($productid);
368
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
369
            $price = $this->getPrice($price, $price_model);
370
            $subtotal = $qty * $price;
371
            //dd($subtotal);
372
            if ($code) {
373
                $subtotal = $this->checkCode($code, $productid, $currency);
374
                $mode = 'coupon';
375
                $discount = $price - $subtotal;
376
            }
377
            $userid = \Auth::user()->id;
378
            if (\Auth::user()->role == 'user') {
379
                $tax = $this->checkTax($product->id, $userid);
380
                $tax_name = '';
381
                $tax_rate = '';
382
                if (!empty($tax)) {
383
384
                    //dd($value);
385
                    $tax_name = $tax[0];
386
                    $tax_rate = $tax[1];
387
                }
388
            }
389
390
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
391
392
            $domain = $this->domain($productid);
393
            $items = $this->invoiceItem->create([
394
                'invoice_id'     => $invoiceid,
395
                'product_name'   => $product->name,
396
                'regular_price'  => $price,
397
                'quantity'       => $qty,
398
                'discount'       => $discount,
399
                'discount_mode'  => $mode,
400
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
401
                'tax_name'       => $tax_name,
402
                'tax_percentage' => $tax_rate,
403
                'domain'         => $domain,
404
                'plan_id'        => $planid,
405
            ]);
406
407
            return $items;
408
        } catch (\Exception $ex) {
409
            Bugsnag::notifyException($ex);
410
411
            return redirect()->back()->with('fails', $ex->getMessage());
412
        }
413
    }
414
415
    public function checkCode($code, $productid, $currency)
416
    {
417
        try {
418
            if ($code != '') {
419
                $promo = $this->promotion->where('code', $code)->first();
420
                //check promotion code is valid
421
                if (!$promo) {
422
                    throw new \Exception(\Lang::get('message.no-such-code'));
423
                }
424
                $relation = $promo->relation()->get();
425
                //check the relation between code and product
426
                if (count($relation) == 0) {
427
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
428
                }
429
                //check the usess
430
                $cont = new \App\Http\Controllers\Payment\PromotionController();
431
                $uses = $cont->checkNumberOfUses($code);
432
                if ($uses != 'success') {
433
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
434
                }
435
                //check for the expiry date
436
                $expiry = $this->checkExpiry($code);
437
                if ($expiry != 'success') {
438
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
439
                }
440
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
441
442
                return $value;
443
            } else {
444
                $product = $this->product->find($productid);
445
                $plans = Plan::where('product', $product)->pluck('id')->first();
446
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
447
448
                return $price;
449
            }
450
        } catch (\Exception $ex) {
451
            throw new \Exception($ex->getMessage());
452
        }
453
    }
454
455
    public function checkTax($productid, $userid)
456
    {
457
        try {
458
            $taxs = [];
459
            $taxs[0] = ['name' => 'null', 'rate' => 0];
460
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
461
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
462
            $product = $this->product->findOrFail($productid);
463
            $cartController = new CartController();
464
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
465
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
466
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
467
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
468
469
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
470
                     ->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...
471
                    if ($taxClassId) {
472
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
473
                        $taxs = $rate['taxes'];
474
                        $rate = $rate['rate'];
475
                    } 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)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 199 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
477
                        $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...
478
                        if ($taxClassId) { //if state equals the user State
479
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
480
                            $taxs = $rate['taxes'];
481
                            $rate = $rate['rate'];
482
                        }
483
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
484
485
                        return $taxs;
486
                    }
487
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
488
                } else {
489
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
490
                }
491
            }
492
493
            return $taxs;
494
        } catch (\Exception $ex) {
495
            throw new \Exception(\Lang::get('message.check-tax-error'));
496
        }
497
    }
498
499
    public function getRate($productid, $taxs, $userid)
500
    {
501
        $tax_attribute = [];
502
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
503
        $tax_value = '0';
504
505
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
506
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
507
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
508
        $origin_state = $this->setting->first()->state; //Get the State of origin
509
        $cartController = new CartController();
510
511
        $rate = 0;
512
        $name1 = 'CGST';
513
        $name2 = 'SGST';
514
        $name3 = 'IGST';
515
        $name4 = 'UTGST';
516
        $c_gst = 0;
517
        $s_gst = 0;
518
        $i_gst = 0;
519
        $ut_gst = 0;
520
        $state_code = '';
521
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
522
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
523
            $taxes = $tax['taxes'];
524
            $value = $tax['value'];
525
        } else {//If user from other Country
526
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
527
            $taxes = $tax['taxes'];
528
            $value = $tax['value'];
529
            $rate = $tax['rate'];
530
        }
531
532
        foreach ($taxes as $key => $tax) {
533
            if ($taxes[0]) {
534
                $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];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 277 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...
535
536
                $rate = $tax->rate;
537
538
                $tax_value = $value;
539
            } else {
540
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
541
                $tax_value = '0%';
542
            }
543
        }
544
545
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
546
    }
547
548
    /**
549
     * Remove the specified resource from storage.
550
     *
551
     * @param int $id
552
     *
553
     * @return \Response
554
     */
555
    public function destroy(Request $request)
556
    {
557
        try {
558
            $ids = $request->input('select');
559
            if (!empty($ids)) {
560
                foreach ($ids as $id) {
561
                    $invoice = $this->invoice->where('id', $id)->first();
562
                    if ($invoice) {
563
                        $invoice->delete();
564
                    } else {
565
                        echo "<div class='alert alert-danger alert-dismissable'>
566
                    <i class='fa fa-ban'></i>
567
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
568
                    \Lang::get('message.failed').'
569
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
570
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
571
                </div>';
572
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
573
                    }
574
                }
575
                echo "<div class='alert alert-success alert-dismissable'>
576
                    <i class='fa fa-ban'></i>
577
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
578
                    \Lang::get('message.success').'
579
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
580
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
581
                </div>';
582
            } else {
583
                echo "<div class='alert alert-danger alert-dismissable'>
584
                    <i class='fa fa-ban'></i>
585
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
586
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
587
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
588
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
589
                </div>';
590
                //echo \Lang::get('message.select-a-row');
591
            }
592
        } catch (\Exception $e) {
593
            echo "<div class='alert alert-danger alert-dismissable'>
594
                    <i class='fa fa-ban'></i>
595
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
596
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
597
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
598
                        '.$e->getMessage().'
599
                </div>';
600
        }
601
    }
602
603
    public function updateInvoice($invoiceid)
604
    {
605
        try {
606
            $invoice = $this->invoice->findOrFail($invoiceid);
607
            $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...
608
            $total = array_sum($payment);
609
            if ($total < $invoice->grand_total) {
610
                $invoice->status = 'pending';
611
            }
612
            if ($total >= $invoice->grand_total) {
613
                $invoice->status = 'success';
614
            }
615
            if ($total > $invoice->grand_total) {
616
                $user = $invoice->user()->first();
617
                $balance = $total - $invoice->grand_total;
618
                $user->debit = $balance;
619
                $user->save();
620
            }
621
622
            $invoice->save();
623
        } catch (\Exception $ex) {
624
            Bugsnag::notifyException($ex);
625
626
            throw new \Exception($ex->getMessage());
627
        }
628
    }
629
630
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
631
    {
632
        try {
633
            $invoice = $this->invoice->find($invoiceid);
634
            $invoice_status = 'pending';
635
636
            $payment = $this->payment->create([
637
                'invoice_id'     => $invoiceid,
638
                'user_id'        => $invoice->user_id,
639
                'amount'         => $amount,
640
                'payment_method' => $payment_method,
641
                'payment_status' => $payment_status,
642
                'created_at'     => $payment_date,
643
            ]);
644
            $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...
645
            $total_paid = array_sum($all_payments);
646
            if ($total_paid >= $invoice->grand_total) {
647
                $invoice_status = 'success';
648
            }
649
            if ($invoice) {
650
                $invoice->status = $invoice_status;
651
                $invoice->save();
652
            }
653
654
            return $payment;
655
        } catch (\Exception $ex) {
656
            Bugsnag::notifyException($ex);
657
658
            throw new \Exception($ex->getMessage());
659
        }
660
    }
661
662
    public function pdf(Request $request)
663
    {
664
        try {
665
            $id = $request->input('invoiceid');
666
            if (!$id) {
667
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
668
            }
669
            $invoice = $this->invoice->where('id', $id)->first();
670
            if (!$invoice) {
671
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
672
            }
673
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
674
            if ($invoiceItems->count() == 0) {
675
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
676
            }
677
            $user = $this->user->find($invoice->user_id);
678
            if (!$user) {
679
                return redirect()->back()->with('fails', 'No User');
680
            }
681
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
682
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
683
684
            return $pdf->download($user->first_name.'-invoice.pdf');
685
        } catch (\Exception $ex) {
686
            Bugsnag::notifyException($ex);
687
688
            return redirect()->back()->with('fails', $ex->getMessage());
689
        }
690
    }
691
692
    public function getExpiryStatus($start, $end, $now)
693
    {
694
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
695
        if ($whenDateNotSet) {
696
            return $whenDateNotSet;
697
        }
698
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
699
        if ($whenStartDateSet) {
700
            return $whenStartDateSet;
701
        }
702
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
703
        if ($whenEndDateSet) {
704
            return $whenEndDateSet;
705
        }
706
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
707
        if ($whenBothAreSet) {
708
            return $whenBothAreSet;
709
        }
710
    }
711
712
    public function payment(Request $request)
713
    {
714
        try {
715
            if ($request->has('invoiceid')) {
716
                $invoice_id = $request->input('invoiceid');
717
                $invoice = $this->invoice->find($invoice_id);
718
                //dd($invoice);
719
                $invoice_status = '';
720
                $payment_status = '';
721
                $payment_method = '';
722
                $domain = '';
723
                if ($invoice) {
724
                    $invoice_status = $invoice->status;
725
                    $items = $invoice->invoiceItem()->first();
726
                    if ($items) {
727
                        $domain = $items->domain;
728
                    }
729
                }
730
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
731
                if ($payment) {
732
                    $payment_status = $payment->payment_status;
733
                    $payment_method = $payment->payment_method;
734
                }
735
736
                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...
737
            }
738
739
            return redirect()->back();
740
        } catch (\Exception $ex) {
741
            Bugsnag::notifyException($ex);
742
743
            return redirect()->back()->with('fails', $ex->getMessage());
744
        }
745
    }
746
747
    public function findCostAfterDiscount($promoid, $productid, $currency)
748
    {
749
        try {
750
            $promotion = Promotion::findOrFail($promoid);
751
            $product = Product::findOrFail($productid);
752
            $promotion_type = $promotion->type;
753
            $promotion_value = $promotion->value;
754
            $planId = Plan::where('product', $productid)->pluck('id')->first();
755
            // dd($planId);
756
            $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...
757
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
758
759
            return $updated_price;
760
        } catch (\Exception $ex) {
761
            Bugsnag::notifyException($ex);
762
763
            throw new \Exception(\Lang::get('message.find-discount-error'));
764
        }
765
    }
766
767
    public function findCost($type, $value, $price, $productid)
768
    {
769
        switch ($type) {
770
                case 1:
771
                    $percentage = $price * ($value / 100);
772
773
                     return $price - $percentage;
774
                case 2:
775
                    return $price - $value;
776
                case 3:
777
                    return $value;
778
                case 4:
779
                    return 0;
780
            }
781
    }
782
783
    public function postRazorpayPayment($invoiceid, $grand_total)
784
    {
785
        try {
786
            $payment_method = 'Razorpay';
787
            $payment_status = 'success';
788
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
789
            $amount = $grand_total;
790
            $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...
791
792
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
793
        } catch (\Exception $ex) {
794
            return redirect()->back()->with('fails', $ex->getMessage());
795
        }
796
    }
797
798
    public function sendMail($userid, $invoiceid)
799
    {
800
        try {
801
            $invoice = $this->invoice->find($invoiceid);
802
            $number = $invoice->number;
803
            $total = $invoice->grand_total;
804
805
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
806
        } catch (\Exception $ex) {
807
            Bugsnag::notifyException($ex);
808
809
            throw new \Exception($ex->getMessage());
810
        }
811
    }
812
813
    public function deletePayment(Request $request)
814
    {
815
        try {
816
            $ids = $request->input('select');
817
            if (!empty($ids)) {
818
                foreach ($ids as $id) {
819
                    $payment = $this->payment->where('id', $id)->first();
820
                    if ($payment) {
821
                        $invoice = $this->invoice->find($payment->invoice_id);
822
                        if ($invoice) {
823
                            $invoice->status = 'pending';
824
                            $invoice->save();
825
                        }
826
                        $payment->delete();
827
                    } else {
828
                        echo "<div class='alert alert-danger alert-dismissable'>
829
                    <i class='fa fa-ban'></i>
830
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 153 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...
831
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
832
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
833
                </div>';
834
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
835
                    }
836
                }
837
                echo "<div class='alert alert-success alert-dismissable'>
838
                    <i class='fa fa-ban'></i>
839
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
840
                    \Lang::get('message.success').'
841
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
842
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
843
                </div>';
844
            } else {
845
                echo "<div class='alert alert-danger alert-dismissable'>
846
                    <i class='fa fa-ban'></i>
847
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
848
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
849
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
850
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
851
                </div>';
852
                //echo \Lang::get('message.select-a-row');
853
            }
854
        } catch (\Exception $e) {
855
            Bugsnag::notifyException($e);
856
            echo "<div class='alert alert-danger alert-dismissable'>
857
                    <i class='fa fa-ban'></i>
858
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
859
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
860
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
861
                        '.$e->getMessage().'
862
                </div>';
863
        }
864
    }
865
}
866