<?php

namespace App\Http\Controllers;

use App\Models\Candidate;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Whatsapp_tracker;

use App\Models\WhatsappMessage;
use Illuminate\Support\Facades\Crypt;
use DB;
use Mail;

class WhatsappTemplateController extends Controller
{
    //

    // public function CronJobProfileCompletion(){

    //     $users = Whatsapp_tracker::Select('user_id')->whereIn('user_id', function ($query) {
    //         $query->select('user_id')
    //             ->from('whatsapp_tracker')
    //             ->where('template_id', 1)
    //             ->where('created_at', '>=', now()->subDays(3));
    //     })
    //     ->groupby('user_id')
    //     ->get();
    //     $Candidates = Candidate::whereIn('user_id', $users)->with('educations', 'destination', 'user')->get();
    //     foreach ($Candidates as $Candidate) {
    //         if ($Candidate->educations->count() <= 0 || $Candidate->destination->count() <= 0) {
    //             $currentDate = now()->format('Y-m-d');
    //                 $tempdata = Whatsapp_tracker::whereDate('created_at', $currentDate)->where('template_id',2)->groupBy('user_id')->get()->toArray();
    //                 // dd($tempdata);
    //                 if($tempdata['user_id'] !== $Candidate->user_id){

    //                 $data['template'] = 'profile';
    //                 $data['user_id'] = $Candidate->user_id;
    //                 $data['name'] = $Candidate->user->name;
    //                 $data['sendTo'] = '918875501432';
    //                 $data['message'] = 'this is an testing message from graading';
    //                 $encrypted = Crypt::encryptString($Candidate->user_id);
    //                 $data['link'] = 'auth/reg_login/'.$encrypted;
    //                 $this->send_whatsapp($data);
    //             }
    //         }
    //     }
    
        
    // }
       


public function CronJobProfileCompletion()
{
    // die("1");
    $users = Whatsapp_tracker::select('user_id')
        ->whereIn('user_id', function ($query) {
            $query->select('user_id')
                ->from('whatsapp_tracker')
                ->where('template_id', 1)
                ->where('created_at', '>=', now()->subDays(3));
        })
        ->groupBy('user_id')
        ->get();

    $Candidates = Candidate::whereIn('user_id', $users)
        ->with('educations', 'destination', 'user')
        ->get();

    foreach ($Candidates as $Candidate) {
        if ($Candidate->educations->count() <= 0 || $Candidate->destination->count() <= 0) {
            $currentDate = now()->format('Y-m-d');
            $tempdata = Whatsapp_tracker::whereDate('created_at', $currentDate)
                ->where('template_id', 2)
                ->groupBy('user_id')
                ->get()
                ->toArray();

            $candidateFound = false;
            foreach ($tempdata as $data) {
                if ($data['user_id'] === $Candidate->user_id) {
                    $candidateFound = true;
                    break;
                }
            }
            // dd($Candidate);
            if (!$candidateFound) {
                $data['template'] = 'profile';
                $data['user_id'] = $Candidate->user_id;
                $data['name'] = $Candidate->user->name;

                $code = $Candidate->user->country_code == '' ? '91' : $Candidate->user->country_code;
                $phone = $code.substr(@$Candidate->user->phone, -10);


                $data['sendTo'] = $phone;
                $encrypted = Crypt::encryptString($Candidate->user_id);
                $data['link'] = 'auth/reg_login/'.$encrypted;
                $this->send_whatsapp($data);
                print_r($data['sendTo']. '<br>');
            }
        }
    }
}



// public function GetUserToSendWhatsapp($template){

//     $stages = ['Inquiry', 'Counselling'];
//     $usersPerPage = 250;
    
//     $page = 1;
//     $offset = ($page - 1) * $usersPerPage;
    
//     $users = User::whereIn('stages', $stages)->skip($offset)->take($usersPerPage)->get();
    
//     foreach($users as $user){
//         // $code = $user->country_code == '' ? '91' : $user->country_code;
//         // $phone = $code.substr(@$user->phone, -10);
//         // $name = $user->name;
//         // $id = $user->id;
//         $user->template = $template;
//         $phone = "918875501432";
//         $user->sendTo = $phone;
//         $user->user_id = $user->id;
//         // $encrypted = Crypt::encryptString($user->id);
//         // $user->link = 'auth/reg_login/'.$encrypted;
//         $user->message = "This is testing message to our Client";
//         $this->send_whatsapp($user);
//         echo $phone. '  <br> ';
//         die;
//     }
    

//     // $stages = ['Inquiry', 'Counselling'];
//     // $users = User::whereIn('stages', $stages)->take(1000)->get();
//     // dd($users);

// }

