Completed
Push — development ( 2be1cb...034e49 )
by Ashutosh
11:52
created

ClientController::advanceSearch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 36
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 36
rs 9.6666
c 0
b 0
f 0
cc 1
nc 1
nop 13

How to fix   Many Parameters   

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\User;
4
5
use App\Http\Controllers\License\LicenseController;
6
use App\Http\Requests\User\ClientRequest;
7
use App\Model\Order\Invoice;
8
use App\Model\Order\Order;
9
use App\Model\Order\Payment;
10
use App\Model\Payment\Currency;
11
use App\Model\Status\StatusSetting;
12
use App\Model\User\AccountActivate;
13
use App\Traits\PaymentsAndInvoices;
14
use App\User;
15
use Bugsnag;
16
use DateTime;
17
use DateTimeZone;
18
use Illuminate\Http\Request;
19
use Log;
20
21
class ClientController extends AdvanceSearchController
22
{
23
    use PaymentsAndInvoices;
0 ignored issues
show
introduced by
The trait App\Traits\PaymentsAndInvoices requires some properties which are not provided by App\Http\Controllers\User\ClientController: $grand_total, $first_name, $planPrice, $domain, $user_id, $payment_method, $payment, $product_quantity, $payment_status, $invoice, $id, $amt_to_credit, $planRelation, $invoiceItem, $invoice_id, $no_of_agents
Loading history...
24
25
    public $user;
26
    public $activate;
27
    public $product;
28
29
    public function __construct()
30
    {
31
        $this->middleware('auth');
32
        // $this->middleware('admin');
33
        $user = new User();
34
        $this->user = $user;
35
        $activate = new AccountActivate();
36
        $this->activate = $activate;
37
        $product = new \App\Model\Product\Product();
38
        $this->product = $product;
39
        $license = new LicenseController();
40
        $this->licensing = $license;
41
    }
42
43
    /**
44
     * Display a listing of the resource.
45
     *
46
     * @return \Response
47
     */
48
    public function index(Request $request)
49
    {
50
        $name = $request->input('name');
51
        $username = $request->input('username');
52
        $company = $request->input('company');
53
        $mobile = $request->input('mobile');
54
        $email = $request->input('email');
55
        $country = $request->input('country');
56
        $industry = $request->input('industry');
57
        $company_type = $request->input('company_type');
58
        $company_size = $request->input('company_size');
59
        $role = $request->input('role');
60
        $position = $request->input('position');
61
        $reg_from = $request->input('reg_from');
62
        $reg_till = $request->input('reg_till');
63
64
        return view(
65
            'themes.default1.user.client.index',
66
            compact(
67
                'name',
68
                'username',
69
                'company',
70
                'mobile',
71
                'email',
72
                'country',
73
                'industry',
74
                'company_type',
75
                'company_size',
76
                'role',
77
                'position',
78
                'reg_from',
79
                'reg_till'
80
            )
81
        );
82
    }
83
84
    /**
85
     * Get Clients for yajra datatable.
86
     */
87
    public function getClients(Request $request)
88
    {
89
        $name = $request->input('name');
90
        $username = $request->input('username');
91
        $company = $request->input('company');
92
        $mobile = $request->input('mobile');
93
        $email = $request->input('email');
94
        $country = $request->input('country');
95
        $industry = $request->input('industry');
96
        $company_type = $request->input('company_type');
97
        $company_size = $request->input('company_size');
98
        $role = $request->input('role');
99
        $position = $request->input('position');
100
        $reg_from = $request->input('reg_from');
101
        $reg_till = $request->input('reg_till');
102
        $user = $this->advanceSearch(
103
            $name,
104
            $username,
105
            $company,
106
            $mobile,
107
            $email,
108
            $country,
109
            $industry,
110
            $company_type,
111
            $company_size,
112
            $role,
113
            $position,
114
            $reg_from,
115
            $reg_till
116
        );
117
118
        return\ DataTables::of($user->get())
119
                         ->addColumn('checkbox', function ($model) {
120
                             return "<input type='checkbox' class='user_checkbox' 
121
                            value=".$model->id.' name=select[] id=check>';
122
                         })
123
                        ->addColumn('first_name', function ($model) {
124
                            return '<a href='.url('clients/'.$model->id).'>'
125
                            .ucfirst($model->first_name).' '.ucfirst($model->last_name).'</a>';
126
                        })
127
                         ->addColumn('email', function ($model) {
128
                             return $model->email;
129
                         })
130
                          ->addColumn('created_at', function ($model) {
131
                              $ends = $model->created_at;
132
                              if ($ends) {
133
                                  $date1 = new DateTime($ends);
134
                                  $tz = \Auth::user()->timezone()->first()->name;
135
                                  $date1->setTimezone(new DateTimeZone($tz));
136
                                  $end = $date1->format('M j, Y, g:i a ');
137
                              }
138
139
                              return $end;
140
                          })
141
                        // ->showColumns('email', 'created_at')
142
                        ->addColumn('active', function ($model) {
143
                            if ($model->active == 1) {
144
                                $email = "<span class='glyphicon glyphicon-envelope'
145
                                 style='color:green' title='verified email'></span>";
146
                            } else {
147
                                $email = "<span class='glyphicon glyphicon-envelope'
148
                                 style='color:red' title='unverified email'></span>";
149
                            }
150
                            if ($model->mobile_verified == 1) {
151
                                $mobile = "<span class='glyphicon glyphicon-phone' 
152
                                style='color:green' title='verified mobile'></span>";
153
                            } else {
154
                                $mobile = "<span class='glyphicon glyphicon-phone'
155
                                 style='color:red' title='unverified mobile'></span>";
156
                            }
157
158
                            return $email.'&nbsp;&nbsp;'.$mobile;
159
                        })
160
                        ->addColumn('action', function ($model) {
161
                            return '<a href='.url('clients/'.$model->id.'/edit')
162
                            ." class='btn btn-sm btn-primary btn-xs'>
163
                            <i class='fa fa-edit' style='color:white;'> </i>&nbsp;&nbsp;Edit</a>"
164
                                    .'  <a href='.url('clients/'.$model->id)
165
                                    ." class='btn btn-sm btn-primary btn-xs'>
166
                                    <i class='fa fa-eye' style='color:white;'> </i>&nbsp;&nbsp;View</a>";
167
                            // return 'hhhh';
168
                        })
169
                        ->rawColumns(['checkbox', 'first_name', 'email',  'created_at', 'active', 'action'])
170
                        ->make(true);
171
172
        // ->searchColumns('email', 'first_name')
173
                        // ->orderColumns('email', 'first_name', 'created_at')
174
                        // ->make();
175
    }
176
177
    /**
178
     * Show the form for creating a new resource.
179
     *
180
     * @return \Response
181
     */
182
    public function create()
183
    {
184
        $timezones = new \App\Model\Common\Timezone();
185
        $timezones = $timezones->pluck('name', 'id')->toArray();
186
        $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
187
        $managers = User::where('role', 'admin')->where('position', 'manager')
188
        ->pluck('first_name', 'id')->toArray();
189
        $timezonesList = \App\Model\Common\Timezone::get();
190
        foreach ($timezonesList as $timezone) {
191
            $location = $timezone->location;
192
            if ($location) {
193
                $start = strpos($location, '(');
194
                $end = strpos($location, ')', $start + 1);
195
                $length = $end - $start;
196
                $result = substr($location, $start + 1, $length - 1);
197
                $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
198
            }
199
        }
200
        $timezones = array_column($display, 'name', 'id');
201
202
        return view('themes.default1.user.client.create', compact('timezones', 'bussinesses', 'managers'));
203
    }
204
205
    /**
206
     * Store a newly created resource in storage.
207
     *
208
     * @return \Response
209
     */
210
    public function store(ClientRequest $request)
211
    {
212
        try {
213
            $user = $this->user;
214
            $str = 'demopass';
215
            $password = \Hash::make($str);
216
            $user->password = $password;
217
            $cont = new \App\Http\Controllers\Front\PageController();
218
            $location = $cont->getLocation();
219
            $user->ip = $location['ip'];
220
            $user->fill($request->input())->save();
221
            $this->sendWelcomeMail($user);
222
            $mailchimpStatus = StatusSetting::first()->value('mailchimp_status');
223
            if ($mailchimpStatus == 1) {
224
                $mailchimp = new \App\Http\Controllers\Common\MailChimpController();
225
                $r = $mailchimp->addSubscriber($user->email);
226
            }
227
228
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...e.saved-successfully')) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
229
        } catch (\Swift_TransportException $e) {
230
            return redirect()->back()->with('warning', 'User has been created successfully
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ion has some problem!') also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
231
             But email configuration has some problem!');
232
        } catch (\Exception $e) {
233
            return redirect()->back()->with('fails', $e->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ils', $e->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
234
        }
235
    }
236
237
    /**
238
     * Display the specified resource.
239
     *
240
     * @param int $id
241
     *
242
     * @return \Response
243
     */
244
    public function show($id)
245
    {
246
        try {
247
            $invoice = new Invoice();
248
            $order = new Order();
249
            $invoices = $invoice->where('user_id', $id)->orderBy('created_at', 'desc')->get();
250
            $invoiceSum = $this->getTotalInvoice($invoices);
251
            $amountReceived = $this->getAmountPaid($id);
252
            $pendingAmount = $invoiceSum - $amountReceived;
253
            // $pendingAmount = $invoiceSum - $amountReceived;
254
            // if ($pendingAmount < 0) {
255
            //     $pendingAmount = 0;
256
            // }
257
            $extraAmt = $this->getExtraAmt($id);
258
            $client = $this->user->where('id', $id)->first();
259
260
            // $client = "";
261
            $currency = $client->currency;
262
            $orders = $order->where('client', $id)->get();
263
            $comments = $client->comments()->where('user_id', $client->id)->get();
264
265
            return view(
266
                'themes.default1.user.client.show',
267
                compact(
268
                    'id',
269
                    'client',
270
                    'invoices',
271
                    'model_popup',
272
                    'orders',
273
                    'payments',
274
                    'invoiceSum',
275
                    'amountReceived',
276
                    'pendingAmount',
277
                    'currency',
278
                    'extraAmt',
279
                    'comments'
280
                )
281
            );
282
        } catch (\Exception $ex) {
283
            app('log')->info($ex->getMessage());
284
            Bugsnag::notifyException($ex);
285
286
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
287
        }
288
    }
289
290
    public function getOrderDetail($id)
291
    {
292
        $client = $this->user->where('id', $id)->first();
293
        $responseData = [];
294
        foreach ($client->order()->orderBy('created_at', 'desc')->get() as $order) {
295
            $date = $order->created_at;
296
            $productName = $order->product()->first() && $order->product()->first()->name ?
297
            $order->product()->first()->name : 'Unknown';
298
            $number = $order->number;
299
            $price = $order->price_override;
300
            $status = $order->order_status;
301
            array_push($responseData, (['date'=> $date, 'productName'=>$productName,
302
                'number'                      => $number, 'price' =>$price, 'status'=>$status, ]));
303
        }
304
305
        return $responseData;
306
    }
307
308
    //Get Payment Details on Invoice Page
309
    public function getPaymentDetail($id)
310
    {
311
        $client = $this->user->where('id', $id)->first();
312
        $invoice = new Invoice();
313
        $invoices = $invoice->where('user_id', $id)->orderBy('created_at', 'desc')->get();
314
        $extraAmt = $this->getExtraAmtPaid($id);
315
        $date = '';
316
        $responseData = [];
317
        if ($invoices) {
318
            foreach ($client->payment()->orderBy('created_at', 'desc')->get() as $payment) {
319
                $number = $payment->invoice()->first() ? $payment->invoice()->first()->number : '--';
320
                $date = $payment->created_at;
321
                $date1 = new DateTime($date);
322
                $tz = \Auth::user()->timezone()->first()->name;
323
                $date1->setTimezone(new DateTimeZone($tz));
324
                $date = $date1->format('M j, Y, g:i a ');
325
                $pay_method = $payment->payment_method;
326
                if ($payment->invoice_id == 0) {
327
                    $amount = $extraAmt;
328
                } else {
329
                    $amount = $payment->amount;
330
                }
331
                $status = ucfirst($payment->payment_status);
332
                array_push($responseData, (['number'=>$number, 'pay_method'=>$pay_method, 'amount'=>$amount, 'status'=>$status, 'date'=>$date]));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 145 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...
333
            }
334
        }
335
336
        return $responseData;
337
    }
338
339
    public function getClientDetail($id)
340
    {
341
        $client = $this->user->where('id', $id)->first();
342
        $currency = $client->currency;
343
        if (array_key_exists('name', \App\Http\Controllers\Front\CartController::getStateByCode($client->state))) {
344
            $client->state = \App\Http\Controllers\Front\CartController::getStateByCode($client->state)['name'];
345
        }
346
        $client->country = ucwords(strtolower(\App\Http\Controllers\Front\CartController::getCountryByCode($client->country)));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
347
348
        $displayData = (['currency'=>$currency, 'client'=> $client]);
349
350
        return $displayData;
351
    }
352
353
    public function getExtraAmt($userId)
354
    {
355
        try {
356
            $amounts = Payment::where('user_id', $userId)->where('invoice_id', 0)->select('amt_to_credit')->get();
357
            $balance = 0;
358
            foreach ($amounts as $amount) {
359
                if ($amount) {
360
                    $balance = $balance + $amount->amt_to_credit;
361
                }
362
            }
363
364
            return $balance;
365
        } catch (\Exception $ex) {
366
            app('log')->info($ex->getMessage());
367
            Bugsnag::notifyException($ex);
368
369
            return redirect()->back()->with('fails', $ex->getMessage());
370
        }
371
    }
372
373
374
375
376
    /**
377
     * Show the form for editing the specified resource.
378
     *
379
     * @param int $id
380
     *
381
     * @return \Response
382
     */
383
    public function edit($id)
384
    {
385
        try {
386
            $user = $this->user->where('id', $id)->first();
387
            $timezonesList = \App\Model\Common\Timezone::get();
388
            foreach ($timezonesList as $timezone) {
389
                $location = $timezone->location;
390
                if ($location) {
391
                    $start = strpos($location, '(');
392
                    $end = strpos($location, ')', $start + 1);
393
                    $length = $end - $start;
394
                    $result = substr($location, $start + 1, $length - 1);
395
                    $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
396
                }
397
            }
398
            //for display
399
            $timezones = array_column($display, 'name', 'id');
400
            $state = \App\Http\Controllers\Front\CartController::getStateByCode($user->state);
401
            $managers = User::where('role', 'admin')
402
            ->where('position', 'manager')
403
            ->pluck('first_name', 'id')->toArray();
404
            $selectedCurrency = Currency::where('code', $user->currency)
405
            ->pluck('name', 'code')->toArray();
406
            $selectedCompany = \DB::table('company_types')->where('short', $user->company_type)
407
            ->pluck('name', 'short')->toArray();
408
            $selectedIndustry = \App\Model\Common\Bussiness::where('short', $user->bussiness)
409
            ->pluck('name', 'short')->toArray();
410
            $selectedCompanySize = \DB::table('company_sizes')->where('short', $user->company_size)
411
            ->pluck('name', 'short')->toArray();
412
            $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($user->country);
413
414
            $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
415
416
            return view(
417
                'themes.default1.user.client.edit',
418
                compact(
419
                    'bussinesses',
420
                    'user',
421
                    'timezones',
422
                    'state',
423
                    'states',
424
                    'managers',
425
                    'selectedCurrency',
426
                    'selectedCompany',
427
                    'selectedIndustry',
428
                    'selectedCompanySize'
429
                )
430
            );
431
        } catch (\Exception $ex) {
432
            app('log')->error($ex->getMessage());
433
434
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
435
        }
436
    }
437
438
    /**
439
     * Update the specified resource in storage.
440
     *
441
     * @param int $id
442
     *
443
     * @return \Response
444
     */
445
    public function update($id, Request $request)
446
    {
447
        try {
448
            $user = $this->user->where('id', $id)->first();
449
            $symbol = Currency::where('code', $request->input('currency'))->pluck('symbol')->first();
450
            $user->currency_symbol = $symbol;
451
            $user->fill($request->input())->save();
452
453
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...updated-successfully')) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
454
        } catch (\Exception $ex) {
455
            app('log')->error($ex->getMessage());
456
            Bugsnag::notifyException($ex);
457
458
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type Response.
Loading history...
459
        }
460
    }
461
462
    /**
463
     * Remove the specified resource from storage.
464
     *
465
     * @param int $id
466
     *
467
     * @return \Response
468
     */
469
    public function destroy(Request $request)
470
    {
471
        $ids = $request->input('select');
472
        if (!empty($ids)) {
473
            foreach ($ids as $id) {
474
                $user = $this->user->where('id', $id)->first();
475
                if ($user) {
476
                    $user->delete();
477
                } else {
478
                    echo "<div class='alert alert-success alert-dismissable'>
479
                    <i class='fa fa-ban'></i>
480
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
481
                    /* @scrutinizer ignore-type */
482
                    \Lang::get('message.success').'
483
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
484
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
485
                </div>';
486
                    //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
487
                }
488
            }
489
            echo "<div class='alert alert-success alert-dismissable'>
490
                    <i class='fa fa-ban'></i>
491
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert')
492
                    .'!</b> './* @scrutinizer ignore-type */
493
                    \Lang::get('message.success').'
494
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
495
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
496
                </div>';
497
        } else {
498
            echo "<div class='alert alert-success alert-dismissable'>
499
                    <i class='fa fa-ban'></i>
500
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
501
                    ./* @scrutinizer ignore-type */\Lang::get('message.success').'
502
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
503
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
504
                </div>';
505
        }
506
    }
507
508
    public function sendWelcomeMail($user)
509
    {
510
        $activate_model = new AccountActivate();
511
        $str = str_random(40);
512
        $activate = $activate_model->create(['email' => $user->email, 'token' => $str]);
513
        $token = $activate->token;
514
        $url = url("activate/$token");
515
        //check in the settings
516
        $settings = new \App\Model\Common\Setting();
517
        $setting = $settings->where('id', 1)->first();
518
        //template
519
        $templates = new \App\Model\Common\Template();
520
        $temp_id = $setting->welcome_mail;
521
        $template = $templates->where('id', $temp_id)->first();
522
        $from = $setting->email;
523
        $to = $user->email;
524
        $subject = $template->name;
525
        $data = $template->data;
526
        $replace = ['name' => $user->first_name.' '.$user->last_name,
527
        'username'         => $user->email, 'password' => $str, 'url' => $url, ];
528
        $type = '';
529
        if ($template) {
530
            $type_id = $template->type;
531
            $temp_type = new \App\Model\Common\TemplateType();
532
            $type = $temp_type->where('id', $type_id)->first()->name;
533
        }
534
        //dd($type);
535
        $templateController = new \App\Http\Controllers\Common\TemplateController();
536
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
537
538
        return $mail;
539
    }
540
}
541