Completed
Push — development ( c2ff46...95cb59 )
by Ashutosh
28:29 queued 18:30
created

ClientController::getExtraAmt()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 17
rs 9.9
c 0
b 0
f 0
cc 4
nc 4
nop 1
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
340
341
    /**
342
     * Show the form for editing the specified resource.
343
     *
344
     * @param int $id
345
     *
346
     * @return \Response
347
     */
348
    public function edit($id)
349
    {
350
        try {
351
            $user = $this->user->where('id', $id)->first();
352
            $timezonesList = \App\Model\Common\Timezone::get();
353
            foreach ($timezonesList as $timezone) {
354
                $location = $timezone->location;
355
                if ($location) {
356
                    $start = strpos($location, '(');
357
                    $end = strpos($location, ')', $start + 1);
358
                    $length = $end - $start;
359
                    $result = substr($location, $start + 1, $length - 1);
360
                    $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
361
                }
362
            }
363
            //for display
364
            $timezones = array_column($display, 'name', 'id');
365
            $state = \App\Http\Controllers\Front\CartController::getStateByCode($user->state);
366
            $managers = User::where('role', 'admin')
367
            ->where('position', 'manager')
368
            ->pluck('first_name', 'id')->toArray();
369
            $selectedCurrency = Currency::where('code', $user->currency)
370
            ->pluck('name', 'code')->toArray();
371
            $selectedCompany = \DB::table('company_types')->where('short', $user->company_type)
372
            ->pluck('name', 'short')->toArray();
373
            $selectedIndustry = \App\Model\Common\Bussiness::where('short', $user->bussiness)
374
            ->pluck('name', 'short')->toArray();
375
            $selectedCompanySize = \DB::table('company_sizes')->where('short', $user->company_size)
376
            ->pluck('name', 'short')->toArray();
377
            $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($user->country);
378
379
            $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
380
381
            return view(
382
                'themes.default1.user.client.edit',
383
                compact(
384
                    'bussinesses',
385
                    'user',
386
                    'timezones',
387
                    'state',
388
                    'states',
389
                    'managers',
390
                    'selectedCurrency',
391
                    'selectedCompany',
392
                    'selectedIndustry',
393
                    'selectedCompanySize'
394
                )
395
            );
396
        } catch (\Exception $ex) {
397
            app('log')->error($ex->getMessage());
398
399
            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...
400
        }
401
    }
402
403
    /**
404
     * Update the specified resource in storage.
405
     *
406
     * @param int $id
407
     *
408
     * @return \Response
409
     */
410
    public function update($id, Request $request)
411
    {
412
        try {
413
            $user = $this->user->where('id', $id)->first();
414
            $symbol = Currency::where('code', $request->input('currency'))->pluck('symbol')->first();
415
            $user->currency_symbol = $symbol;
416
            $user->fill($request->input())->save();
417
418
            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...
419
        } catch (\Exception $ex) {
420
            app('log')->error($ex->getMessage());
421
            Bugsnag::notifyException($ex);
422
423
            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...
424
        }
425
    }
426
427
    /**
428
     * Remove the specified resource from storage.
429
     *
430
     * @param int $id
431
     *
432
     * @return \Response
433
     */
434
    public function destroy(Request $request)
435
    {
436
        $ids = $request->input('select');
437
        if (!empty($ids)) {
438
            foreach ($ids as $id) {
439
                $user = $this->user->where('id', $id)->first();
440
                if ($user) {
441
                    $user->delete();
442
                } else {
443
                    echo "<div class='alert alert-success alert-dismissable'>
444
                    <i class='fa fa-ban'></i>
445
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
446
                    /* @scrutinizer ignore-type */
447
                    \Lang::get('message.success').'
448
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
449
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
450
                </div>';
451
                    //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
452
                }
453
            }
454
            echo "<div class='alert alert-success alert-dismissable'>
455
                    <i class='fa fa-ban'></i>
456
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert')
457
                    .'!</b> './* @scrutinizer ignore-type */
458
                    \Lang::get('message.success').'
459
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
460
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
461
                </div>';
462
        } else {
463
            echo "<div class='alert alert-success alert-dismissable'>
464
                    <i class='fa fa-ban'></i>
465
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
466
                    ./* @scrutinizer ignore-type */\Lang::get('message.success').'
467
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
468
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
469
                </div>';
470
        }
471
    }
472
473
    public function sendWelcomeMail($user)
474
    {
475
        $activate_model = new AccountActivate();
476
        $str = str_random(40);
477
        $activate = $activate_model->create(['email' => $user->email, 'token' => $str]);
478
        $token = $activate->token;
479
        $url = url("activate/$token");
480
        //check in the settings
481
        $settings = new \App\Model\Common\Setting();
482
        $setting = $settings->where('id', 1)->first();
483
        //template
484
        $templates = new \App\Model\Common\Template();
485
        $temp_id = $setting->welcome_mail;
486
        $template = $templates->where('id', $temp_id)->first();
487
        $from = $setting->email;
488
        $to = $user->email;
489
        $subject = $template->name;
490
        $data = $template->data;
491
        $replace = ['name' => $user->first_name.' '.$user->last_name,
492
        'username'         => $user->email, 'password' => $str, 'url' => $url, ];
493
        $type = '';
494
        if ($template) {
495
            $type_id = $template->type;
496
            $temp_type = new \App\Model\Common\TemplateType();
497
            $type = $temp_type->where('id', $type_id)->first()->name;
498
        }
499
        //dd($type);
500
        $templateController = new \App\Http\Controllers\Common\TemplateController();
501
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
502
503
        return $mail;
504
    }
505
}
506