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 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\WhatsappDevice;
use App\Models\WhatsappTemplate;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\ConnectionException;
use App\Rules\DifferenceRule;
use Exception;
use Illuminate\Support\Facades\Auth;

class WhatsappDeviceController extends Controller
{
    /**
     * create form show
     */
    public function create() {

        $user               = Auth::user();
        $title              = translate("Setup Whatsapp");
        $credentials        = config('setting.whatsapp_business_credentials');
        $whatsappBusinesses = WhatsappDevice::where('user_id', auth()->user()->id)
            ->where("type", WhatsappDevice::BUSINESS)
            ->orderBy('id', 'desc')
            ->paginate(paginateNumber(site_settings("paginate_number")));

        $whatsappNodes      = WhatsappDevice::where('user_id', auth()->user()->id)
            ->where("type", WhatsappDevice::NODE)
            ->orderBy('id', 'desc')
            ->paginate(paginateNumber(site_settings("paginate_number")));

        try {

            $response = Http::get(env('WP_SERVER_URL'));
        } catch (ConnectionException) {

            return view('user.whatsapp_device.error', [
                'title'              => $title,
                'message'            => "Failed to establish a connection with the WhatsApp node server. Please reach out to your service provider for further assistance.",
                'credentials'        => $credentials,
                'whatsappBusinesses' => $whatsappBusinesses,
                'user'               => $user,
            ]);
        }

        foreach ($whatsappNodes as $key => $value) {

            try {

                $findWhatsappsession = Http::get(env('WP_SERVER_URL') . '/sessions/status/' . $value->name);
                $wpu = WhatsappDevice::where('id', $value->id)->first();
                if ($findWhatsappsession->status() == 200) {

                    $wpu->status = 'connected';
                } else {
                    
                    $wpu->status = 'disconnected';
                }
                $wpu->save();
            } catch (\Exception $e) {
                
            }
        }
        return view('user.whatsapp_device.create', [
            'title'              => $title,
            'credentials'        => $credentials,
            'whatsappBusinesses' => $whatsappBusinesses,
            'whatsappNodes'      => $whatsappNodes,
            'user'               => $user,
        ]);
    }

    /**
     * whatsapp store method
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request, $type = null) {

        
        $access = auth()->user()->runningSubscription()->currentPlan()->whatsapp;
        $whatsapp_device_count = WhatsappDevice::where("user_id", auth()->user()->id)->get()->count();
        
        if($request->has("whatsapp_business_api") && $request->input("whatsapp_business_api") == true && $type == "cloud_api") {

            $required_credentials = config("setting.whatsapp_business_credentials.required");

            foreach($required_credentials as $required_cred_key => $required_cred_value) {

                $validate['credentials'][$required_cred_key] = 'required';
            }

            $whatsapp              = new WhatsappDevice();
            $whatsapp->user_id     = auth()->user()->id;
            
            $whatsapp->name        = $request->input('name');
            $whatsapp->type        = WhatsappDevice::BUSINESS;
            $whatsapp->credentials = $request->credentials;
            $whatsapp->save();
            $notify[] = ['success', 'Whatsapp business API credentials added successfully'];
            return back()->withNotify($notify);
        }

        if($access->is_allowed) {

            if ($type == "webhook") {
    
                $user = Auth::user();
                $user->webhook_token = $request->input("verify_token");
                $user->save();
                $notify[] = ['success', 'Whatsapp Cloud Webhook verify token saved successfully'];
            }

            if($whatsapp_device_count < $access->gateway_limit || $access->gateway_limit == 0) {

             
                if($request->has("min_delay") && $request->has("max_delay")) { 
                    
                    $validate['min_delay'] = 'required|gte:10';
                    $validate['max_delay'] = ['required', 'gt:min_delay', new DifferenceRule($request->min_delay)];
                    
                    $currentUrl = $request->root();
                    $parsedUrl = parse_url($currentUrl);
                    $domain = $parsedUrl['host'];
        
                    $response = Http::post(env('WP_SERVER_URL').'/sessions/init', [ 
                        'domain' => $domain
                    ]);
        
                    $responseBody = json_decode($response->body());
            
                    if ($response->status() === 200 && $responseBody->success) {
        
                        $credentials = [];
                        $credentials['min_delay']   = $request->input('min_delay');
                        $credentials['max_delay']   = $request->input('max_delay');
                        $credentials['number']      = " ";
                        $credentials['multidevice'] = "YES";
                        $whatsapp = new WhatsappDevice();
                        $whatsapp->user_id = auth()->user()->id;
                        $whatsapp->name = randomNumber()."_".$request->input('name');
                        $whatsapp->credentials =  $credentials;
                        $whatsapp->type =  WhatsappDevice::NODE;
                        
                        $whatsapp->status = 'initiate';
                        $whatsapp->save();
                        $notify[] = ['success', 'Whatsapp Device successfully added'];
        
                    } else {
        
                        $notify[] = ['error', $responseBody->message];
                    } 
                }
                return back()->withNotify($notify);
            } else {
                $notify[] = ['error', "Plan does not allow you to create more than $access->gateway_limit gateways"];
                return back()->withNotify($notify);
            }
            
        } else {
            $notify[] = ['error', "Current Plan doesn't allow you to add Whatsapp Devices"];
            return back()->withNotify($notify);
        }
        
    }

    /**
     * whatsapp template fetch method
     * @param Request $request, $type
     * @return mixed
     */
    public function cloudFetch(Request $request, $type = null) {
		
        $user = Auth::user();
		$templates = WhatsappTemplate::where("user_id", $user->id)->where("cloud_id", $request->input("cloud_id"))
                              ->whereIn("status", ["APPROVED"])
                              ->get();
		return response()->json(['templates' => $templates]);
	}

