Completed
Push — master ( c9d136...013c3e )
by vijay
119:15 queued 59:12
created

InvoiceController::generateById()   B

Complexity

Conditions 4
Paths 13

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 4 Features 0
Metric Value
cc 4
eloc 15
c 8
b 4
f 0
nc 13
nop 1
dl 0
loc 22
rs 8.9197
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Common\TemplateController;
6
use App\Http\Controllers\Controller;
7
use App\Model\Common\Setting;
8
use App\Model\Common\Template;
9
use App\Model\Order\Invoice;
10
use App\Model\Order\InvoiceItem;
11
use App\Model\Order\Payment;
12
use App\Model\Payment\Currency;
13
use App\Model\Payment\Promotion;
14
use App\Model\Payment\Tax;
15
use App\Model\Payment\TaxOption;
16
use App\Model\Product\Price;
17
//use Symfony\Component\HttpFoundation\Request as Requests;
18
use App\Model\Product\Product;
19
use App\User;
20
use Illuminate\Http\Request;
21
use Input;
22
23
class InvoiceController extends Controller
24
{
25
    public $invoice;
26
    public $invoiceItem;
27
    public $user;
28
    public $template;
29
    public $setting;
30
    public $payment;
31
    public $product;
32
    public $price;
33
    public $promotion;
34
    public $currency;
35
    public $tax;
36
    public $tax_option;
37
38 View Code Duplication
    public function __construct()
39
    {
40
        $this->middleware('auth');
41
//        $this->middleware('admin');
42
43
        $invoice = new Invoice();
44
        $this->invoice = $invoice;
45
46
        $invoiceItem = new InvoiceItem();
47
        $this->invoiceItem = $invoiceItem;
48
49
        $user = new User();
50
        $this->user = $user;
51
52
        $template = new Template();
53
        $this->template = $template;
54
55
        $seting = new Setting();
56
        $this->setting = $seting;
57
58
        $payment = new Payment();
59
        $this->payment = $payment;
60
61
        $product = new Product();
62
        $this->product = $product;
63
64
        $price = new Price();
65
        $this->price = $price;
66
67
        $promotion = new Promotion();
68
        $this->promotion = $promotion;
69
70
        $currency = new Currency();
71
        $this->currency = $currency;
72
73
        $tax = new Tax();
74
        $this->tax = $tax;
75
76
        $tax_option = new TaxOption();
77
        $this->tax_option = $tax_option;
78
    }
79
80
    public function index()
81
    {
82
        try {
83
            //dd($this->invoice->get());
84
            return view('themes.default1.invoice.index');
85
        } catch (\Exception $ex) {
86
            return redirect()->back()->with('fails', $ex->getMessage());
87
        }
88
    }
89
90
    public function GetInvoices()
91
    {
92
        //dd($this->invoice->get());
93
        //$invoice = \DB::table('invoices');
94
        return \Datatable::query($this->invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at'))
95
                        ->addColumn('#', function ($model) {
96
                            return "<input type='checkbox' value=".$model->id.' name=select[] id=check>';
97
                        })
98
                        ->addColumn('user_id', function ($model) {
99
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
100
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
101
                            $id = $this->user->where('id', $model->user_id)->first()->id;
102
103
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
104
                        })
105
                        ->showColumns('number', 'created_at', 'grand_total', 'status')
106
                        ->addColumn('action', function ($model) {
107
                            $order = \App\Model\Order\Order::where('invoice_id', $model->id)->first();
108
                            if (!$order) {
109
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)." class='btn btn-sm btn-primary'>Execute Order</a>";
110
                            } else {
111
                                $action = '';
112
                            }
113
114
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)." class='btn btn-sm btn-primary'>View</a>"
115
                                    ."   $action";
116
                        })
117
                        ->searchColumns('created_at', 'user_id', 'number', 'grand_total', 'status')
118
                        ->orderColumns('created_at', 'user_id', 'number', 'grand_total', 'status')
119
                        ->make();
120
    }
121
122
    public function show(Request $request)