    public function send_email($oldUser){
        $data = array('data'=>$oldUser);
        // dd($data);
        Mail::send('mails.usa', $data, function($message) use($oldUser) {
            $message->to($oldUser->email, $oldUser->name)->subject
            ('German A1 Demo Language Session');
            $message->from(env('MAIL_USERNAME'),'Gradding Team');
        });
    }


    public function GetUserToSendWhatsapp($template){
        // Email
        // $users = DB::select("select *,u.id as id from users u inner join candidates c on (u.id = c.user_id) inner join candidate_destinations cd on (cd.candidate_id = c.id)  where (FIND_IN_SET(59,preferred_country) OR FIND_IN_SET(110,preferred_country) OR FIND_IN_SET(75,preferred_country) OR FIND_IN_SET(146,preferred_country) OR FIND_IN_SET(41,preferred_country) OR  FIND_IN_SET(62,preferred_country) OR FIND_IN_SET(69,preferred_country) OR preferred_country is null OR u.stages = 'Student backed out / Dropped') AND u.deleted_at is null order by u.id desc limit 1000");
        // // // dd($users);
        // foreach ($users as $key => $user) {
        //     // $user->email = "deepak@cognustechnology.com";
        //     $this->send_email($user);

        //     // die;
        // }
        // die;

        // Whatsapp
        // die("1");
        $stages = ['Inquiry', 'Counselling'];
        $stages = ['Application submitted','Application ready to submit','Student backed out / Dropped'];
        // $ids = [1876,1749,2294,218,1684,1804,1830,501,2069,2120,1758,2298,279,385,1091,122,2238,1158,1739,702,740,1472,1223,2069,517,689];


        // $ids = [3117,457,2253,2631,673,2926,3051,3392,2368,3028,1079,2910,2775,3039,3439,3015,3498,2362,3336,3571,630];
        // $users = User::whereIn('id', $ids)->get();

        $countryId = [59,110,75,146,41,62,69];
        $users = User::whereNotIn('stages', $stages)->with("candidate")->orderBy("id","desc")->get();
        // $users = User::whereIn('stages', $stages)->get();
        // $users = User::whereIn('id', $ids)->get();

        // $users = User::whereIn('id', $ids)->get();

        // $users = DB::select("select * from users u inner join candidates c on (u.id = c.user_id) where FIND_IN_SET(webinar_ids,2)");

        // select * from users u inner join candidates c on (u.id = c.user_id) inner join candidate_destinations cd on (cd.candidate_id = c.id)  where FIND_IN_SET(59,preferred_country) OR FIND_IN_SET(110,preferred_country) OR FIND_IN_SET(75,preferred_country) OR FIND_IN_SET(146,preferred_country) OR FIND_IN_SET(41,preferred_country) OR  FIND_IN_SET(62,preferred_country) OR FIND_IN_SET(69,preferred_country)

        // $users = DB::select("select *,u.id as id from users u inner join candidates c on (u.id = c.user_id) inner join candidate_destinations cd on (cd.candidate_id = c.id)  where (FIND_IN_SET(59,preferred_country) OR FIND_IN_SET(110,preferred_country) OR FIND_IN_SET(75,preferred_country) OR FIND_IN_SET(146,preferred_country) OR FIND_IN_SET(41,preferred_country) OR  FIND_IN_SET(62,preferred_country) OR FIND_IN_SET(69,preferred_country) OR preferred_country is null OR u.stages = 'Student backed out / Dropped') AND u.deleted_at is null");

        // $users = DB::select("select *,c.id as id from users u inner join candidates c on (u.id = c.user_id) inner join candidate_destinations cd on (cd.candidate_id = c.id)  where FIND_IN_SET(59,preferred_country)");

        // $users = DB::select('select * from users where stages = "document pending"');
 
        // Student backed out / Dropped
        // select *,c.id as candidate_id from users u inner join candidates c on (c.user_id = u.id) where length(phone) > 9 && length(phone) <= 12 and u.deleted_at is null and u.country = "India" and u.stages != "Student backed out / Dropped"  order by u.id desc

        $users = DB::select('select *,c.id as candidate_id from users u inner join candidates c on (c.user_id = u.id) where length(phone) > 9 && length(phone) <= 12 and u.deleted_at is null and u.country = "India" and u.id in(1231,2915,3739,5476,2362,5081,5437,4393,3428,4483,5471,5452,4269,870) order by u.id desc');
        // dd($users);

        // die;
        foreach($users as $key => $user){
            $user = (array)$user;
            // var_dump($user);die;
            // if(@$user->candidate->id != null){
                // $phone = @$user->country_code.substr(@$user->phone, -10);
                $phone = @$user['country_code'].substr(@$user['phone'], -10);
                // $name = $user->name;
                // $id = $user->id;
                // $phone = "918947025147";
                // $phone = "918875501432";
                // $phone = "919509439267";
                // $phone = "919982989959";
                // $phone = "919773368655";
                if($phone != "917048434227" && $phone != "919569112662"){
                    $user['sendTo'] = $phone;
                    // $encrypted = Crypt::encryptString($user->id);
                    $webinar_id = 10;
                    // $user['link'] = 'subscribe-to-webinar/'.base64_encode($webinar_id).'/'.base64_encode($user['id']);
                    echo $user['link'] = 'subscribe-to-webinar/'.base64_encode($webinar_id).'/'.base64_encode($user['candidate_id']);
                    // dd($user);
                    $this->send_whatsapp2($user);
                    echo $key." - ".$phone." " .$user['name']. " " .$user['id']  .'  <br> ';
                }
                // die;
            // }
        }

        Mail::send([], [], function ($message) {
            $message->to("deepak@cognustechnology.com")
                ->subject('whatsapp message sent')
                // here comes what you want
                ->setBody('<h1>data = </h1>', 'text/html'); // for HTML rich messages
        });
        die;
    }