    /**
     * whatsapp cloud api templates
     * @param Request $request, $type, $id
     * @return view
     */
    public function cloudTemplate(Request $request, $type = null, $id = null) {
        
        $user = Auth::user();
        $templates = [];
		$title 	   = strtoupper(@$type)." ".translate("Template List");
		if($type = "whatsapp") {

			$templates = $id ? WhatsappTemplate::where("user_id", $user->id)->where("cloud_id", $id)->latest()->paginate(paginateNumber(site_settings("paginate_number"))) :  WhatsappTemplate::where($user->id)->latest()->paginate(paginateNumber(site_settings("paginate_number")));
            return view('user.template.whatsapp.index', compact('title', 'templates'));
		}
    }

    /**
     * whatsapp cloud api templates
     * @param Request $request
     * @return view
     */
    public function cloudRefresh(Request $request) {

		try {
            
            $user = Auth::user();
			$itemId = $request->input("itemId");
			WhatsappTemplate::where('cloud_id', $itemId)->delete();
			$whatsapp_business_account = WhatsappDevice::find($itemId);
			$credentials 			   = $whatsapp_business_account->credentials;
			$token 					   = $credentials['user_access_token'];
			$waba_id 				   = $credentials['whatsapp_business_account_id'];
			$url 					   = "https://graph.facebook.com/v19.0/$waba_id/message_templates";

			$queryParams = [
				'fields' => 'name,category,language,quality_score,components,status',
				'limit'  => 100
			];

			$headers = [
				'Authorization' => "Bearer $token"
			];

			$response 	  = Http::withHeaders($headers)->get($url, $queryParams);
			$responseData = $response->json();
            
			if (array_key_exists("data", $responseData)) {
				
				foreach ($responseData["data"] as $template) {
					
					$template_data = [
						'cloud_id'      	   => $itemId,
						'user_id'       	   => $user->id,
						'language_code' 	   => $template["language"],
						'name' 	   			   => $template["name"],
						'category'	    	   => $template["category"],
						'status'        	   => $template["status"],
						'template_information' => $template["components"]
					];

					WhatsappTemplate::create($template_data);
				}

				return json_encode([
					'reload' => true,
					'status' => true,
				]);
				
			} else {

				return json_encode([
					'reload' => true,
					'status' => false,
				]);
			}

		} catch (\Exception $e) {
            
			return json_encode([
				'reload' => true,
				'status' => false,
			]);
		}
	}