123
    {
124
        try {
125
            $id = $request->input('invoiceid');
126
            $invoice = $this->invoice->where('id', $id)->first();
127
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
128
            $user = $this->user->find($invoice->user_id);
129
130
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
131
        } catch (\Exception $ex) {
132
            return redirect()->back()->with('fails', $ex->getMessage());
133
        }
134
    }
135
136
    /**
137
     * not in use case.
138
     *
139
     * @param Request $request
140
     *
141
     * @return type
142
     */
143
    public function generateById(Request $request)
144
    {
145
        try {
146
            $clientid = $request->input('clientid');
147
            //dd($clientid);
148
            if ($clientid) {
149
                $user = new User();
150
                $user = $user->where('id', $clientid)->first();
151
                if (!$user) {
152
                    return redirect()->back()->with('fails', 'Invalid user');
153
                }
154
            } else {
155
                $user = '';
156
            }
157
            $products = $this->product->lists('name', 'id')->toArray();
158
            $currency = $this->currency->lists('name', 'code')->toArray();
159
160
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
161
        } catch (\Exception $ex) {
162
            return redirect()->back()->with('fails', $ex->getMessage());
163
        }
164
    }
165
166
    public function invoiceGenerateByForm(Request $request, $user_id = '')
167
    {
168
        $qty = 1;
169
        if (array_key_exists('domain', $request->all())) {
170
            $this->validate($request, [
171
                'domain' => 'required|url',
172
            ]);
173
        }
174
        if (array_key_exists('quantity', $request->all())) {
175
            $this->validate($request, [
176
                'quantity' => 'required|integer',
177
            ]);
178
            $qty = $request->input('quantity');
179
        }
180
181
        $this->validate($request, [
182
            'product' => 'required',
183
        ]);
184
        try {
185
            if ($user_id == '') {
186
                $user_id = \Input::get('user');
187
            }
188
189
            $productid = Input::get('product');
190
            $code = Input::get('code');
191
            $total = Input::get('price');
192
            if ($request->has('domain')) {
193
                $domain = $request->input('domain');
194
                $this->setDomain($productid, $domain);
195
            }
196
            $currency = $this->user->find($user_id)->currency;
197
            if (!$currency) {
198
                $currency = 'USD';
199
            }
200
            if ($currency == 1) {
201
                $currency = 'USD';
202
            } else {
203
                $currency = 'INR';
204
            }
205
            $number = rand(11111111, 99999999);
206
            $date = \Carbon\Carbon::now();
207
            $product = $this->product->findOrFail($productid);
208
            $price = $product->price()->where('currency', $currency)->first();
209
            //dd($price);
210
            $cost = $price->sales_price;
211
            if (!$cost) {
212
                $cost = $price->price;
213
            }
214
            if ($cost != $total) {
215
                $grand_total = $total;
216
            }
217
            //dd($cost);
218
            if ($code) {
219
                $grand_total = $this->checkCode($code, $productid);
220
                //dd($grand_total);
221
            } else {
222
                if (!$total) {
223
                    $grand_total = $cost;
224
                } else {
225
                    $grand_total = $total;
226
                }
227
            }
228
            $grand_total = $qty * $grand_total;
229
            //dd($grand_total);
230
            $tax = $this->checkTax($product->id);
231
            //dd($tax);
232
            $tax_name = '';
233
            $tax_rate = '';
234 View Code Duplication
            if (!empty($tax)) {
235
                foreach ($tax as $key => $value) {
236
                    //dd($value);
237
                    $tax_name .= $value['name'].',';
238
                    $tax_rate .= $value['rate'].',';
239
                }
240
            }
241
            //dd('dsjcgv');
242
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
243
244
            //dd($grand_total);
245
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
246
247
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'currency' => $currency, 'status' => 'pending']);
248
            if ($grand_total > 0) {
249
                $this->doPayment('online payment', $invoice->id, $grand_total, '', $user_id);
250
            }
251
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid, $code, $total, $currency, $qty);
252
            if ($items) {
253
                $this->sendmailClientAgent($user_id, $items->invoice_id);
254
                $result = ['success' => \Lang::get('message.invoice-generated-successfully')];
255
            } else {
256
                $result = ['fails' => \Lang::get('message.can-not-generate-invoice')];
257
            }
