Completed
Push — development ( 138ffb...1fce93 )
by Ashutosh
09:58
created

InvoiceController::deleteTrasaction()   A

Complexity

Conditions 5
Paths 14

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

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