    /**
     * whatsapp update method
     * @param Request $request
     * @return mixed
     */
    public function update(Request $request) {

        $validate         = [];
        $notify           = [];
        if($request->has("whatsapp_business_api") && $request->input("whatsapp_business_api") == true) {

            $required_credentials = config("setting.whatsapp_business_credentials.required");

            foreach($required_credentials as $required_cred_key => $required_cred_value) {

                $validate['credentials'][$required_cred_key] = 'required';
            }
        }

        if($request->has("whatsapp_node_module") && $request->input("whatsapp_node_module") == true) { 
            
            $validate['min_delay'] = 'required|gte:10';
            $validate['max_delay'] = ['required', 'gt:min_delay', new DifferenceRule($request->min_delay)];
        }
        $request->validate($validate);

        $userId     = auth()->user()->id;
        $whatsapp    = WhatsappDevice::where('user_id',$userId)
            ->where('id', $request->input('id'))
            ->first();

        $credentials = $whatsapp->credentials;
       
        if($request->input("whatsapp_business_api") == true) {

            $credentials = $request->input("credentials");
            $whatsapp->user_id    = $userId;
            $whatsapp->admin_id    = null;
            $whatsapp->name        = $request->input('name');
            $whatsapp->credentials = $credentials;
            $whatsapp->update();
            $notify[] = ['success', 'Whatsapp business API credentials updated successfully'];
        } 
        
        if($request->input("whatsapp_node_module") == true) {

            $whatsapp->user_id  = $userId;
            $whatsapp->admin_id  = null;
            
            $credentials['min_delay']   = $request->input('min_delay');
            $credentials['max_delay']   = $request->input('max_delay');
            $whatsapp->credentials      = $credentials;
            $whatsapp->update();
            $notify[] = ['success', 'WhatsApp device updated successfully.'];
        }
        
        return back()->withNotify($notify);
    }

    /**
     * whatsapp delete method
     * @param Request $request
     * @return mixed
     */
    public function delete(Request $request)
    {
        $whatsapp = WhatsappDevice::where('id', $request->id)->where('user_id', auth()->user()->id)->first();
        $whatsapp->delete();
        if ($whatsapp->type == WhatsappDevice::BUSINESS) {
            $notify[] = ['success', 'WhatsApp Business Portfolio has been successfully deleted.'];
            return back()->withNotify($notify);
        }
        try {
            $response = Http::delete(env('WP_SERVER_URL').'/sessions/delete/'.$whatsapp->name);
            if ($response->status() == 200) {
                $notify[] = ['success', 'WhatsApp device has been successfully deleted, and the associated sessions have been cleared from the node.'];
            }else{
                $notify[] = ['success', 'WhatsApp device has been successfully deleted.'];
            }
        } catch (\Exception $e) {
            $notify[] = ['error', 'Oops! Something went wrong. The Node server is not running.'];
            return back()->withNotify($notify);
        }
        return back()->withNotify($notify);
    }