258
        } catch (\Exception $ex) {
259
            $result = ['fails' => $ex->getMessage()];
260
        }
261
262
        return response()->json(compact('result'));
263
    }
264
265
    public function sendmailClientAgent($userid, $invoiceid)
266
    {
267
        try {
268
            $agent = \Input::get('agent');
269
            $client = \Input::get('client');
270
            if ($agent == 1) {
271
                $id = \Auth::user()->id;
272
                $this->sendMail($id, $invoiceid);
273
            }
274
            if ($client == 1) {
275
                $this->sendMail($userid, $invoiceid);
276
            }
277
        } catch (\Exception $ex) {
278
            throw new \Exception($ex->getMessage());
279
        }
280
    }
281
282
    /**
283
     * Generate invoice.
284
     *
285
     * @throws \Exception
286
     */
287
    public function GenerateInvoice()
288
    {
289
        try {
290
            $tax_rule = new \App\Model\Payment\TaxOption();
291
            $rule = $tax_rule->findOrFail(1);
292
            $rounding = $rule->rounding;
293
294
            $user_id = \Auth::user()->id;
295
            $grand_total = \Cart::getSubTotal();
296
297
            $number = rand(11111111, 99999999);
298
            $date = \Carbon\Carbon::now();
299
300
            if ($rounding == 1) {
301
                $grand_total = round($grand_total);
302
            }
303
            $content = \Cart::getContent();
304
            $attributes = [];
305
            foreach ($content as $key => $item) {
306
                $attributes[] = $item->attributes;
307
            }
308
            $symbol = $attributes[0]['currency'][0]['code'];
309
            //dd($symbol);
310
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
311
312
            foreach (\Cart::getContent() as $cart) {
313
                $this->createInvoiceItems($invoice->id, $cart);
314
            }
315
316
            return $invoice;
317
        } catch (\Exception $ex) {
318
            dd($ex);
319
            throw new \Exception('Can not Generate Invoice');
320
        }
321
    }
322
323
    public function createInvoiceItems($invoiceid, $cart)
324
    {
325
        try {
326
            $product_name = $cart->name;
327
            $regular_price = $cart->price;
328
            $quantity = $cart->quantity;
329
            $domain = $this->domain($cart->id);
330
            //dd($quantity);
331
            $subtotal = \App\Http\Controllers\Front\CartController::rounding($cart->getPriceSumWithConditions());
332
333
            $tax_name = '';
334
            $tax_percentage = '';
335
336
            foreach ($cart->attributes['tax'] as $tax) {
337
                //dd($tax['name']);
338
                $tax_name .= $tax['name'].',';
339
                $tax_percentage .= $tax['rate'].',';
340
            }
341
342
//            dd($tax_name);
343
344
            $invoiceItem = $this->invoiceItem->create([
345
                'invoice_id'     => $invoiceid,
346
                'product_name'   => $product_name,
347
                'regular_price'  => $regular_price,
348
                'quantity'       => $quantity,
349
                'tax_name'       => $tax_name,
350
                'tax_percentage' => $tax_percentage,
351
                'subtotal'       => $subtotal,
352
                'domain'         => $domain,
353
            ]);
354
355
            return $invoiceItem;
356
        } catch (\Exception $ex) {
357
            dd($ex);
358
            throw new \Exception('Can not create Invoice Items');
359
        }
360
    }
361
362
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
363
    {
364
        try {
365
            if ($amount > 0) {
366
                if ($userid == '') {
367
                    $userid = \Auth::user()->id;
368
                }
369
                if ($amount == 0) {
370
                    $payment_status = 'success';
371
                }
372
                $this->payment->create([
373
                    'parent_id'      => $parent_id,
374
                    'invoice_id'     => $invoiceid,
375
                    'user_id'        => $userid,
376
                    'amount'         => $amount,
377
                    'payment_method' => $payment_method,
378
                    'payment_status' => $payment_status,
379
                ]);
380
                $this->updateInvoice($invoiceid);
381
            }
382
        } catch (\Exception $ex) {
383
            throw new \Exception($ex->getMessage());
384
        }
385
    }
