Completed
Push — development ( b3ab84...f1d660 )
by Ashutosh
22:33 queued 09:02
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' 
115
                            value=".$model->id.' name=select[] id=check>';
116
                        })
117
                        ->addColumn('user_id', function ($model) {
118
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
119
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
120
                            $id = $this->user->where('id', $model->user_id)->first()->id;
121
122
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
123
                        })
124
                         ->addColumn('number', function ($model) {
125
                             return ucfirst($model->number);
126
                         })
127
128
                        ->addColumn('date', function ($model) {
129
                            $date = date_create($model->created_at);
130
131
                            return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
132
                        })
133
                         ->addColumn('grand_total', function ($model) {
134
                             return ucfirst($model->number);
135
                         })
136
                          ->addColumn('status', function ($model) {
137
                              return ucfirst($model->status);
138
                          })
139
140
                        ->addColumn('action', function ($model) {
141
                            $action = '';
142
143
                            $check = $this->checkExecution($model->id);
144
                            if ($check == false) {
145
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)
146
                                ." class='btn btn-sm btn-primary btn-xs'>
147
                                <i class='fa fa-tasks' style='color:white;'>
148
                                 </i>&nbsp;&nbsp; Execute Order</a>";
149
                            }
150
151
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)
152
                            ." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' 
153
                            style='color:white;'> </i>&nbsp;&nbsp;View</a>"
154
                                    ."   $action";
155
                        })
156
157
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
158
                        ->make(true);
159
    }
160
161
    public function show(Request $request)
162
    {
163
        try {
164
            $id = $request->input('invoiceid');
165
            $invoice = $this->invoice->where('id', $id)->first();
166
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
167
            $user = $this->user->find($invoice->user_id);
168
169
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
170
        } catch (\Exception $ex) {
171
            Bugsnag::notifyException($ex);
172
173
            return redirect()->back()->with('fails', $ex->getMessage());
174
        }
175
    }
176
177
    /**
178
     * not in use case.
179
     *
180
     * @param Request $request
181
     *
182
     * @return type
183
     */
184
    public function generateById(Request $request)
185
    {
186
        try {
187
            $clientid = $request->input('clientid');
188
            if ($clientid) {
189
                $user = new User();
190
                $user = $user->where('id', $clientid)->first();
191
                if (!$user) {
192
                    return redirect()->back()->with('fails', 'Invalid user');
193
                }
194
            } else {
195
                $user = '';
196
            }
197
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
198
            $currency = $this->currency->pluck('name', 'code')->toArray();
199
200
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
201
        } catch (\Exception $ex) {
202
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
203
            app('log')->info($ex->getMessage());
204
            Bugsnag::notifyException($ex);
205
206
            return redirect()->back()->with('fails', $ex->getMessage());
207
        }
208
    }
209
210
    /*
211
    *Edit Invoice Total.
212
    */
213
    public function invoiceTotalChange(Request $request)
214
    {
215
        $total = $request->input('total');
216
        if ($total == '') {
217
            $total = 0;
218
        }
219
        $number = $request->input('number');
220
        $invoiceId = Invoice::where('number', $number)->value('id');
221
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
222
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
223
    }
224
225
    public function sendmailClientAgent($userid, $invoiceid)
226
    {
227
        try {
228
            $agent = \Input::get('agent');
229
            $client = \Input::get('client');
230
            if ($agent == 1) {
231
                $id = \Auth::user()->id;
232
                $this->sendMail($id, $invoiceid);
233
            }
234
            if ($client == 1) {
235
                $this->sendMail($userid, $invoiceid);
236
            }
237
        } catch (\Exception $ex) {
238
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
239
            app('log')->info($ex->getMessage());
240
            Bugsnag::notifyException($ex);
241
242
            throw new \Exception($ex->getMessage());
243
        }
244
    }
245
246
    /**
247
     * Generate invoice.
248
     *
249
     * @throws \Exception
250
     */
251
    public function generateInvoice()
