Completed
Push — development ( 877883...280d38 )
by Ashutosh
10:04
created

ClientController::store()   A

Complexity

Conditions 4
Paths 24

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 24
rs 9.6333
c 0
b 0
f 0
cc 4
nc 24
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\Common\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, $amount, $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
            // $client = "";
260
            $currency = $client->currency;
261
            $orders = $order->where('client', $id)->get();
262
            $comments = $client->comments()->where('user_id', $client->id)->get();
263
264
            return view(
265
                'themes.default1.user.client.show',
266
                compact(
267
                    'id',
268
                    'client',
269
                    'invoices',
270
                    'model_popup',
271
                    'orders',
272
                    'payments',
273
                    'invoiceSum',
274
                    'amountReceived',
275
                    'pendingAmount',
276
                    'currency',
277
                    'extraAmt',
278
                    'comments'
279
                )
280
            );
281
        } catch (\Exception $ex) {
282
            app('log')->info($ex->getMessage());
283
            Bugsnag::notifyException($ex);
284
285
            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...
286
        }
287
    }
288
289
290
    /**
291
     * Show the form for editing the specified resource.
292
     *
293
     * @param int $id
294
     *
295
     * @return \Response
296
     */
297
    public function edit($id)
298
    {
299
        try {
300
            $user = $this->user->where('id', $id)->first();
301
            $timezonesList = \App\Model\Common\Timezone::get();
302
            foreach ($timezonesList as $timezone) {
303
                $location = $timezone->location;
304
                if ($location) {
305
                    $start = strpos($location, '(');
306
                    $end = strpos($location, ')', $start + 1);
307
                    $length = $end - $start;
308
                    $result = substr($location, $start + 1, $length - 1);
309
                    $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
310
                }
311
            }
312
            //for display
313
            $timezones = array_column($display, 'name', 'id');
314
            $state = \App\Http\Controllers\Front\CartController::getStateByCode($user->state);
315
            $managers = User::where('role', 'admin')
316
            ->where('position', 'manager')
317
            ->pluck('first_name', 'id')->toArray();
318
            $selectedCurrency = Currency::where('code', $user->currency)
319
            ->pluck('name', 'code')->toArray();
320
            $selectedCompany = \DB::table('company_types')->where('short', $user->company_type)
321
            ->pluck('name', 'short')->toArray();
322
            $selectedIndustry = \App\Model\Common\Bussiness::where('short', $user->bussiness)
323
            ->pluck('name', 'short')->toArray();
324
            $selectedCompanySize = \DB::table('company_sizes')->where('short', $user->company_size)
325
            ->pluck('name', 'short')->toArray();
326
            $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($user->country);
327
328
            $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
329
330
            return view(
331
                'themes.default1.user.client.edit',
332
                compact(
333
                    'bussinesses',
334
                    'user',
335
                    'timezones',
336
                    'state',
337
                    'states',
338
                    'managers',
339
                    'selectedCurrency',
340
                    'selectedCompany',
341
                    'selectedIndustry',
342
                    'selectedCompanySize'
343
                )
344
            );
345
        } catch (\Exception $ex) {
346
            app('log')->error($ex->getMessage());
347
348
            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...
349
        }
350
    }
351
352
    /**
353
     * Update the specified resource in storage.
354
     *
355
     * @param int $id
356
     *
357
     * @return \Response
358
     */
359
    public function update($id, Request $request)
360
    {
361
        try {
362
            $user = $this->user->where('id', $id)->first();
363
            $symbol = Currency::where('code', $request->input('currency'))->pluck('symbol')->first();
364
            $user->currency_symbol = $symbol;
365
            $user->fill($request->input())->save();
366
367
            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...
368
        } catch (\Exception $ex) {
369
            app('log')->error($ex->getMessage());
370
            Bugsnag::notifyException($ex);
371
372
            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...
373
        }
374
    }
375
376
    /**
377
     * Remove the specified resource from storage.
378
     *
379
     * @param int $id
380
     *
381
     * @return \Response
382
     */
383
    public function destroy(Request $request)
384
    {
385
        $ids = $request->input('select');
386
        if (!empty($ids)) {
387
            foreach ($ids as $id) {
388
                $user = $this->user->where('id', $id)->first();
389
                if ($user) {
390
                    $user->delete();
391
                } else {
392
                    echo "<div class='alert alert-success alert-dismissable'>
393
                    <i class='fa fa-ban'></i>
394
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
395
                    /* @scrutinizer ignore-type */
396
                    \Lang::get('message.success').'
397
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
398
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
399
                </div>';
400
                    //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
401
                }
402
            }
403
            echo "<div class='alert alert-success alert-dismissable'>
404
                    <i class='fa fa-ban'></i>
405
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert')
406
                    .'!</b> './* @scrutinizer ignore-type */
407
                    \Lang::get('message.success').'
408
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
409
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
410
                </div>';
411
        } else {
412
            echo "<div class='alert alert-success alert-dismissable'>
413
                    <i class='fa fa-ban'></i>
414
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
415
                    ./* @scrutinizer ignore-type */\Lang::get('message.success').'
416
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
417
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
418
                </div>';
419
        }
420
    }
421
422
    public function sendWelcomeMail($user)
423
    {
424
        $activate_model = new AccountActivate();
425
        $str = str_random(40);
426
        $activate = $activate_model->create(['email' => $user->email, 'token' => $str]);
427
        $token = $activate->token;
428
        $url = url("activate/$token");
429
        //check in the settings
430
        $settings = new \App\Model\Common\Setting();
431
        $setting = $settings->where('id', 1)->first();
432
        //template
433
        $templates = new \App\Model\Common\Template();
434
        $temp_id = $setting->welcome_mail;
435
        $template = $templates->where('id', $temp_id)->first();
436
        $from = $setting->email;
437
        $to = $user->email;
438
        $subject = $template->name;
439
        $data = $template->data;
440
        $replace = ['name' => $user->first_name.' '.$user->last_name,
441
        'username'         => $user->email, 'password' => $str, 'url' => $url, ];
442
        $type = '';
443
        if ($template) {
444
            $type_id = $template->type;
445
            $temp_type = new \App\Model\Common\TemplateType();
446
            $type = $temp_type->where('id', $type_id)->first()->name;
447
        }
448
        //dd($type);
449
        $templateController = new \App\Http\Controllers\Common\TemplateController();
450
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
451
452
        return $mail;
453
    }
454
}
455