386
387
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price, $currency, $qty)
388
    {
389
        try {
390
            $discount = '';
391
            $mode = '';
392
            $product = $this->product->findOrFail($productid);
393
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
394
            if ($price == '') {
395
                $price = $price_model->sales_price;
396
                if (!$price) {
397
                    $price = $price_model->price;
398
                }
399
            }
400
            $subtotal = $qty * $price;
401
            //dd($subtotal);
402
            if ($code) {
403
                $subtotal = $this->checkCode($code, $productid);
404
                $mode = 'coupon';
405
                $discount = $price - $subtotal;
406
            }
407
            $tax = $this->checkTax($product->id);
408
            //dd($tax);
409
            $tax_name = '';
410
            $tax_rate = '';
411 View Code Duplication
            if (!empty($tax)) {
412
                foreach ($tax as $key => $value) {
413
                    //dd($value);
414
                    $tax_name .= $value['name'].',';
415
                    $tax_rate .= $value['rate'].',';
416
                }
417
            }
418
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
419
            $domain = $this->domain($productid);
420
            $items = $this->invoiceItem->create([
421
                'invoice_id'     => $invoiceid,
422
                'product_name'   => $product->name,
423
                'regular_price'  => $price,
424
                'quantity'       => $qty,
425
                'discount'       => $discount,
426
                'discount_mode'  => $mode,
427
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
428
                'tax_name'       => $tax_name,
429
                'tax_percentage' => $tax_rate,
430
                'domain'         => $domain,
431
            ]);
432
433
            return $items;
434
        } catch (\Exception $ex) {
435
            dd($ex);
436
437
            return redirect()->back()->with('fails', $ex->getMessage());
438
        }
439
    }
440
441
    public function checkCode($code, $productid)
442
    {
443
        try {
444
            if ($code != '') {
445
                $promo = $this->promotion->where('code', $code)->first();
446
                //check promotion code is valid
447
                if (!$promo) {
448
                    throw new \Exception(\Lang::get('message.no-such-code'));
449
                }
450
                $relation = $promo->relation()->get();
451
                //check the relation between code and product
452
                if (count($relation) == 0) {
453
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
454
                }
455
                //check the usess
456
                $uses = $this->checkNumberOfUses($code);
457
                //dd($uses);
458
                if ($uses != 'success') {
459
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
460
                }
461
                //check for the expiry date
462
                $expiry = $this->checkExpiry($code);
463
                //dd($expiry);
464
                if ($expiry != 'success') {
465
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
466
                }
467
                $value = $this->findCostAfterDiscount($promo->id, $productid);
468
469
                return $value;
470
            } else {
471
                $product = $this->product->find($productid);
472
                $price = $product->price()->sales_price;
473
                if (!$price) {
474
                    $price = $product->price()->price;
475
                }
476
477
                return $price;
478
            }
479
        } catch (\Exception $ex) {
480
            dd($ex);
481
            throw new \Exception(\Lang::get('message.check-code-error'));
482
        }
483
    }
484
485 View Code Duplication
    public function findCostAfterDiscount($promoid, $productid)
486
    {
487
        try {
488
            $promotion = $this->promotion->findOrFail($promoid);
489
            $product = $this->product->findOrFail($productid);
490
            $promotion_type = $promotion->type;
491
            $promotion_value = $promotion->value;
492
            $product_price = $product->price()->first()->sales_price;
493
            if (!$product_price) {
494
                $product_price = $product->price()->first()->price;
495
            }
496
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
497
498
            return $updated_price;
499
        } catch (\Exception $ex) {
500
            throw new \Exception(\Lang::get('message.find-discount-error'));
501
        }
502
    }
503
504
    public function findCost($type, $value, $price, $productid)
