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