252
    {
253
        try {
254
            // dd(\Cart::getContent());
255
            $tax_rule = new \App\Model\Payment\TaxOption();
256
            $rule = $tax_rule->findOrFail(1);
257
            $rounding = $rule->rounding;
258
259
            $user_id = \Auth::user()->id;
260
            if (\Auth::user()->currency == 'INR') {
261
                $grand_total = \Cart::getSubTotal();
262
            } else {
263
                foreach (\Cart::getContent() as $cart) {
264
265
                    // $grand_total = $cart->price;
266
                    $grand_total = \Cart::getSubTotal();
267
                }
268
            }
269
            // dd($grand_total);
270
271
            $number = rand(11111111, 99999999);
272
            $date = \Carbon\Carbon::now();
273
274
            if ($rounding == 1) {
275
                $grand_total = round($grand_total);
276
            }
277
            $content = \Cart::getContent();
278
            $attributes = [];
279
            foreach ($content as $key => $item) {
280
                $attributes[] = $item->attributes;
281
            }
282
283
            $symbol = $attributes[0]['currency'][0]['code'];
284
            //dd($symbol);
285
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number,
286
             'date'                                      => $date, 'grand_total' => $grand_total, 'status' => 'pending',
287
             'currency'                                  => $symbol, ]);
288
289
            foreach (\Cart::getContent() as $cart) {
290
                $this->createInvoiceItems($invoice->id, $cart);
291
            }
292
            //$this->sendMail($user_id, $invoice->id);
293
            return $invoice;
294
        } catch (\Exception $ex) {
295
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
296
            app('log')->info($ex->getMessage());
297
            Bugsnag::notifyException($ex);
298
299
            throw new \Exception('Can not Generate Invoice');
300
        }
301
    }
302
303
    public function createInvoiceItems($invoiceid, $cart)
304
    {
305
        try {
306
            $planid = 0;
307
            $product_name = $cart->name;
308
            $regular_price = $cart->price;
309
            $quantity = $cart->quantity;
310
            $domain = $this->domain($cart->id);
311
            $cart_cont = new \App\Http\Controllers\Front\CartController();
312
            if ($cart_cont->checkPlanSession() === true) {
313
                $planid = \Session::get('plan');
314
            }
315
            $user_currency = \Auth::user()->currency;
316
            $subtotal = $this->getSubtotal($user_currency, $cart);
317
318
            $tax_name = '';
319
            $tax_percentage = '';
320
321
            foreach ($cart->attributes['tax'] as $tax) {
322
                $tax_name .= $tax['name'].',';
323
                $tax_percentage .= $tax['rate'].',';
324
            }
325
326
            $invoiceItem = $this->invoiceItem->create([
327
                'invoice_id'     => $invoiceid,
328
                'product_name'   => $product_name,
329
                'regular_price'  => $regular_price,
330
                'quantity'       => $quantity,
331
                'tax_name'       => $tax_name,
332
                'tax_percentage' => $tax_percentage,
333
                'subtotal'       => $subtotal,
334
                'domain'         => $domain,
335
                'plan_id'        => $planid,
336
            ]);
337
338
            return $invoiceItem;
339
        } catch (\Exception $ex) {
340
            Bugsnag::notifyException($ex);
341
342
            throw new \Exception('Can not create Invoice Items');
343
        }
344
    }
345
346
347
    public function invoiceGenerateByForm(Request $request, $user_id = '')
348
    {
349
        $qty = 1;
350
351
        try {
352
            if ($user_id == '') {
353
                $user_id = \Request::input('user');
354
            }
355
            $productid = $request->input('product');
356
            $code = $request->input('code');
357
            $total = $request->input('price');
358
            $plan = $request->input('plan');
359
            $description = $request->input('description');
360
            if ($request->has('domain')) {
361
                $domain = $request->input('domain');
362
                $this->setDomain($productid, $domain);
363
            }
364
            $controller = new \App\Http\Controllers\Front\CartController();
365
            $currency = $controller->currency($user_id);
366
            $number = rand(11111111, 99999999);
367
            $date = \Carbon\Carbon::now();
368
            $product = Product::find($productid);
369
            $cost = $controller->cost($productid, $user_id, $plan);
370
            if ($cost != $total) {
371
                $grand_total = $total;
372
            }
373
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
374
            $grand_total = $qty * $grand_total;
375
376
            $tax = $this->checkTax($product->id, $user_id);
377
            $tax_name = '';
378
            $tax_rate = '';
379
            if (!empty($tax)) {
380
                $tax_name = $tax[0];
381
                $tax_rate = $tax[1];
382
            }
383
384
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
385
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
386
387
            $invoice = Invoice::create(['user_id' => $user_id,
388
                'number'   => $number, 'date' => $date, 'grand_total' => $grand_total,
389
                'currency' => $currency, 'status' => 'pending', 'description' => $description, ]);
390
391
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid,
392
             $code, $total, $currency, $qty, $plan, $user_id, $tax_name, $tax_rate);
393
            $result = $this->getMessage($items, $user_id);
394
        } catch (\Exception $ex) {
395
            app('log')->useDailyFiles(storage_path().'/laravel.log');
396
            app('log')->info($ex->getMessage());
397
            Bugsnag::notifyException($ex);
398
            $result = ['fails' => $ex->getMessage()];
399
        }