    // Whatsapp Message
    public function send_whatsapp2($data=null){

       if($data == null || $data == ''){
           return ['status' => 0, 'msg' => 'data is required!'];
       }

       $data = (array)$data;

       $webInfo = [
           'GD' => ['siteFullName' => 'Gradding', 'siteEmail' => 'contact@gradding.com'],
       ];
      
       $siteName = 'GD';
       $options['siteFullName'] = $webInfo[$siteName]['siteFullName'];
       $options['siteEmail'] = $webInfo[$siteName]['siteEmail'];
       $options['name'] = $data['name'];
    //    $options['name'] = $data->name;
       $options['sendTo'] = $sendTo = $data['sendTo'];

       $integrationIds = [
           'GD' => '64d0a5da5f38929d8ac3e9a8',
       ];

       $nameSpaces = [
           'GD' => '4f3009db_722c_4219_8897_8f9f07a1f7a3',
       ];
       
       $integrationIds = $integrationIds[$siteName];
       $nameSpaces = $nameSpaces[$siteName];
        //$templateName = $templateName[$siteName][$data['template']];
       $templateData = $this->getWhatsappTemplate('webinar_coming_soon',$options, $data);
       $components = [];
        //after_webinar

       $data = [
           'destination' => [
               'integrationId' => $integrationIds,
               'destinationId' => $sendTo,
           ],
           'author' => [
               'role' => 'appMaker',
           ],
           'messageSchema' => 'whatsapp',
           'message' => [
               'type' => 'template',
               'template' => [
                   'namespace' => $nameSpaces,
                   'name' => 'webinar_is_live',
                   'language' => [
                       'policy' => 'deterministic',
                       'code' => 'en',
                   ],
                   'components' => [
                       [
                           'type' => 'body',
                           'parameters' => [

                                [
                                    'type' => 'text',
                                    'text' => '*'.ucwords($options['name']).'*',
                                ],
                                [
                                    'type' => 'text',
                                    'text' => '*https://zoom.us/j/99143384572?pwd=Ky83ck8xYndlUHFyRFRhZjdqNTRUQT09*',
                                ],

                              

                                
                                // [
                                //     'type' => 'text',
                                //     'text' => ''.base64_encode($data['candidate_id']).'',
                                // ],
                                
                                
                                // 1. webinar_coming_soon

                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."2 Septemeber".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."11:00 AM".'*',
                                // ],
                           
                                // 2. joinwebinar
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."9 September".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."1:00 PM".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."Study Abroad Counselling Session".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => ''."https://zoom.us/j/99745106305".'',
                                // ],
                                // 3. join_webinar_now 
                                // [
                                //     'type' => 'text',
                                //     'text' => ''."https://zoom.us/j/98568723955?pwd=NUJvRGNqeGdGdUdremxDZ3VzQTBiZz09".'',
                                // ],
                                // 4.uk_webinar_alert 
                                //  [
                                //     'type' => 'text',
                                //     'text' => '*'."16 Sept".'*',
                                // ],
                                // 5. webinar_uk_with_name 
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."Disha".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."16 Sept @ 1 PM".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."Disha".'*',
                                // ],
                                // 6. uk_01 

                                // 7. webinar_alert_01 
                               
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."Saturday".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."1 PM".'*',
                                // ],

                                // 8. germany_classes_start_01A
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."German A1 classes".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."30th October 2023".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."30th October 2023 (Monday)".'*',
                                // ],
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."8:00 PM - 9:00 PM".'*',
                                // ],
                                // ilets_demo_class_started
                                // [
                                //     'type' => 'text',
                                //     'text' => '*'."5 PM".'*',
                                // ],
                                // ilets_demo_class_started_01 
                                // [
                                //     'type' => 'text',
                                //     'text' => 'https://zoom.us/j/95952274047',
                                // ],
                              
                           ],
                       ],
                    //    [
                    //     "type" => "header",
                    //         "parameters" => [
                    //             [
                    //                 "type" =>"image",
                    //                 "image" => [
                    //                     "link" => "https://www.gradding.com/_USA.png", // comming soon
                    //                     // "link" => "https://www.gradding.com/WhatsApp.mp4", // join soon
                    //                 ]
                    //             ]
                    //         ]
                    //     ],
                    [
                        'type' => 'button',
                        "sub_type" => "url",
                        "index" => "0",
                        'parameters' => [
                            [
                                'type' => 'text',
                                // 'text' => $data['link'],
                                'text' => '99143384572?pwd=Ky83ck8xYndlUHFyRFRhZjdqNTRUQT09',
                            ]
                        ],
                    ],
                   ]
               ],
           ],
       ];
       // print_r($data);
       // die;
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, 'https://api.smooch.io/v1.1/apps/64cb7076c2c33afe04178f83/notifications');
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
       curl_setopt($ch, CURLOPT_USERPWD, 'app_64d0eb6b91ea27ed133f3684' . ':' . 'K2UvYWXCdhf7_o4VzH36ZwR6fXsCbzogUkqMMiQV3J4kiMieDh0lNahEytd00vX9153rUpH30WFh_B0YmYuTkw');