505
    {
506
        try {
507
            switch ($type) {
508
509
                case 1:
510
                    $percentage = $price * ($value / 100);
511
512
                    return $price - $percentage;
513
                case 2:
514
                    return $price - $value;
515
                case 3:
516
                    return $value;
517
                case 4:
518
                    return 0;
519
            }
520
        } catch (\Exception $ex) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $ex) {...e.find-cost-error')); } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
521
            throw new \Exception(\Lang::get('message.find-cost-error'));
522
        }
523
    }
524
525 View Code Duplication
    public function checkNumberOfUses($code)
526
    {
527
        try {
528
            $promotion = $this->promotion->where('code', $code)->first();
529
            $uses = $promotion->uses;
530
            if ($uses == 0) {
531
                return 'success';
532
            }
533
            $used_number = $this->invoice->where('coupon_code', $code)->count();
534
            if ($uses >= $used_number) {
535
                return 'success';
536
            } else {
537
                return 'fails';
538
            }
539
        } catch (\Exception $ex) {
540
            throw new \Exception(\Lang::get('message.find-cost-error'));
541
        }
542
    }
543
544 View Code Duplication
    public function checkExpiry($code = '')
545
    {
546
        try {
547
            if ($code != '') {
548
                $promotion = $this->promotion->where('code', $code)->first();
549
                $start = $promotion->start;
550
                $end = $promotion->expiry;
551
                //dd($end);
552
                $now = \Carbon\Carbon::now();
553
                //both not set, always true
554
                if (($start == null || $start == '0000-00-00 00:00:00') && ($end == null || $end == '0000-00-00 00:00:00')) {
555
                    return 'success';
556
                }
557
                //only starting date set, check the date is less or equel to today
558
                if (($start != null || $start != '0000-00-00 00:00:00') && ($end == null || $end == '0000-00-00 00:00:00')) {
559
                    if ($start <= $now) {
560
                        return 'success';
561
                    }
562
                }
563
                //only ending date set, check the date is greater or equel to today
564
                if (($end != null || $end != '0000-00-00 00:00:00') && ($start == null || $start == '0000-00-00 00:00:00')) {
565
                    if ($end >= $now) {
566
                        return 'success';
567
                    }
568
                }
569
                //both set
570
                if (($end != null || $start != '0000-00-00 00:00:00') && ($start != null || $start != '0000-00-00 00:00:00')) {
571
                    if ($end >= $now && $start <= $now) {
572
                        return 'success';
573
                    }
574
                }
575
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
576
            }
577
        } catch (\Exception $ex) {
578
            dd($ex);
579
            throw new \Exception(\Lang::get('message.check-expiry'));
580
        }
581
    }
582
583
    public function checkTax($productid)
584
    {
585
        try {
586
            //dd($productid);
587
            $taxs[0] = ['name' => 'null', 'rate' => 0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$taxs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $taxs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
588
            $product = $this->product->findOrFail($productid);
589
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
590
                if ($product->tax()->first()) {
591
                    $tax_class_id = $product->tax()->first()->tax_class_id;
592
                } else {
593
                    return $taxs;
594
                }
595
596
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
597
                    $cart_controller = new \App\Http\Controllers\Front\CartController();
598
                    $taxes = $cart_controller->getTaxByPriority($tax_class_id);
599
600
                    foreach ($taxes as $key => $tax) {
601
                        //dd($tax);
602
                        if ($tax->compound == 1) {
603
                            $taxs[$key] = ['name' => $tax->name, 'rate' => $tax->rate];
604
                        } else {
605
                            $rate = '';
606
                            $rate += $tax->rate;
607
                            $taxs[$key] = ['name' => $tax->name, 'rate' => $rate];
608
                        }
609
                    }
610
                }
611
            }
612
            //dd($taxs);
613
            return $taxs;
614
        } catch (\Exception $ex) {
615
            dd($ex);
616
            throw new \Exception(\Lang::get('message.check-tax-error'));
617
        }
618
    }
619
620
    public function pdf(Request $request)