400
401
        return response()->json(compact('result'));
402
    }
403
404
    public function doPayment($payment_method, $invoiceid, $amount,
405
        $parent_id = '', $userid = '', $payment_status = 'pending')
406
    {
407
        try {
408
            if ($amount > 0) {
409
                if ($userid == '') {
410
                    $userid = \Auth::user()->id;
411
                }
412
                if ($amount == 0) {
413
                    $payment_status = 'success';
414
                }
415
                $this->payment->create([
416
                    'parent_id'      => $parent_id,
417
                    'invoice_id'     => $invoiceid,
418
                    'user_id'        => $userid,
419
                    'amount'         => $amount,
420
                    'payment_method' => $payment_method,
421
                    'payment_status' => $payment_status,
422
                ]);
423
                $this->updateInvoice($invoiceid);
424
            }
425
        } catch (\Exception $ex) {
426
            Bugsnag::notifyException($ex);
427
428
            throw new \Exception($ex->getMessage());
429
        }
430
    }
431
432
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price,
433
        $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
434
    {
435
        try {
436
            $discount = '';
437
            $mode = '';
438
            $product = $this->product->findOrFail($productid);
439
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
440
            $price = $this->getPrice($price, $price_model);
441
            $subtotal = $qty * $price;
442
            //dd($subtotal);
443
            if ($code) {
444
                $subtotal = $this->checkCode($code, $productid, $currency);
445
                $mode = 'coupon';
446
                $discount = $price - $subtotal;
447
            }
448
            $userid = \Auth::user()->id;
449
            if (\Auth::user()->role == 'user') {
450
                $tax = $this->checkTax($product->id, $userid);
451
                $tax_name = '';
452
                $tax_rate = '';
453
                if (!empty($tax)) {
454
455
                    //dd($value);
456
                    $tax_name = $tax[0];
457
                    $tax_rate = $tax[1];
458
                }
459
            }
460
461
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
462
463
            $domain = $this->domain($productid);
464
            $items = $this->invoiceItem->create([
465
                'invoice_id'     => $invoiceid,
466
                'product_name'   => $product->name,
467
                'regular_price'  => $price,
468
                'quantity'       => $qty,
469
                'discount'       => $discount,
470
                'discount_mode'  => $mode,
471
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
472
                'tax_name'       => $tax_name,
473
                'tax_percentage' => $tax_rate,
474
                'domain'         => $domain,
475
                'plan_id'        => $planid,
476
            ]);
477
478
            return $items;
479
        } catch (\Exception $ex) {
480
            Bugsnag::notifyException($ex);
481
482
            return redirect()->back()->with('fails', $ex->getMessage());
483
        }
484
    }
485
486
    public function checkCode($code, $productid, $currency)
487
    {
488
        try {
489
            if ($code != '') {
490
                $promo = $this->promotion->where('code', $code)->first();
491
                //check promotion code is valid
492
                if (!$promo) {
493
                    throw new \Exception(\Lang::get('message.no-such-code'));
494
                }
495
                $relation = $promo->relation()->get();
496
                //check the relation between code and product
497
                if (count($relation) == 0) {
498
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
499
                }
500
                //check the usess
501
                $cont = new \App\Http\Controllers\Payment\PromotionController();
502
                $uses = $cont->checkNumberOfUses($code);
503
                if ($uses != 'success') {
504
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
505
                }
506
                //check for the expiry date
507
                $expiry = $this->checkExpiry($code);
508
                if ($expiry != 'success') {
509
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
510
                }
511
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
512
513
                return $value;
514
            } else {
515
                $product = $this->product->find($productid);
516
                $plans = Plan::where('product', $product)->pluck('id')->first();
517
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
518
519
                return $price;
520
            }
521
        } catch (\Exception $ex) {
522
            throw new \Exception($ex->getMessage());
523
        }
524
    }