       $headers = array();
       $headers[] = 'Content-Type: application/json';
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

       $result = curl_exec($ch);
       if (curl_errno($ch)) {
           // echo 'Error:' . curl_error($ch);
           return false;
       }
       $result = json_decode($result,1);
      

       curl_close($ch);
       return true;
    }


    // Whatsapp Message
    public function send_whatsapp($data=null){
        // dd($data);
     // Configure::write("debug",1);
        if($data == null || $data == ''){
            return ['status' => 0, 'msg' => 'data is required!'];
        }
        if($data['sendTo'] == null || $data['sendTo'] == ''){
            return ['status' => 0, 'msg' => 'Phone Number is required!'];
        }
        // else if(!isset($options['siteName']) || $options['siteName'] == ''){
        //     return ['status' => 0, 'msg' => 'siteName is required!'];
        // }
        // else if(!isset($options['sendTo']) || $options['sendTo'] == ''){
        //     return ['status' => 0, 'msg' => 'sendTo is required!'];
        // }


        $user_id = $data['user_id'];
        $template = $data['template'];
        $message = @$data['message'];
        $webInfo = [
            'GD' => ['siteFullName' => 'Gradding', 'siteEmail' => 'contact@gradding.com'],
        ];
       
        $siteName = 'GD';
        // $siteName = $options['siteName'];
        // $options['siteFullName'] = 'Gradding';
        $options['siteFullName'] = $webInfo[$siteName]['siteFullName'];
        $options['siteEmail'] = $webInfo[$siteName]['siteEmail'];

        $options['sendTo'] = $sendTo = $data['sendTo'];
        // $options['sendTo'] = $sendTo = trim(str_replace(['-','+'],'',$options['sendTo']));
        // $sendTo = '919602097198';
        // echo $siteName
        $integrationIds = [
            'GD' => '64d0a5da5f38929d8ac3e9a8',
        ];

        $nameSpaces = [
            'GD' => 'bfb31f77_506b_45e0_a97b_94bf47a418f1',
        ];

        $templateName = [
 
            'GD' => [
                'register' => ['register_ads_05','1'],
                'profile' => ['profile_complete_02','2'],
                'counselling' => ['counselling','3'],
                'documentation_collection' => ['documentation_collection','4'],
                'no_contact' => ['no_contact','5'],
                'no_contact_follow-up' => ['no_contact_follow','6'],
                'reminder_for_documention' => ['reminder_for_documention','7'],
                'admission' => ['admission','8'],
                'application_status' => ['application_status','9'],
                'joinwebinar' => ['joinwebinar','10'],
                'reminder_for_documentation' => ['reminder_for_documentation_02','11'],
                'ready_for_application' => ['ready_for_application','12'],
                'webinar_coming_soon' => ['webinar_coming_soon','13'],
                'custom' => ['custom','14'],
                'website_watsapp_button_01' => ['website_watsapp_button_01','15'],
                'country_selection' =>  ['country_selection','16'],
                'event_register' =>  ['event_register','17'],
            ],
        ];
        
        $integrationIds = $integrationIds[$siteName];
        $nameSpaces = $nameSpaces[$siteName];
        $template = $templateName[$siteName][$template];
        $templateName = $template[0];
        $template_Id = $template[1];
        $templateData = $this->getWhatsappTemplate($template,$options, $data);
        // pr($templateData['bodyData']); die;
        // print_r($templateData);
        // die;
        $components = [];
        if(isset($templateData['bodyData'])){
            array_push($components, [
                'type' => 'body',
                'parameters' => $templateData['bodyData'],
            ]);
        }  
        
        if(isset($data['link'])){
            array_push($components, [
                'type' => 'button',
                "sub_type" => "url",
                "index" => "0",
                'parameters' => [
                    [
                        'type' => 'text',
                        'text' => $data['link'],
                    ]
                ],
            ],);
        }

        if(isset($data["img"]) != "" && isset($data['img'])){
            // image  //
            array_push($components, 
                [
                    "type" => "header",
                    "parameters" => [
                        [
                            "type" =>"image",
                            "image" => [
                                "link" => $data['img']
                                // "filename" => $options['siteFullName']
                            ]
                        ]
                    ]
                ]
            );
        }

        $data = [
            'destination' => [
                'integrationId' => $integrationIds,
                'destinationId' => $sendTo,
            ],
            'author' => [
                'role' => 'appMaker',
            ],
            'messageSchema' => 'whatsapp',
            'message' => [
                'type' => 'template',
                'template' => [
                    'namespace' => $nameSpaces,
                    'name' => $templateName,
                    'language' => [
                        'policy' => 'deterministic',
                        'code' => 'en',
                    ],
                    'components' => $components
                    // 'components' => [
                    //     [
                    //         'type' => 'body',
                    //         'parameters' => $templateData['bodyData'],
                    //     ],
                    //     [
                    //         'type' => 'button',
                    //         "sub_type" => "url",
                    //         "index" => "0",
                    //         'parameters' => $templateData['btnData'],
                    //     ],
                    // ],
                ],
            ],
        ];
        // print_r($data);
        // die;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.smooch.io/v1.1/apps/64cb7076c2c33afe04178f83/notifications');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_USERPWD, 'app_64d0eb6b91ea27ed133f3684' . ':' . 'K2UvYWXCdhf7_o4VzH36ZwR6fXsCbzogUkqMMiQV3J4kiMieDh0lNahEytd00vX9153rUpH30WFh_B0YmYuTkw');

        $headers = array();
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            // echo 'Error:' . curl_error($ch);
            return false;
        }
        $result = json_decode($result,1);

        if(isset($message)){
            $message = $message;
        }else{
            $message = '';
        }
        $whatsapp = new Whatsapp_tracker;
        $whatsapp->user_id = $user_id;
        $whatsapp->message = $message;
        $whatsapp->phone = $data['destination']['destinationId'];
        $whatsapp->status = 1;
        // $whatsapp->conversation_id = $result['notification']['_id'];
        $whatsapp->template_id = $template_Id;
        $whatsapp = $whatsapp->save();
        // if($options["userId"] != ''){           
            // if(!isset($result['error'])){              
            //     // Configure::write("debug",1);
            //     # last activity update
            //     $this->loadModel("LeadManagement");
            //     $this->LeadManagement->updateAll(["last_activity_source" => "'whatsapp'", "last_activity"=> "'".date("Y-m-d h:i:s")."'"],["cust_id" => $options["userId"]]);
            // }
        // }

        // if($result['notification']['_id'] != null){
        //     if($template == "custom"){
        //         $template = $options['message'];
        //     }else{
        //         $template = "Template: ".$template;
        //     }

        //     $this->loadModel("WhatsappTracker");
        //     $saveData = [
        //         "user_id" => isset($options["userId"]) ? $options["userId"]:0,
        //         "message" => $template,
        //         "phone" => $sendTo,
        //         "conversation_id" => $result['notification']['_id'],
        //         "website" => $siteName
        //     ];
        //     if(isset($options["campaign_id"])){
        //         $saveData["campaigns_id"] =  $options["campaign_id"];
        //     }
        //     $this->WhatsappTracker->save($saveData);
        // }
        // var_dump($result['error']);

        // echo '<pre>';
        // print_r($options);

        curl_close($ch);

        return true;
    }

    // Get Whatsapp Template

    private function getWhatsappTemplate($template,$messageData, $data){
        // pr($template); die;
        // $messageData = ['name'=>'Deepak','email','siteName'=>'GAH','siteFullName'=>'Global Assignment help','siteEmail'=>'help@globalassignmenthelp.com','password'=>'user123','order_code'=>'B45678','order_id'=>'213123','amount'=>'us$ 45','message'=>'','topic'=>'','ddate'=>''];
        $downloadApp = [
            'GAH' => 'bit.ly/gah-App',
            'IAH' => 'bit.ly/iah-App',
            'IAH_AU' => 'bit.ly/iahau-App',
            'AP' => 'bit.ly/ap-App',
            'GAH_AU' => 'bit.ly/gahau-App',
            'AD' => 'bit.ly/ad-App'
        ];

        // $loginKey = base64_encode(base64_encode($messageData['siteName'] . "?$&@" . $messageData['userId']));
        switch($template){
            case 'register':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                    // [
                    //     'type' => 'text',
                    //     'text' => ''."🎉 Welcome to Gradding! 🌍 Discover our exclusive study abroad features!".'',
                    // ],

                    [
                        'type' => 'text',
                        'text' => '*'."- University / Course Shortlisting".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."- Application Submissions".'*',
                    ],                       
                    [
                        'type' => 'text',
                        'text' => '*'."- Test Prep".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."- Scholarships Application".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."- Education Loans Assistance".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."- Visa Assistance & much more!".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$data['sendTo'].'*',
                    ],

                    [
                        'type' => 'text',
                        'text' => ''.$data['password'].'',
                    ],
                ];
                break;
            case 'event_register':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$data['sendTo'].'*',
                    ],

                    [
                        'type' => 'text',
                        'text' => ''.$data['password'].'',
                    ],
                ];
                break;
            case 'profile':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => "🌟Just a friendly reminder to complete your profile and unlock exclusive benefits!",
                    ],                        
                    [
                        'type' => 'text',
                        'text' => ''."- University / Course Shortlisting".'',
                    ],
                    [
                        'type' => 'text',
                        'text' => ''."- Relevant Insights".'',
                    ],
                    [
                        'type' => 'text',
                        'text' => ''."- Hand Picked Courses".'',
                    ],
                    [
                        'type' => 'text',
                        'text' => ''."- Expert Counselling".'',
                    ],
                    [
                        'type' => 'text',
                        'text' => ''."- A More Personalized Experience".'',
                    ],
                ];  
                break;
            // case 'profile_complete':
            //     $bodyData = [
            //         [
            //             'type' => 'text',
            //             'text' => '*'.$data['name'].'*',
            //         ],[
            //             'type' => 'text',
            //             'text' => "🎉 Welcome to Gradding! 🌍 Discover our exclusive study abroad features!",
            //         ],                        
            //         [
            //             'type' => 'text',
            //             'text' => ''."- University / Course Shortlisting".'',
            //         ],
            //         [
            //             'type' => 'text',
            //             'text' => ''."- Relevant Insights".'',
            //         ],
            //         [
            //             'type' => 'text',
            //             'text' => ''."- Hand Picked Courses".'',
            //         ],
            //         [
            //             'type' => 'text',
            //             'text' => ''."- Expert Counselling".'',
            //         ],
            //         [
            //             'type' => 'text',
            //             'text' => ''."- A More Personalized Experience".'',
            //         ],
            //     ];
            //     break;
            case 'counselling':
                $bodyData = [
                        [
                            'type' => 'text',
                            'text' => '*'.$data['name'].'*',
                        ],
                        [
                            'type' => 'text',
                            'text' => ''."16 Aug, 2023".'',
                        ],
                        [
                            'type' => 'text',
                            'text' => ''."1:00 PM".'',
                        ],
                        [
                            'type' => 'text',
                            'text' => ''."https://live.zoho.in/rXVA4kfo6l".'',
                        ],
                ];      
                break;
            case 'payment_reminder':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['order_code'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['amount'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['order_code'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['topic'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => $downloadApp[$messageData['siteName']],
                    ]
                ];
                break;
            case 'delivery':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['order_code'].'*',
                    ], 
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['topic'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => $downloadApp[$messageData['siteName']],
                    ]
                ];
                break;
            case 'custom':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => $data['message'],
                    ], 
                ];
                break;
            case 'partial_payment':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['name'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['order_code'].'*',
                    ], 
                    [
                        'type' => 'text',
                        'text' => '*'.trim($messageData['topic']).'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['amount'].'*',
                    ]
                ];
                break; 
            case 'lead_followup':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.trim($messageData['name']).'*',
                    ]
                ];
                break;
            case 'send_password':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['name'].'*',
                    ], 
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['email'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['password'].'*',
                    ],
                ];
                break;
             case 'image_code':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['1'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => ''.$messageData['2'].'',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['3'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '✅ *'.$messageData['4'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '✅ *'.$messageData['5'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '✅ *'.$messageData['6'].'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['7'].'*',
                    ],
                ];                       
                break; 
            case 'joinwebinar':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.ucFirst($data['name']).'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."August 10, 2023".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."4:00 PM (GMT)".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => '*'."Financial Planning for Studying Abroad".'*',
                    ],
                    [
                        'type' => 'text',
                        'text' => "https://live.zoho.in/FWGfbTVj1e",
                    ],
                    // [
                    //     'type' => 'text',
                    //     'text' => '✅ *'.$messageData['6'].'*',
                    // ],
                    // [
                    //     'type' => 'text',
                    //     'text' => '*'.$messageData['7'].'*',
                    // ],
                ];                       
                break; 
                case 'webinar_coming_soon':
                    $bodyData = [
                        [
                            'type' => 'text',
                            'text' => '*'.$data['name'].'*',
                        ],   [
                            'type' => 'text',
                            'text' => ''."26 August".'',
                        ],
                        [
                            'type' => 'text',
                            'text' => ''."1:00 PM".'',
                        ],
                    ];                       
                break;  
            case 'notification':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$messageData['1'].'*',
                    ]
                ];                       
                break;
            case 'documentation_collection':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                ];                       
                break;
            case 'reminder_for_documentation':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                ];                       
                break;
            case 'ready_for_application':
                $bodyData = [
                    [
                        'type' => 'text',
                        'text' => '*'.$data['name'].'*',
                    ],
                ];                       
                break;
            case 'country_selection';
                $bodyData = [
                ];            
            break;
            default:
                return false;
                break;
        }       

        // $btnData = [
        //     [
        //         'type' => 'text',
        //         'text' => $loginKey
        //     ]
        // ];    
        
        // return ['bodyData'=>$bodyData, 'btnData'=>$btnData];
        $returnArr = ['bodyData'=>$bodyData];

        if($template != 'custom' && $template != 'send_password' && $template != 'country_selection' && isset($messageData['userId'])){
            // $btnData
            $returnArr['btnData'] = [
                [
                    'type' => 'text',
                    'text' => $data['link']
                ]
            ];    
        }

        
        
        return $returnArr;
    }

    public function WhatsappInquiry(Request $request){
        $code = explode('@#$?',$request->country);
        $code = end($code);
    
        $data = [];
    
        $data['sendTo'] = $code.$request->phone;
        $data['user_id'] = @$data['id'] == '' ? '' : @$data['id'];
        $data['template'] = 'website_watsapp_button_01';
        $data['message'] = $request->message;
        $this->send_whatsapp($data);
    
        $message = new WhatsappMessage();
        $message->message = $request->message;
        $message->country = $request->country;
        $message->phone = $request->phone;
        $message->save();
        return response()->json(['status'=>1]);
    }

    // Send Whatsapp

    // public function sendwhatsapp(Request $request){

    //     if ($this->request->is('post')) {
    //        $this->loadModel("Order");
    //          $order_id = $this->request->data['order_id'];
    //          $msg = $this->request->data['msg'];
    //          $order_data = $this->Order->find('all', array('conditions' => array('id' => $order_id)))[0]['Order'];
    //          // print_r($order_data);die;
    //          if($this->request->data['type'] != '' && $this->request->data['type'] == 1 && !empty($order_data)){
    //             $loginKey = base64_encode(base64_encode($order_data['site_sort_name']."?$&@".$order_data['cust_id']."?$&@".$order_data['id']));
           
    //            $this->loadModel("websitephone");
    //            $websitephone = $this->websitephone->find('all', array(
    //                'fields' => array('websitephone.*', 'Country.code'),
    //                'joins' => array(
    //                    array(
    //                        'table' => 'country', 'alias' => 'Country', 'type' => 'inner',
    //                        'foreignKey' => false,
    //                        'conditions' => array('websitephone.site_sort_name' => $order_data['site_sort_name'], 'websitephone.country=Country.name')
    //                    )
    //                )
    //            ));

    //            $match_by_cust = 0;
    //            foreach ($websitephone as $value) {
    //                $country_list_name = $value['websitephone']['country'];
    //                $country_list_code = $value['Country']['code'];
    //                $country_list_toll_free = $value['websitephone']['toll_free'];
    //                $country_list_whatsup = $value['websitephone']['whatsup'];
    //                $country_list_default = $value['websitephone']['default'];
    //                if ($country_list_name == $order_data['customer_country']) {
    //                    $website_phone = $country_list_toll_free;
                      
    //                    $match_by_cust = 1;
    //                }
    //                if ($country_list_default == 1) {
    //                    $toll_free_default = $country_list_toll_free;
    //                }
    //            }

    //            if ($match_by_cust == 0) {
    //                $website_phone = $toll_free_default;
    //            }

    //            $website_phone = $websitephone[0]['websitephone']['toll_free'];
    //            // print_r($website_phone);die;
    //              $cust_phone = $order_data['customer_phone'];
    //            $cust_phone = str_replace('-','', $cust_phone);
    //           /*if($this->request->data['site_sort_name'] == 'GAH'){
    //              $msgStr = '3469345~'. $order_data['customer_name'].'~'.$order_data['order_code'].'~'.substr(htmlentities(strip_tags($msg)),0,40).'..~'.urlencode($website_phone);  
             
    //             //$cust_phone = '8947025147'; 
    //            // $loginKey = 'UjBGSVB5UW1RRGd3TkRnNQ==';  
    //            $whatsappMessage = urlencode('<?xml version="1.0" encoding="ISO-8859-1" ? >
    //            <!DOCTYPE MESSAGE SYSTEM "http://127.0.0.1:8181/psms/dtd/messagev12.dtd">
    //            <MESSAGE VER="1.2">
    //            <USER USERNAME="GlobalasWA" PASSWORD="ueuhe@#r4" CH_TYPE="4"/>
    //            <SMS UDH="0" CODING="1" TEXT="" TEMPLATEINFO="'.$msgStr.'" MSGTYPE="3" B_URLINFO="'.$loginKey.'" PROPERTY="0"
    //            ID="1" TEMPLATE="" EMAILTEXT="" ATTACHMENT="">
    //            <ADDRESS FROM="447388406225" TO="'.$cust_phone.'" EMAIL="" SEQ="1" TAG="some clientside random
    //            data"/>
    //            </SMS>
    //            </MESSAGE>');
    //            // print_r($whatsappMessage);die;
    //            // $ctx = stream_context_create(array('http'=>
    //            //         array(
    //            //         'timeout' => 60,
    //            //         )));

    //            file_get_contents("https://api.myvfirst.com/psms/servlet/psms.Eservice2?data=" . $whatsappMessage . "&action=send");
    //           }else if($this->request->data['site_sort_name'] == 'IAH'){
    //                $str = '3567931~'. $order_data['customer_name'].'~'.$order_data['order_code'].'~'.$msg.'~'.urlencode($website_phone);
    //                // $cust_phone = '8947025147';
    //                $this->sendMessage('447384043559',$cust_phone,$str,$loginKey,$this->request->data['site_sort_name']);
    //            }*/
    //            $messageData = [
    //                'name' => $order_data['customer_name'],
    //                // 'email'=>'testcognus@gmail.com',
    //                'siteName' => $this->request->data['site_sort_name'],
    //                // 'password'=>'user123',
    //                'order_code' => $order_data['order_code'],
    //                'order_id' => $order_data['id'],
    //                // 'amount' => $wpCost,
    //                // 'words' => $order_id['Order']['words'],
    //                'message' => substr(htmlentities(strip_tags($msg)),0,40),
    //                // 'topic' => $order_id['Order']['topic'],
    //                // 'ddate' => date("d M",strtotime($order_id['Order']['ddate'])),
    //                'sendTo' => $cust_phone,
    //                'userId' => $order_data['cust_id'],
    //            ];
    //            $return = $this->send_whatsapp('clarification',$messageData);

    //        }
    //          echo 'success';
    //          exit;
    //     }
    // }

    public function webhook(Request $request){

        $data = $request->all();

        // $number = $data->events[0]->message->source->client->externalId;

        $events = $data['events'][0];
        $type = $events['type'];

        $number = $events['payload']['activity']['source']['client']['externalId'];

        if(strpos($type,"read")){
           
        }

        if($number == '918947025147'){
            Mail::send([], [], function ($message) use ($data,$number,$type) {
                $message->to("deepak@cognustechnology.com")
                  ->subject('Whatsapp by '.$number." type = ".$type)
                  // here comes what you want
                 
                  ->setBody('<h1>data = </h1>'.json_encode($data['events']), 'text/html'); // for HTML rich messages
            });
        }


        
    }

}