621
    {
622
        try {
623
            $id = $request->input('invoiceid');
624
            if (!$id) {
625
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
626
            }
627
            $invoice = $this->invoice->where('id', $id)->first();
628
            if (!$invoice) {
629
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
630
            }
631
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
632
            $user = $this->user->find($invoice->user_id);
633
            //return view('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
634
            $pdf = \PDF::loadView('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
635
636
            return $pdf->download($user->first_name.'-invoice.pdf');
637
        } catch (\Exception $ex) {
638
            return redirect()->back()->with('fails', $ex->getMessage());
639
        }
640
    }
641
642
    public function calculateTotal($rate, $total)
643
    {
644
        try {
645
            //dd($total);
646
            $rates = explode(',', $rate);
647
            //dd($rates);
648
//            $total = '';
649
            $rule = new TaxOption();
650
            $rule = $rule->findOrFail(1);
651
            if ($rule->tax_enable == 1 && $rule->inclusive == 0) {
652
                foreach ($rates as $rate) {
653
                    $total += $total * ($rate / 100);
654
                }
655
            }
656
            //dd($total);
657
            return $total;
658
        } catch (\Exception $ex) {
659
            dd($ex);
660
            throw new \Exception($ex->getMessage());
661
        }
662
    }
663
664
    /**
665
     * Remove the specified resource from storage.
666
     *
667
     * @param int $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
668
     *
669
     * @return Response
670
     */
671 View Code Duplication
    public function destroy(Request $request)
672
    {
673
        try {
674
            $ids = $request->input('select');
675
            if (!empty($ids)) {
676
                foreach ($ids as $id) {
0 ignored issues
show
Bug introduced by
The expression $ids of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
677
                    $invoice = $this->invoice->where('id', $id)->first();
678
                    if ($invoice) {
679
                        $invoice->delete();
680
                    } else {
681
                        echo "<div class='alert alert-danger alert-dismissable'>
682
                    <i class='fa fa-ban'></i>
683
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
684
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
685
                        '.\Lang::get('message.no-record').'
686
                </div>';
687
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
688
                    }
689
                }
690
                echo "<div class='alert alert-success alert-dismissable'>
691
                    <i class='fa fa-ban'></i>
692
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.success').'
693
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
694
                        '.\Lang::get('message.deleted-successfully').'
695
                </div>';
696
            } else {
697
                echo "<div class='alert alert-danger alert-dismissable'>
698
                    <i class='fa fa-ban'></i>
699
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
700
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
701
                        '.\Lang::get('message.select-a-row').'
702
                </div>';
703
                //echo \Lang::get('message.select-a-row');
704
            }
705
        } catch (\Exception $e) {
706
            echo "<div class='alert alert-danger alert-dismissable'>
707
                    <i class='fa fa-ban'></i>
708
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
709
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
710
                        '.$e->getMessage().'
711
                </div>';
712
        }
713
    }
714
715
    public function setDomain($productid, $domain)
716
    {
717
        try {
718
            if (\Session::has('domain'.$productid)) {
719
                \Session::forget('domain'.$productid);
720
            }
721
            \Session::put('domain'.$productid, $domain);
722
        } catch (\Exception $ex) {
723
            throw new \Exception($ex->getMessage());
724
        }
725
    }
726
727
    public function domain($id)
728
    {
729
        try {
730
            if (\Session::has('domain'.$id)) {
731
                $domain = \Session::get('domain'.$id);
732
            } else {
733
                $domain = '';
734
            }
735
736
            return $domain;
737
        } catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
738
        }
739
    }
740
741
    public function updateInvoice($invoiceid)
742
    {
743
        try {
744
            $invoice = $this->invoice->findOrFail($invoiceid);
745
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->lists('amount')->toArray();
746
            $total = array_sum($payment);
747
            if ($total < $invoice->grand_total) {
748
                $invoice->status = 'pending';
749
            }
750
            if ($total >= $invoice->grand_total) {
751
                $invoice->status = 'success';
752
            }
753
            if ($total > $invoice->grand_total) {
754
                $user = $invoice->user()->first();
755
                $balance = $total - $invoice->grand_total;
756
                $user->debit = $balance;
757
                $user->save();
758
            }
759
760
            $invoice->save();
761
        } catch (\Exception $ex) {
762
            throw new \Exception($ex->getMessage());
763
        }
764
    }