525
526
    public function checkTax($productid, $userid)
527
    {
528
        try {
529
            $taxs = [];
530
            $taxs[0] = ['name' => 'null', 'rate' => 0];
531
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
532
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
533
            $product = $this->product->findOrFail($productid);
534
            $cartController = new CartController();
535
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
536
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
537
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
538
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
539
540
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
541
                     ->pluck('tax_classes_id')->first(); //In case of India when
542
                    //other tax is available and tax is not enabled
543
                    if ($taxClassId) {
544
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
545
                        $taxs = $rate['taxes'];
546
                        $rate = $rate['rate'];
547
                    } elseif ($geoip_country != 'IN') {//In case of other country
548
                        // when tax is available and tax is not enabled(Applicable
549
                        //when Global Tax class for any country and state is not there)
550
551
                        $taxClassId = Tax::where('state', $geoip_state)
552
                        ->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
553
                        if ($taxClassId) { //if state equals the user State
554
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
555
                            $taxs = $rate['taxes'];
556
                            $rate = $rate['rate'];
557
                        }
558
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
559
560
                        return $taxs;
561
                    }
562
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
563
                } else {
564
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
565
                }
566
            }
567
568
            return $taxs;
569
        } catch (\Exception $ex) {
570
            throw new \Exception(\Lang::get('message.check-tax-error'));
571
        }
572
    }
573
574
    public function getRate($productid, $taxs, $userid)
575
    {
576
        $tax_attribute = [];
577
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
578
        $tax_value = '0';
579
580
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
581
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
582
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
583
        $origin_state = $this->setting->first()->state; //Get the State of origin
584
        $cartController = new CartController();
585
586
        $rate = 0;
587
        $name1 = 'CGST';
588
        $name2 = 'SGST';
589
        $name3 = 'IGST';
590
        $name4 = 'UTGST';
591
        $c_gst = 0;
592
        $s_gst = 0;
593
        $i_gst = 0;
594
        $ut_gst = 0;
595
        $state_code = '';
596
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
597
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
598
            $taxes = $tax['taxes'];
599
            $value = $tax['value'];
600
        } else {//If user from other Country
601
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
602
            $taxes = $tax['taxes'];
603
            $value = $tax['value'];
604
            $rate = $tax['rate'];
605
        }
606
607
        foreach ($taxes as $key => $tax) {
608
            if ($taxes[0]) {
609
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1,
610
                 'name2'                       => $name2, 'name3' => $name3, 'name4' => $name4,
611
                 'rate'                        => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst,
612
                 'rate3'                       => $i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code,
613
                  'origin_state'               => $origin_state, ];
614
615
                $rate = $tax->rate;
616
617
                $tax_value = $value;
618
            } else {
619
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
620
                $tax_value = '0%';
621
            }
622
        }
623
624
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
625
    }
626
627
    /**
628
     * Remove the specified resource from storage.
629
     *
630
     * @param int $id
631
     *
632
     * @return \Response
633
     */
634
    public function destroy(Request $request)
635
    {
636
        try {
637
            $ids = $request->input('select');
638
            if (!empty($ids)) {
639
                foreach ($ids as $id) {
640
                    $invoice = $this->invoice->where('id', $id)->first();
641
                    if ($invoice) {
642
                        $invoice->delete();
643
                    } else {
644
                        echo "<div class='alert alert-danger alert-dismissable'>
645
                    <i class='fa fa-ban'></i>
646
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
647
                    /* @scrutinizer ignore-type */
648
                    \Lang::get('message.failed').'
649
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
650
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
651
                </div>';
652
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
653
                    }
654
                }
655
                echo "<div class='alert alert-success alert-dismissable'>
656
                    <i class='fa fa-ban'></i>
657
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
658
                    /* @scrutinizer ignore-type */
659
                    \Lang::get('message.success').'
660
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
661
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
662
                </div>';
663
            } else {
664
                echo "<div class='alert alert-danger alert-dismissable'>
665
                    <i class='fa fa-ban'></i>
666
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
667
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
668
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
669
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
670
                </div>';
671
                //echo \Lang::get('message.select-a-row');
672
            }
673
        } catch (\Exception $e) {
674
            echo "<div class='alert alert-danger alert-dismissable'>
675
                    <i class='fa fa-ban'></i>
676
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
677
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
678
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
679
                        '.$e->getMessage().'
680
                </div>';
681
        }
682
    }