    /**
     * whatsapp device status update method
     * @param Request $request
     * @return false|string
     */
    public function statusUpdate(Request $request)
    {
        $whatsapp = WhatsappDevice::where('id', $request->id)->where('user_id', auth()->user()->id)->first();

        if ($request->status=='connected') {
            try {
                $findWhatsappsession = Http::get(env('WP_SERVER_URL').'/sessions/status/'.$whatsapp->name);
                if ($findWhatsappsession->status()==200) {
                    $whatsapp->status = 'connected';
                    $message = "Successfully whatsapp sessions reconnect";
                }else{
                    $response = Http::delete(env('WP_SERVER_URL').'/sessions/delete/'.$whatsapp->name);
                    $whatsapp->status = 'disconnected';
                    $message = "Successfully whatsapp sessions disconnected";
                }
                $whatsapp->update();
            } catch (\Exception $e) {

            }
        }elseif ($request->status=='disconnected') {
            try {
                $response = Http::delete(env('WP_SERVER_URL').'/sessions/delete/'.$whatsapp->name);
                if ($response->status() == 200) {
                    $whatsapp->status = 'disconnected';
                    $message =  'Whatsapp Device successfully Deleted';
                }else{
                    $message =  'Opps! Something went wrong, try again';
                }
                $whatsapp->update();
            } catch (\Exception $e) {

            }
        }else{
            try {
                $response = Http::delete(env('WP_SERVER_URL').'/sessions/delete/'.$whatsapp->name);
                if ($response->status() == 200) {
                    $whatsapp->status = 'disconnected';
                    $message = 'Whatsapp Device successfully Deleted';
                }else{
                    $message ='Opps! Something went wrong, try again';
                }
                $whatsapp->update();
            } catch (\Exception $e) {

            }
            $whatsapp->status = $request->status;
            $whatsapp->update();
        }

        return json_encode([
            'success' => $message
        ]);
    }

    /**
     * whatsapp qr quote scan method
     * @param Request $request
     * @return false|string
     */
    public function getWaqr(Request $request) {
       
        $whatsapp = WhatsappDevice::where('id', $request->id)->where('user_id', auth()->user()->id)->first();
        $islegacy = !(array_key_exists("multidevice", $whatsapp->credentials) && $whatsapp->credentials["multidevice"] ? $whatsapp->credentials["multidevice"] : 'NO' === "YES");
        $data = array();
        $currentUrl = $request->root();
        $parsedUrl = parse_url($currentUrl);
        $domain = $parsedUrl['host'];
        
        $response = Http::post(env('WP_SERVER_URL').'/sessions/create', [
            'id' => $whatsapp->name,
            'isLegacy' => $islegacy,
            'domain' => $domain
        ]);
        
        $responseBody = json_decode($response->body());
       
        if ($response->status() === 200) {
            $data['status'] = $response->status();
            $data['qr'] = $responseBody->data->qr;
            $data['message'] = $responseBody->message;
        } else {
            $msg = $response->status() === 500 ? "Invalid Software License" : "Trying to create a new Session";
            $data['status'] = $response->status();
            $data['qr'] = '';
            $data['message'] = $msg;
        }

        $response = [
            'response' => $whatsapp,
            'data' => $data
        ];

        return json_encode($response);
    }


    public function getDeviceStatus(Request $request): bool|string
    {
        $device_id   = $request->id;
        $whatsapp    = WhatsappDevice::where('id', $device_id)->where('user_id', auth()->user()->id)->first();
        $credentials = $whatsapp->credentials;
        $data = array();
        try {
            $checkConnection = Http::get(env('WP_SERVER_URL').'/sessions/status/'.$whatsapp->name);
            if ($whatsapp->status === "connected" || $checkConnection->status() === 200) {
                $whatsapp->status = 'connected';
                $res = json_decode($checkConnection->body());
                if (isset($res->data->wpInfo)) {
                    $wpNumber = str_replace('@s.whatsapp.net', '', $res->data->wpInfo->id);
                    $wpNumber = explode(':', $wpNumber);
                    $wpNumber = $wpNumber[0] ?? $whatsapp->credentials["number"];

                    try {
                        $credentials["number"] = $wpNumber;
                        $whatsapp->credentials = $credentials;
                    } catch (Exception $e) {
                        
                    }
                }
                $whatsapp->save();
                $data['status']  = 301;
                $data['qr']      = asset('assets/file/dashboard/image/done.gif');
                $data['message'] = 'Successfully connected WhatsApp device';
            }
        } catch (RequestException $e) {
            $data['status'] = $e->getCode();
            $data['qr'] = '';
            $data['message'] = $e->getMessage();
        } catch (\Exception $e) {
            $data['status'] = 500;
            $data['qr'] = '';
            $data['message'] = $e->getMessage();
        }

        $response = [
            'response' => $whatsapp,
            'data' => $data
        ];

        return json_encode($response);
    }
}