765
766
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
767
    {
768
        try {
769
            $invoice = $this->invoice->find($invoiceid);
770
            //$user  = $this->user->find($invoice->user_id);
771
            //dd($payment_date);
772
            $invoice_status = 'pending';
773
774
            $payment = $this->payment->create([
775
                'invoice_id'     => $invoiceid,
776
                'user_id'        => $invoice->user_id,
777
                'amount'         => $amount,
778
                'payment_method' => $payment_method,
779
                'payment_status' => $payment_status,
780
                'created_at'     => $payment_date,
781
            ]);
782
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->lists('amount')->toArray();
783
            $total_paid = array_sum($all_payments);
784
            if ($total_paid >= $invoice->grand_total) {
785
                $invoice_status = 'success';
786
            }
787
            if ($invoice) {
788
                $invoice->status = $invoice_status;
789
                $invoice->save();
790
            }
791
792
            return $payment;
793
        } catch (\Exception $ex) {
794
            throw new \Exception($ex->getMessage());
795
        }
796
    }
797
798
    public function payment(Request $request)
799
    {
800
        try {
801
            if ($request->has('invoiceid')) {
802
                $invoice_id = $request->input('invoiceid');
803
                $invoice = $this->invoice->find($invoice_id);
804
                //dd($invoice);
805
                $invoice_status = '';
806
                $payment_status = '';
807
                $payment_method = '';
808
                $domain = '';
809
                if ($invoice) {
810
                    $invoice_status = $invoice->status;
811
                    $items = $invoice->invoiceItem()->first();
812
                    if ($items) {
813
                        $domain = $items->domain;
814
                    }
815
                }
816
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
817
                if ($payment) {
818
                    $payment_status = $payment->payment_status;
819
                    $payment_method = $payment->payment_method;
820
                }
821
822
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
823
            }
824
825
            return redirect()->back();
826
        } catch (\Exception $ex) {
827
            return redirect()->back()->with('fails', $ex->getMessage());
828
        }
829
    }
830
831
    public function postPayment($invoiceid, Request $request)
832
    {
833
        $this->validate($request, [
834
            'payment_method' => 'required',
835
            'amount'         => 'required|numeric',
836
            'payment_date'   => 'required|date_format:Y-m-d',
837
        ]);
838
        try {
839
            $payment_method = $request->input('payment_method');
840
            $payment_status = 'success';
841
            $payment_date = $request->input('payment_date');
842
            $amount = $request->input('amount');
843
            $payment = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
844
            if ($payment) {
845
                return redirect()->back()->with('success', 'Payment Accepted Successfully');
846
            }
847
        } catch (\Exception $ex) {
848
            return redirect()->back()->with('fails', $ex->getMessage());
849
        }
850
    }
851
852
    public function sendMail($userid, $invoiceid, $templatetype = 7)
853
    {
854
        try {
855
            $settings = new Setting();
856
            $settings = $settings->findOrFail(1);
857
            $user = $this->user->find($userid);
858
            $name = '';
859
            $to = '';
860
            $product = '';
861
            if ($user) {
862
                $name = $user->first_name.' '.$user->last_name;
863
                $to = $user->email;
864
            }
865
            $invoice = $this->invoice->find($invoiceid);
866
            $invoice_number = $invoice->number;
867
            $item = $invoice->invoiceItem()->first();
868
            if ($item) {
869
                $product = $item->product_name;
870
            }
871
872
            $url = url("download/$userid/$invoice_number");
873
            $from = $settings->email;
874
875
            $data = $this->template->where('type', $templatetype)->first()->data;
876
            $subject = $this->template->where('type', $templatetype)->first()->name;
877
            $replace = ['url' => $url, 'name' => $name, 'product' => $product];
878
879
            //send mail
880
            $template_controller = new TemplateController();
881
            $template_controller->Mailing($from, $to, $data, $subject, $replace);
882
        } catch (\Exception $ex) {
883
            throw new \Exception($ex->getMessage());
884
        }
885
    }
886
}
887