683
684
    public function updateInvoice($invoiceid)
685
    {
686
        try {
687
            $invoice = $this->invoice->findOrFail($invoiceid);
688
            $payment = $this->payment->where('invoice_id', $invoiceid)
689
            ->where('payment_status', 'success')->pluck('amount')->toArray();
690
            $total = array_sum($payment);
691
            if ($total < $invoice->grand_total) {
692
                $invoice->status = 'pending';
693
            }
694
            if ($total >= $invoice->grand_total) {
695
                $invoice->status = 'success';
696
            }
697
            if ($total > $invoice->grand_total) {
698
                $user = $invoice->user()->first();
699
                $balance = $total - $invoice->grand_total;
700
                $user->debit = $balance;
701
                $user->save();
702
            }
703
704
            $invoice->save();
705
        } catch (\Exception $ex) {
706
            Bugsnag::notifyException($ex);
707
708
            throw new \Exception($ex->getMessage());
709
        }
710
    }
711
712
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
713
    {
714
        try {
715
            $invoice = $this->invoice->find($invoiceid);
716
            $invoice_status = 'pending';
717
718
            $payment = $this->payment->create([
719
                'invoice_id'     => $invoiceid,
720
                'user_id'        => $invoice->user_id,
721
                'amount'         => $amount,
722
                'payment_method' => $payment_method,
723
                'payment_status' => $payment_status,
724
                'created_at'     => $payment_date,
725
            ]);
726
            $all_payments = $this->payment
727
            ->where('invoice_id', $invoiceid)
728
            ->where('payment_status', 'success')
729
            ->pluck('amount')->toArray();
730
            $total_paid = array_sum($all_payments);
731
            if ($total_paid >= $invoice->grand_total) {
732
                $invoice_status = 'success';
733
            }
734
            if ($invoice) {
735
                $invoice->status = $invoice_status;
736
                $invoice->save();
737
            }
738
739
            return $payment;
740
        } catch (\Exception $ex) {
741
            Bugsnag::notifyException($ex);
742
743
            throw new \Exception($ex->getMessage());
744
        }
745
    }
746
747
    public function pdf(Request $request)
748
    {
749
        try {
750
            $id = $request->input('invoiceid');
751
            if (!$id) {
752
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
753
            }
754
            $invoice = $this->invoice->where('id', $id)->first();
755
            if (!$invoice) {
756
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
757
            }
758
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
759
            if ($invoiceItems->count() == 0) {
760
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
761
            }
762
            $user = $this->user->find($invoice->user_id);
763
            if (!$user) {
764
                return redirect()->back()->with('fails', 'No User');
765
            }
766
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
767
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
768
769
            return $pdf->download($user->first_name.'-invoice.pdf');
770
        } catch (\Exception $ex) {
771
            Bugsnag::notifyException($ex);
772
773
            return redirect()->back()->with('fails', $ex->getMessage());
774
        }
775
    }
776
777
    public function getExpiryStatus($start, $end, $now)
778
    {
779
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
780
        if ($whenDateNotSet) {
781
            return $whenDateNotSet;
782
        }
783
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
784
        if ($whenStartDateSet) {
785
            return $whenStartDateSet;
786
        }
787
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
788
        if ($whenEndDateSet) {
789
            return $whenEndDateSet;
790
        }
791
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
792
        if ($whenBothAreSet) {
793
            return $whenBothAreSet;
794
        }
795
    }
796
797
    public function payment(Request $request)
798
    {
799
        try {
800
            if ($request->has('invoiceid')) {
801
                $invoice_id = $request->input('invoiceid');
802
                $invoice = $this->invoice->find($invoice_id);
803
                //dd($invoice);
804
                $invoice_status = '';
805
                $payment_status = '';
806
                $payment_method = '';
807
                $domain = '';
808
                if ($invoice) {
809
                    $invoice_status = $invoice->status;
810
                    $items = $invoice->invoiceItem()->first();
811
                    if ($items) {
812
                        $domain = $items->domain;
813
                    }
814
                }
815
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
816
                if ($payment) {
817
                    $payment_status = $payment->payment_status;
818
                    $payment_method = $payment->payment_method;
819
                }
820
821
                return view('themes.default1.invoice.payment',
822
                 compact('invoice_status', 'payment_status',
823
                  'payment_method', 'invoice_id', 'domain', 'invoice'));
824
            }
825
826
            return redirect()->back();
827
        } catch (\Exception $ex) {
828
            Bugsnag::notifyException($ex);
829
830
            return redirect()->back()->with('fails', $ex->getMessage());
831
        }
832
    }
