comm = $comm; } protected function interaktAuthHeader(): string { return env('INTERAKT_API_AUTH', 'Basic S1BnVWoxRGZUcWpTYVl2OG9ZN3lEbkk2YjlXTzUtZXhvOWpMQ3RIN3ZJVTo='); } protected function sendMsg($number, $message) { Log::debug(print_r([$number, $message], true)); $params = ["countryCode" => "+91", "phoneNumber" => $number, "callbackData" => "some text here", "type" => "Text", "data" => ["message" => $message] ]; $response = Http::withHeaders(['Authorization' => $this->interaktAuthHeader()]) ->post('https://api.interakt.ai/v1/public/message/', $params); Log::debug(print_r($response, true)); } protected function deliverSessionText($number, $message, $session, $contact): void { if (!$session || !$contact) { $this->sendMsg($number, $message); return; } $mode = $this->comm->resolveMode($session); if ($this->comm->shouldSendWhatsApp($mode)) { $this->sendMsg($number, $message); } if ($this->comm->shouldSendEmail($mode)) { $this->comm->queueEmailFromText($session, $contact, $message); } } public function webhook(Request $request) { Log::debug('===== Webhook ======'); $post = $request->all(); Log::debug(print_r($post, true)); if(isset($post['type']) && $post['type'] == "message_received") { return response()->json([]); } if(!isset($post['entry'][0]['changes'][0]['value']['messages'][0])) { return response()->json([]); } $post = $post['entry'][0]['changes'][0]['value']['messages'][0]; //Log::debug(print_r($post, true)); $domain = 'https://road.xltr.in/'; // $number = $post['data']['customer']['phone_number']; // $data['from'] = '91'.$post['data']['customer']['phone_number']; // $data['text'] = $post['data']['message']['message']; $number = substr($post['from'], -10); $data['from'] = $post['from']; $data['text'] = $post['text']['body']; //CREST_VERIFY_LMS_1692788174-76994ced-b2da-4920-814b-df2cbb10aC4c $reply = ''; $session_data = []; $sessions = []; $finalised = false; $botSess = Rapiwha::where('from', $data['from'])->where('created_at', '>=', date("Y-m-d H:i:s", strtotime("now")-88200 ) )->orderby('created_at', 'desc')->first(); Log::debug(print_r($data, true)); if(strpos($data['text'],'CREST_VERIFY_') === 0) { list($code, $uid) = explode('_', str_replace('CREST_VERIFY_', '', $data['text']) ); if($code == 'LMS') { $contact = LambdaRequest::getrequest('contact', 'contact/get_one', ['id'=>$uid], env('LAMBDA_ACCESS_TOKEN', 'default_value') ); $contact = $contact->data->item; $access_token = User::where('user_id', $contact->user_id)->first()->access_token; $response = LambdaRequest::postrequest('contact', 'contact/update', ['id' => $uid, 'position'=>$contact->position, 'is_verified' => true ], $access_token ); $reply = 'Greetings ' . $response->data->item->name ."\n"; $reply .= 'You have Successfully registered for Paramedic Training Course'."\n"; $reply .= "\n" . 'Please click on the below link to view the available courses and start learning.'; $reply .= "\n" . 'https://road.xltr.in/lmscourse/'.$response->data->item->id; $rsdata = ['to' => $number, 'text' => json_encode(['countryCode'=>'+91','phoneNumber'=>$number,'callbackData'=>rand(10000,99999).'-'.$response->data->item->id,'type'=>'Template','template'=>['name'=>'paramedic_course_registration_success','languageCode'=>'en','bodyValues'=>[$response->data->item->name,$response->data->item->id] ] ]), 'is_sent' => 0, 'session_id' => 0, 'contact_id' => $response->data->item->id, 'status' => 1 ]; DB::table("raphiwa_send")->insert($rsdata); return response()->json([]); } else if($code == 'USER') { $user = LambdaRequest::getrequest('ums', 'users/get_one', ['id'=>$uid], env('LAMBDA_ACCESS_TOKEN', 'default_value') ); $user = $user->data->item; $toupdate = ['id' => $user->id, 'pincode' => $user->pincode, 'address' => $user->address, 'city' => $user->city, 'state' => $user->state, 'email' => $user->email, 'is_active' => true, 'status' => 'active' ]; $response = LambdaRequest::postrequest('ums', 'users/update', $toupdate, env('LAMBDA_ACCESS_TOKEN', 'default_value') ); Log::debug(print_r($toupdate, true)); $reply = 'Dear ' . $user->firstname .','."\n"; $reply .= 'You have successfully verified your CREST account'."\n"; $reply .= "\n" . 'You can now login to your CREST app using the email and password you have used while registering'; $reply .= "\n" . 'Email: '.$user->email; $reply .= "\n" . 'Password: '.$user->password; $reply .= "\n" ."\n" . 'Greetings'."\n" .'CREST Team'; } else { $response = LambdaRequest::postrequest('contact', 'contact/update', ['id' => $uid, 'position'=>'india', 'is_verified' => true ], env('LAMBDA_ACCESS_TOKEN', 'default_value') ); $session = Session::where('code', $code)->first(); $contact = $response->data->item; $reply = 'Greetings ' . $contact->name ."\n"; $reply .= 'You have Successfully registered for Crest session "'.$session->number.' ('.$session->type.') "'."\n"; $reply .= 'Please find the details below'."\n"; $reply .= 'Venue: ' . $session->venue . "\n"; $reply .= 'Address: ' . $session->address . "\n"; $reply .= 'Timings:' . "\n"; $dates = json_decode($session->dates); foreach($dates->date as $i => $date){ $reply .= date("d M, Y", strtotime($date) ) . ' at ' . date("h:iA", strtotime($dates->start[$i]) ) .' - ' . date("h:iA", strtotime($dates->end[$i]) ) . "\n"; } $reply .= "\n" . 'You can use this chat as your self assistance for getting details, download your certificate etc.'; Session::where('code', $code)->increment('reg_confirmed'); $this->deliverSessionText($number, $reply, $session, $contact); return response()->json([]); } $this->sendMsg($number, $reply); return response()->json([]); // if($code == 'Y8WUVES7VIdRNB4gOEe7') { // return response()->json(['autoreply' => $reply]); // } else { // return response()->json([]); // } } if($botSess && !$finalised) { $session_data = (array)json_decode($botSess->session_data); Log::debug(print_r($session_data, true)); if(isset($session_data['session'])) { $sess = $session_data['session_data']; $reply = 'We can see that you have registered for '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n"; //$finalised = true; } } //Log::debug($reply); if(!$botSess && !$finalised) { $response = LambdaRequest::getrequest('contact', 'contact/get_all', ['source'=>'dynamodb', 'search' => json_encode(['phone' => $number]), 'fields' => json_encode(['session_code', 'present', 'type']) ], env('LAMBDA_ACCESS_TOKEN', 'default_value') ); $users = []; Log::debug(print_r($response, true)); if( sizeof($response->data->items) > 0 ) { foreach($response->data->items as $item) { if(isset($item->type) && $item->type == 'lmsuser') { $reply = 'Greetings ' . $item->name ."\n"; $reply .= 'You have Successfully registered for Paramedic Training Course'."\n"; $reply .= "\n" . 'Please click on the below link to view the available courses and start learning.'; $reply .= "\n" . 'https://road.xltr.in/lmscourse/'.$item->id; $this->sendMsg($number, $reply); $rsdata = ['to' => $number, 'text' => json_encode(['countryCode'=>'+91','phoneNumber'=>$number,'callbackData'=>rand(10000,99999).'-'.$item->id,'type'=>'Template','template'=>['name'=>'paramedic_course_registration_success','languageCode'=>'en','bodyValues'=>[$item->name,$item->id] ] ]), 'is_sent' => 0, 'session_id' => 0, 'contact_id' => $item->id, 'status' => 1 ]; DB::table("raphiwa_send")->insert($rsdata); return response()->json([]); return response()->json([]); } if( isset($item->session_code) ) { $sessions[] = $item->session_code; $users[$item->session_code] = $item->id; } } //Log::debug(print_r($sessions, true)); $sessions = DB::table('sessions')->wherein('code', $sessions)->orderby('created_at', 'desc')->get(); //$sessions = DB::table('sessions')->wherein('code', $sessions)->where('start_date', '>=', date("Y-m-d 00:00:00", strtotime("now") ) )->orderby('created_at', 'desc')->get(); //Log::debug(print_r($sessions, true)); if($sessions->count() > 1) { $reply = 'We can see that you have registered for multiple future Crest events. Please reply for which crest session you want to communicate'."\n\n"; $session_data['available_sessions'] = $sessions->toArray(); $session_data['available_users'] = $users; $count = 1; foreach($sessions->toArray() as $sess) { $session_data['session_selection'] = [(string)$count => $sess->code ]; $reply .= 'Reply '.$count.' if you want to select '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n"; $count++; } $finalised = true; } else { $sess = $sessions->toArray(); $sess = $sess[0]; $session_data['session'] = $sess->code; $session_data['session_data'] = $sess; $session_data['user'] = $users[$sess->code]; $reply = 'We can see that you have registered for '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n"; } } else { $reply = 'Thank you for your interest in Crest. we can see that you have not registered for amy future Crest event.'; $finalised = true; } } //echo '
'; print_r($session_data); exit;

        if(!isset($session_data['session']) && !$finalised ) {
            $count = 1;
            if(isset($session_data['available_sessions'])) {
                foreach($session_data['available_sessions'] as $sess) {
                    if($count == $data['text']) {
                        $session_data['session'] = $sess->code;
                        $session_data['session_data'] = $sess;
                        $session_data['user'] = $session_data['available_users']->{$sess->code};
                        $reply = 'You have selected '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n";
                        $data['text'] = 'hi';
                        //$finalised = true;
                    }
                    $count++;
                }
            }
        }

        if(isset($session_data['session']) && !$finalised) {
            switch(Str::slug($data['text'], '_')) {
                case '1':
                    $reply = 'Here is the link to the session website: ' . $domain . 'microsite/' . $session_data['session_data']->type . '-' . $session_data['session_data']->code;
                    break;
                case '2':
                    $reply = 'Please find the details below'."\n\n";
                    $reply .= 'Venue: ' . $session_data['session_data']->venue . "\n\n";
                    $reply .= 'Address: ' . $session_data['session_data']->address . "\n\n" . "\n\n";
                    $reply .= 'Timings:' . "\n\n";
                    $dates = json_decode($session_data['session_data']->dates);
                    foreach($dates->date as $i => $date){
                        $reply .= date("d M, Y", strtotime($date) ) . ' at ' . date("h:iA", strtotime($dates->start[$i]) ) .' - ' . date("h:iA", strtotime($dates->end[$i]) ) . "\n\n";
                    }
                    break;
                case '3':
                    $reply = 'Here is the link to the session website: ' . $domain . 'brochure/' . $session_data['session_data']->code;
                    break;
                case '4':
                    $response = LambdaRequest::getrequest('contact', 'contact/get_one', ['id'=>$session_data['user']], env('LAMBDA_ACCESS_TOKEN', 'default_value') );
                    $doctor = $response->data->item;
                    if(isset($doctor->present) && $doctor->present == 'yes' && isset($doctor->feedback) && $doctor->feedback == 'yes') {
                        $output = Creation::certificate($session_data['session_data'], $doctor);
                        $filename = $output['filename'];
                        $certUrl = $domain . 'storage/certificate/'.$session_data['session_data']->type.'/'.$filename;
                        $sess = Session::find($session_data['session_data']->id);

                        if ($sess) {
                            $this->comm->dispatchForContact($sess, $doctor, [
                                'id' => 0,
                                'template_code' => 'crest_certificate_attached',
                                'template_body' => "Dear {{RECIPIENT_NAME}},\n\nYour certificate for {{SESSION_NAME}} on {{SESSION_DATE}} is ready.\n\nView your certificate: " . $certUrl,
                                'template_title' => 'Your CREST Certificate',
                                'header_values' => [$certUrl],
                                'body_params' => 'RECIPIENT_NAME||SESSION_NAME||SESSION_DATE',
                                'button_params' => '',
                            ]);
                        }

                        $reply = 'We will generate your certificate and send it to you in a while, please give us few minutes.';
                    } else if(isset($doctor->present) && $doctor->present == 'yes') {
                        $reply = 'You have not filled up the feedback form sent to you. Please submit the feedback and request for certificate again.';
                    } else {
                        $reply = 'You have not attended the session or not marked attended.';
                    }                    
                    break;

                default:
                    $reply .= 'Please select what do you want to do'."\n\n";
                    $reply .= 'Reply 1 if you want link to the session website'."\n\n";
                    $reply .= 'Reply 2 if you want to know about session location and timings'."\n\n";
                    //$reply .= 'Reply 3 if you want to know about session agenda and speakers'."\n\n";
                    $reply .= 'Reply 3 if you want to download session brochure'."\n\n";
                    $reply .= 'Reply 4 if you want to download your certificate'."\n\n";
                    break;
            }
        }

        $data['session_data'] = json_encode($session_data);
        //echo $reply; echo '
'; print_r($data); exit;
        if($botSess) {
            unset($data['event']);
            $data['msg_history'] = json_decode($botSess->msg_history);
            $data['msg_history'][] = $data['text'];
            $data['msg_history'] = json_encode($data['msg_history']);
            Rapiwha::where('id', $botSess->id)->update($data);
        } else {
            $data['msg_history'] = json_encode([$data['text']]);
            Rapiwha::create($data);
        }
        $this->deliverBotReply($number, $reply, $session_data);
        return response()->json([]);
    }

    protected function deliverBotReply($number, $reply, array $session_data): void
    {
        if (!isset($session_data['session_data']) || !isset($session_data['user'])) {
            $this->sendMsg($number, $reply);
            return;
        }

        $sess = Session::find($session_data['session_data']->id ?? 0);
        if (!$sess) {
            $this->sendMsg($number, $reply);
            return;
        }

        $response = LambdaRequest::getrequest(
            'contact',
            'contact/get_one',
            ['id' => $session_data['user']],
            env('LAMBDA_ACCESS_TOKEN', 'default_value')
        );
        $contact = $response->data->item ?? null;

        if ($contact) {
            $this->deliverSessionText($number, $reply, $sess, $contact);
        } else {
            $this->sendMsg($number, $reply);
        }
    }

    public function receive(Request $request) {
        Log::debug('===== Receive ======');
        $domain = 'https://road.xltr.in/';
        $post = $request->input();
        $data = (array)json_decode($post['data']);
        //$data = (array)($post['data']);
        Log::debug(print_r($data, true));
        $number = substr($data['from'], -10);
        $reply = '';
        $session_data = [];
        $sessions = [];
        $finalised = false;
        $botSess = Rapiwha::where('from', $data['from'])->where('created_at', '>=', date("Y-m-d H:i:s", strtotime("now")-88200 ) )->orderby('created_at', 'desc')->first();
        
        if(strpos($data['text'],'CREST_VERIFY_') === 0) {
            list($code, $uid) = explode('_', str_replace('CREST_VERIFY_', '', $data['text']) );
            $response = LambdaRequest::postrequest('contact', 'contact/update', ['id' => $uid, 'position'=>'india', 'is_verified' => true ], env('LAMBDA_ACCESS_TOKEN', 'default_value') );
            $session = (object)Session::where('code', $code)->first()->toArray();
            $reply = 'Greetings ' . $response->data->item->name ."\n";
            $reply .= 'You have Successfully registered for Crest session "'.$session->number.' ('.$session->type.') "'."\n";
            $reply .= 'Please find the details below'."\n";
            $reply .= 'Venue: ' . $session->venue . "\n";
            $reply .= 'Address: ' . $session->address . "\n";
            $reply .= 'Timings:' . "\n";
            $dates = json_decode($session->dates);
            foreach($dates->date as $i => $date){
                $reply .= date("d M, Y", strtotime($date) ) . ' at ' . date("h:iA", strtotime($dates->start[$i]) ) .' - ' . date("h:iA", strtotime($dates->end[$i]) ) . "\n";
            }
            $reply .= "\n" . 'You can use this chat as your self assistance for getting details, download your certificate etc.';
            Session::where('code', $code)->increment('reg_confirmed');
            Log::debug($reply);
            Log::debug($code);
            if($code == 'Y8WUVES7VIdRNB4gOEe7') {
                return response()->json(['autoreply' => $reply]);
            } else {
                return response()->json([]);
            }
        }

        if($botSess && !$finalised) {
            $session_data = (array)json_decode($botSess->session_data);
            if(isset($session_data['session'])) {
                $sess = $session_data['session_data'];
                $reply = 'We can see that you have registered for '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n";
                //$finalised = true;
            }
        }

        if(!$botSess && !$finalised) {
            $response = LambdaRequest::getrequest('contact', 'contact/get_all', ['source'=>'dynamodb', 'search' => json_encode(['phone' => $number]), 'fields' => json_encode(['session_code', 'present']) ], env('LAMBDA_ACCESS_TOKEN', 'default_value') );
            $users = [];
            if( sizeof($response->data->items) > 0 ) {
                foreach($response->data->items as $item) {
                    if( isset($item->session_code) ) {
                        $sessions[] = $item->session_code;
                        $users[$item->session_code] = $item->id;
                    }
                }
                //Log::debug(print_r($sessions, true));
                $sessions = DB::table('sessions')->wherein('code', $sessions)->orderby('created_at', 'desc')->get();
                //$sessions = DB::table('sessions')->wherein('code', $sessions)->where('start_date', '>=', date("Y-m-d 00:00:00", strtotime("now") ) )->orderby('created_at', 'desc')->get();
                //Log::debug(print_r($sessions, true));
                if($sessions->count() > 1) {
                    $reply = 'We can see that you have registered for multiple future Crest events. Please reply for which crest session you want to communicate'."\n\n";
                    $session_data['available_sessions'] = $sessions->toArray();
                    $session_data['available_users'] = $users;
                    $count = 1;
                    foreach($sessions->toArray() as $sess) {
                        $session_data['session_selection'] = [(string)$count => $sess->code ];
                        $reply .= 'Reply '.$count.' if you want to select '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n";
                        $count++;
                    }
                    $finalised = true;
                } else {
                    $sess = $sessions->toArray();
                    $sess = $sess[0];
                    $session_data['session'] = $sess->code;
                    $session_data['session_data'] = $sess;
                    $session_data['user'] = $users[$sess->code];
                    $reply = 'We can see that you have registered for '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n";
                }
            } else {
                $reply = 'Thank you for your interest in Crest. we can see that you have not registered for amy future Crest event.';
                $finalised = true;
            }
        } 

        //echo '
'; print_r($session_data); exit;

        if(!isset($session_data['session']) && !$finalised ) {
            $count = 1;
            foreach($session_data['available_sessions'] as $sess) {
                if($count == $data['text']) {
                    $session_data['session'] = $sess->code;
                    $session_data['session_data'] = $sess;
                    $session_data['user'] = $session_data['available_users']->{$sess->code};
                    $reply = 'You have selected '.ucwords($sess->type).' ('.$sess->number.') on '.date("d M Y", strtotime($sess->start_date)). ' at ' . $sess->venue."\n\n";
                    $data['text'] = 'hi';
                    //$finalised = true;
                }
                $count++;
            }
        }

        if(isset($session_data['session']) && !$finalised) {
            switch(Str::slug($data['text'], '_')) {
                case '1':
                    $reply = 'Here is the link to the session website: ' . $domain . 'microsite/' . $session_data['session_data']->type . '-' . $session_data['session_data']->code;
                    break;
                case '2':
                    $reply = 'Please find the details below'."\n\n";
                    $reply .= 'Venue: ' . $session_data['session_data']->venue . "\n\n";
                    $reply .= 'Address: ' . $session_data['session_data']->address . "\n\n" . "\n\n";
                    $reply .= 'Timings:' . "\n\n";
                    $dates = json_decode($session_data['session_data']->dates);
                    foreach($dates->date as $i => $date){
                        $reply .= date("d M, Y", strtotime($date) ) . ' at ' . date("h:iA", strtotime($dates->start[$i]) ) .' - ' . date("h:iA", strtotime($dates->end[$i]) ) . "\n\n";
                    }
                    break;
                case '3':
                    $reply = 'Here is the link to the session website: ' . $domain . 'brochure/' . $session_data['session_data']->code;
                    break;
                case '4':
                    $response = LambdaRequest::getrequest('contact', 'contact/get_one', ['id'=>$session_data['user']], env('LAMBDA_ACCESS_TOKEN', 'default_value') );
                    $doctor = $response->data->item;
                    $output = Creation::certificate($session_data['session_data'], $doctor);
                    $filename = $output['filename'];
                    DB::table('raphiwa_send')->insert(['to'=> $data['from'], 'text' => $domain . 'storage/certificate/'.$session_data['session_data']->code.'/'.$session_data['session_data']->type.'/'.$filename ]);
                    $reply = 'We will generate your certificate and send it to you in a while, please give us few minutes.';
                    break;

                default:
                    $reply .= 'Please select what do you want to do'."\n\n";
                    $reply .= 'Reply 1 if you want link to the session website'."\n\n";
                    $reply .= 'Reply 2 if you want to know about session location and timings'."\n\n";
                    //$reply .= 'Reply 3 if you want to know about session agenda and speakers'."\n\n";
                    $reply .= 'Reply 3 if you want to download session brochure'."\n\n";
                    $reply .= 'Reply 4 if you want to download your certificate'."\n\n";
                    break;
            }
        }

        $data['session_data'] = json_encode($session_data);
        //echo $reply; echo '
'; print_r($data); exit;
        if($botSess) {
            unset($data['event']);
            $data['msg_history'] = json_decode($botSess->msg_history);
            $data['msg_history'][] = $data['text'];
            $data['msg_history'] = json_encode($data['msg_history']);
            Rapiwha::where('id', $botSess->id)->update($data);
        } else {
            $data['msg_history'] = json_encode([$data['text']]);
            Rapiwha::create($data);
        }
        
        return response()->json(['autoreply' => $reply]);

        // if(Str::slug($data['text'], '_') == 'hi_pulmoflix') {
        //     return response()->json(['autoreply' => 'Thank you for showing interest in Pulmoflix. To access the website use the link https://pulmoflix.com']);
        // } elseif(Str::slug($data['text'], '_') == 'hi_napcon') {
        //     return response()->json(['autoreply' => 'Dear Doctor, Please click on the link and download the NAPCON 2022 Application, for a better NAPCON Experience'."\n\n".'Android:'."\n".'https://play.google.com/store/apps/details?id=com.startawiz.napcon'."\n\n".'iOS:'."\n".'https://apps.apple.com/in/app/napcon/id1615285887']);
        // } else {
        //     return response()->json([]);
        // }
        
    }
}