833
834
    public function findCostAfterDiscount($promoid, $productid, $currency)
835
    {
836
        try {
837
            $promotion = Promotion::findOrFail($promoid);
838
            $product = Product::findOrFail($productid);
839
            $promotion_type = $promotion->type;
840
            $promotion_value = $promotion->value;
841
            $planId = Plan::where('product', $productid)->pluck('id')->first();
842
            // dd($planId);
843
            $product_price = PlanPrice::where('plan_id', $planId)
844
            ->where('currency', $currency)->pluck('add_price')->first();
845
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
846
847
            return $updated_price;
848
        } catch (\Exception $ex) {
849
            Bugsnag::notifyException($ex);
850
851
            throw new \Exception(\Lang::get('message.find-discount-error'));
852
        }
853
    }
854
855
    public function findCost($type, $value, $price, $productid)
856
    {
857
        switch ($type) {
858
                case 1:
859
                    $percentage = $price * ($value / 100);
860
861
                     return $price - $percentage;
862
                case 2:
863
                    return $price - $value;
864
                case 3:
865
                    return $value;
866
                case 4:
867
                    return 0;
868
            }
869
    }
870
871
    public function setDomain($productid, $domain)
872
    {
873
        try {
874
            if (\Session::has('domain'.$productid)) {
875
                \Session::forget('domain'.$productid);
876
            }
877
            \Session::put('domain'.$productid, $domain);
878
        } catch (\Exception $ex) {
879
            Bugsnag::notifyException($ex);
880
881
            throw new \Exception($ex->getMessage());
882
        }
883
    }
884
885
    public function postRazorpayPayment($invoiceid, $grand_total)
886
    {
887
        try {
888
            $payment_method = 'Razorpay';
889
            $payment_status = 'success';
890
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
891
            $amount = $grand_total;
892
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method,
893
             $payment_status, $payment_date, $amount);
894
895
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
896
        } catch (\Exception $ex) {
897
            return redirect()->back()->with('fails', $ex->getMessage());
898
        }
899
    }
900
901
    public function sendMail($userid, $invoiceid)
902
    {
903
        try {
904
            $invoice = $this->invoice->find($invoiceid);
905
            $number = $invoice->number;
906
            $total = $invoice->grand_total;
907
908
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
909
        } catch (\Exception $ex) {
910
            Bugsnag::notifyException($ex);
911
912
            throw new \Exception($ex->getMessage());
913
        }
914
    }
915
916
    public function deletePayment(Request $request)
917
    {
918
        try {
919
            $ids = $request->input('select');
920
            if (!empty($ids)) {
921
                foreach ($ids as $id) {
922
                    $payment = $this->payment->where('id', $id)->first();
923
                    if ($payment) {
924
                        $invoice = $this->invoice->find($payment->invoice_id);
925
                        if ($invoice) {
926
                            $invoice->status = 'pending';
927
                            $invoice->save();
928
                        }
929
                        $payment->delete();
930
                    } else {
931
                        echo "<div class='alert alert-danger alert-dismissable'>
932
                    <i class='fa fa-ban'></i>
933
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
934
                    './* @scrutinizer ignore-type */\Lang::get('message.failed').'
935
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
936
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
937
                </div>';
938
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
939
                    }
940
                }
941
                echo "<div class='alert alert-success alert-dismissable'>
942
                    <i class='fa fa-ban'></i>
943
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
944
                    /* @scrutinizer ignore-type */
945
                    \Lang::get('message.success').'
946
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
947
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
948
                </div>';
949
            } else {
950
                echo "<div class='alert alert-danger alert-dismissable'>
951
                    <i class='fa fa-ban'></i>
952
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
953
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
954
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
955
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
956
                </div>';
957
                //echo \Lang::get('message.select-a-row');
958
            }
959
        } catch (\Exception $e) {
960
            Bugsnag::notifyException($e);
961
            echo "<div class='alert alert-danger alert-dismissable'>
962
                    <i class='fa fa-ban'></i>
963
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
964
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
965
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
966
                        '.$e->getMessage().'
967
                </div>';
968
        }
969
    }
970
}
971