<?php

namespace App\Models\Users;

use App\Models\WhatsappBotApi;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\WhatsappTeamboxApi;

class BotExternalAction extends Model
{
    protected $table = 'botmsgs_externalaction';
    use HasFactory;

    public static function externalProcess($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo)
    {
        $externalActions =  BotExternalAction::where('bot_msgs_id', $msg_data->id)->where('status', 1)->get();

        foreach ($externalActions as $externalAction) {

            //return $externalAction->type;
            switch ($externalAction->type) {
                case 2:
                    if (is_numeric($text_message)) {
                        $numlength = strlen((string)$text_message);
                        if ($numlength == 10) {
                            $random = mt_rand(1111, 9999);
                            $curl = curl_init();
                            curl_setopt_array($curl, array(
                                CURLOPT_URL => 'https://api.authkey.io/request?authkey=43cdf8bcd6e9f647&mobile=' . $text_message . '&country_code=91&sid=7620&otp=' . $random . '',
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => '',
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 0,
                                CURLOPT_FOLLOWLOCATION => true,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => 'GET',

                                CURLOPT_HTTPHEADER => array(
                                    'Content-Type: application/json',
                                    'Authorization: Bearer EAAQmhO2aDmMBAOVKZBZCjYzJ0rflTiRGF22QayivVTZAYjyV2FKTZCn0Kgk3qHETOfWoceb6yuAgmZCO1ZAYNngIKPOfegV6r44tlHRLSZByypyW3bwYR547qV5XKsmdF6hgRssvK41WkaYsqn42plIT0YxqiUNueVi4j2MhZC1GyG3rmDV8kLqCGMkui4O6Ef1fXnwIfmpCLgZDZD'
                                ),
                            ));

                            $response = curl_exec($curl);

                            curl_close($curl);
                            BotmsgFormula::saveFormulaValue($random, $BotInfo->id,  $visitor_id, 16);
                        } else {
                            DB::table('bot_visitors_history')
                                ->where('visitor_id', $visitor_id)
                                ->where('msg_id', 41)
                                ->update(['status' => 0]);
                            // if validation fail send the message for correct mobile number
                            $curl = curl_init();
                            $obj_whatsbot = new WhatsappBotApi($bot_number);
                            $URL = $obj_whatsbot->api_url . $obj_whatsbot->phone_number_id . '/messages';
                            curl_setopt_array($curl, array(
                                CURLOPT_URL => $URL,
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => '',
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 0,
                                CURLOPT_FOLLOWLOCATION => true,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => 'POST',
                                CURLOPT_POSTFIELDS => '{
                                    "messaging_product": "whatsapp",
                                    "recipient_type": "individual",
                                    "to": ' . $vistor_phone_no . ',
                                    "type": "text",
                                    "text": {
                                    "preview_url" : false,
                                    "body" : "Please put correct Phone Number without dashes and country code!",
                                    }
                                }',
                                CURLOPT_HTTPHEADER => array(
                                    "Content-Type: application/json",
                                    "Authorization: Bearer $obj_whatsbot->token"
                                ),
                            ));
                            $response = curl_exec($curl);
                            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                            curl_close($curl);

                            //Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo);
                        }
                    } else {
                        DB::table('bot_visitors_history')
                            ->where('visitor_id', $visitor_id)
                            ->where('msg_id', 41)
                            ->update(['status' => 0]);
                        // if validation fail send the message for correct mobile number
                        $curl = curl_init();
                        $obj_whatsbot = new WhatsappBotApi($bot_number);
                        $URL = $obj_whatsbot->api_url . $obj_whatsbot->phone_number_id . '/messages';
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => $URL,
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'POST',
                            CURLOPT_POSTFIELDS => '{
                            "messaging_product": "whatsapp",
                            "recipient_type": "individual",
                            "to": ' . $vistor_phone_no . ',
                            "type": "text",
                            "text": {
                            "preview_url" : false,
                            "body" : "Please put correct Phone Number without dashes and country code!",
                            }
                        }',
                            CURLOPT_HTTPHEADER => array(
                                "Content-Type: application/json",
                                "Authorization: Bearer $obj_whatsbot->token"
                            ),
                        ));
                        $response = curl_exec($curl);
                        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                        curl_close($curl);
                    }

                    break;


                case "3":




                    break;
                default:
                    echo "Your favorite color is neither red, blue, nor green!";
            }
        }
    }

    public static function checkactionBefore($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo)
    {

        $query = DB::table('botmsgs_externalaction_before')->where('fk_msg_id', '=', $msg_data->id)->where('status', '=', 1)->get();
        // print_r("hrere" . $msg_data->id);
        // exit();
        if ($query[0]->is_api) {

            if ($msg_data->id == 41) {
                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'delete', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                if ($response->status != 'success' && $msg_data->id == 41) {

                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                    $message = $response->message;
                    //BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message, 1);
                    $button_options = Botmessageoption::where('msgs_id', $msg_data->id)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else {
                    $message = "Cancellation of $text_message is successful";

                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
                // ----------------- update order id ------------------------------ //
            } else if ($msg_data->id == 45) {

                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success' && $msg_data->id == 44) {

                    $message = $response->message;
                    BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message, 1);
                } else if ($response->status == 'success' && $msg_data->id == 44) {
                    // donothing
                }
            } else if ($msg_data->id == 44) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 45)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "orderId" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);

                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            }
            // ----------------- end of update order id ------------------------------ //
            //-------------------------- Update Order --------------------- //
            else if ($msg_data->id == 47) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 41)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    // if success then do nothing look for next sequence
                }
            } else if ($msg_data->id == 73) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 47)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "addressName" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);

                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            }
            //-------------------------- end of Update Order --------------------- //
            //-------------------------- Update No in address  --------------------- //
            else if ($msg_data->id == 88) {

                if (!is_numeric($text_message)) {
                    $message = 'Only Numbers allowed';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }
                $numlength = strlen((string)$text_message);
                if ($numlength != 4 || $numlength != 10) {
                    $message = 'No is either 4 digit or 10 digit long';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }

                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 89)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    // if success then do nothing look for next sequence
                }
            } else if ($msg_data->id == 89) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 88)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "delBToPhone" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => 'wa.api', 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);

                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
                // ApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
            }

            //-------------------------- end of No in address --------------------- //
            //-------------------------- Update Tracking id ----------- //
            else if ($msg_data->id == 91) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 92)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    // if success then do nothing look for next sequence
                }
            } else if ($msg_data->id == 92) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 91)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "trackingId" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => 'wa.api', 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);
                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            }

            //--------------------------Update Tracking id------------ //

            //-------------------------- end of Update Order --------------------- //
            //-------------------------- (Update otp) ----------- //
            else if ($msg_data->id == 94) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    // if success then do nothing look for next sequence
                }
            } else if ($msg_data->id == 95) {

                if (!is_numeric($text_message)) {
                    $message = 'Only Numbers allowed';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }
                $numlength = strlen((string)$text_message);
                if ($numlength > 8) {
                    $message = 'Maximum Length Should be 8';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }
                $previousResponse = BotApiResponse::where('bot_msg_id', 94)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "OTP" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);
                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            }

            //--------------------------(Update otp)------------ //

            //-------------------------- (Connect delivery agent) ----------- //
            else if ($msg_data->id == 97) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    // if success then do nothing look for next sequence
                }
            } else if ($msg_data->id == 99) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 97)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "delBPhone" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);
                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            } else if ($msg_data->id == 101) {
                $previousResponse = BotApiResponse::where('bot_msg_id', 97)->where('api_status', 'success')->latest()->first();
                $previousResponse = json_decode($previousResponse->api_response);
                $values = [
                    "delBOTP" => $text_message,
                    "status" => $previousResponse->result->status
                ];
                $encodedValues = base64_encode(json_encode($values));
                $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $previousResponse->result->id, 'values' => $encodedValues);
                $response = BotExternalAction::idzoAPI($arrr);
                if ($response->status == 'success') {
                    $message = "Update Successful!";
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                } else {
                    $message = $response->message;
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
                }
            }
            // --------------------------(/end connect delivery agent) -------------------- //  
            //-------------------------- (View order details) ----------- //
            else if ($msg_data->id == 103) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    $productName = $response->result->name;
                    $orderId = $response->result->orderId;
                    $trackingId = $response->result->trackingId;
                    $courier = $response->result->courier;
                    $idzoId = $response->result->id;
                    $addressName = $response->result->addressName;
                    $status = $response->result->status;
                    $OTP = $response->result->OTP;
                    $phone = $response->result->delBToPhone;
                    $message = '';
                    $message = $message . "Product :" . $productName . '\n';
                    $message = $message . "Order Id :" . $orderId . '\n';
                    $message = $message . "Tracking Id :" . $trackingId . '\n';
                    $message = $message . "Courier name :" . $courier . '\n';
                    $message = $message . "IDZO Id :" . $idzoId . '\n';
                    $message = $message . "Address name :" . $addressName . '\n';
                    $message = $message . "Order status :" . $status . '\n';
                    $message = $message . "Otp :" . $OTP . '\n';
                    $message = $message . "Last 4 digits :" .  substr($phone, -4) . '\n';

                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                    // if success then do nothing look for next sequence
                }
                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
            }
            //--------------------------(// end View order details)------------ //
            //-------------------------- (start of ASK of OTP) ----------- //
            else if ($msg_data->id == 112) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                if ($response->status == 'success') {

                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                }

                //BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {
                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    if ($response->result->OTP == null || $response->result->OTP == "" || $response->result->OTP == "NULL") {
                        //send a template message if it's a  NULL In order detail api response



                        $row[0]['text'] = $response->result->name;
                        $row[1]['text'] = $response->result->orderId;
                        $row[2]['text'] = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                        $row[3]['text'] = $response->result->id;
                        $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                        $row[5]['text'] = substr($response->result->delBToPhone, -4);
                        $request = array();
                        $request = (object) array('Account_Id' => '12', 'components' => 6, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                        $response2 =  BotExternalAction::sendTemplate($request);



                        // $row[0]['text'] = $response->result->name;
                        // $row[1]['text'] = $response->result->orderId;
                        // $row[2]['text'] = $response->result->trackingId;
                        // $row[3]['text'] = $response->result->id;
                        // $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                        // $request = array();
                        // $request = (object) array('Account_Id' => '12', 'components' => 5, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                        // $response2 =  BotExternalAction::sendTemplate($request);
                        print_r($response2);
                    } else {


                        $productName = $response->result->name;
                        $orderId = $response->result->orderId;
                        $trackingId = $response->result->trackingId;
                        $courier = $response->result->courier;
                        $idzoId = $response->result->id;
                        $addressName = $response->result->addressName;
                        $status = $response->result->status;
                        $OTP = $response->result->OTP;
                        $phone = $response->result->delBToPhone;
                        $message = "OTP has alredy been updated by card holder. ";
                        $message = $message . "Product :" . $productName . '\n';
                        $message = $message . "Order Id :" . $orderId . '\n';
                        $message = $message . "Tracking Id :" . $trackingId . '\n';
                        $message = $message . "Courier name :" . $courier . '\n';
                        $message = $message . "IDZO Id :" . $idzoId . '\n';
                        $message = $message . "Address name :" . $addressName . '\n';
                        $message = $message . "Order status :" . $status . '\n';
                        $message = $message . "Otp :" . $OTP . '\n';
                        $message = $message . "Last 4 digits :" .  substr($phone, -4) . '\n';
                        BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message, 1);
                    }
                }
            } else if ($msg_data->id == 114) {


                if (!is_numeric($text_message)) {
                    $message = 'Only Numbers allowed';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }

                $botformulatValue = BotmsgFormulaValue::where('fk_visitor_id', $visitor_id)->where('fk_botmsg_formula', '24')->where('status', 1)->get()->first();

                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $botformulatValue->value);


                $response = BotExternalAction::idzoAPI($arr);
                if ($response->status == 'success') {
                    $values = [
                        "OTP" => $text_message,
                        "status" => $response->result->status
                    ];
                    $encodedValues = base64_encode(json_encode($values));
                    $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $response->result->id, 'values' => $encodedValues);
                    $response = BotExternalAction::idzoAPI($arrr);

                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                }
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {

                    // if success then do nothing look for next sequence
                    $message = "Thank you for updating OTP";
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 0);
                    $botformulatValue2 = BotmsgFormulaValue::where('fk_visitor_id', $visitor_id)->where('fk_botmsg_formula', '25')->where('status', 1)->get()->first();
                    //$message = "OTP has been updated by card holder. ";
                    $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $botformulatValue->value);
                    $response = BotExternalAction::idzoAPI($arr);

                    if ($response->status == 'success') {
                        $productName = $response->result->name;
                        $orderId = $response->result->orderId;
                        $trackingId = $response->result->trackingId;
                        $courier = $response->result->courier;
                        $idzoId = $response->result->id;
                        $addressName = $response->result->addressName;
                        //   $status = $response->result->status;
                        $OTP = $response->result->OTP;
                        $phone = $response->result->phone;


                        $row[0]['text'] = $response->result->OTP == NULL ? 0 : $response->result->OTP;
                        $row[1]['text'] = $productName;
                        $row[2]['text'] = $orderId;
                        $row[3]['text'] = $trackingId == NULL ? 0 : $trackingId;
                        $row[4]['text'] = $courier == NULL ? 0 : $courier;
                        $row[5]['text'] = $idzoId == NULL ? 0 : $idzoId;
                        $row[6]['text'] = $addressName == NULL ? 'NULL' : $addressName;
                        $row[7]['text'] = $response->result->status == NULL ? 'NULL' : $response->result->status;

                        $row[8]['text'] = substr($response->result->delBToPhone, -4);



                        $request = array();
                        $request = (object) array('Account_Id' => '12', 'components' => 9, 'row' => $row, 'to_number' => $response->result->buyerPhone, 'template_name' => 'chatbot_otp_request_buyer', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                        $res =  BotExternalAction::sendSimpleTemplate($request);
                        print_r($res);
                        //exit();
                        //$button_options = Botmessageoption::where('msgs_id', 107)->get();
                        // BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message, 1);
                        //BotExternalAction::sendcautionMessage($botformulatValue2->value, $bot_number, $message, 1);
                        // if success then do nothing look for next sequence
                    }
                    // BotExternalAction::sendcautionMessage($botformulatValue2->value, $bot_number, $message, 1);
                }
            }

            //--------------------------(end of Ask for OTP)------------ //
            //-------------------------- (Buyer Ask for newly sent OTP) ----------- //
            else if ($msg_data->id == 108) {
            } else if ($msg_data->id == 109) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {
                    //print_r('here');
                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {

                    if ($response->result->OTP == null || $response->result->OTP == "NULL" || $response->result->OTP == "") {

                        $row[0]['text'] = $response->result->name == NULL ? 0 : $response->result->name;
                        $row[1]['text'] =  $response->result->orderId == NULL ? 0 : $response->result->orderId;
                        $row[2]['text'] = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                        $row[3]['text'] =  $response->result->id == NULL ? 0 : $response->result->id;
                        $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                        $row[5]['text'] = substr($response->result->delBToPhone, -4);
                        $request = array();
                        $request = (object) array('Account_Id' => '12', 'components' => 6, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $vistor_phone_no);
                        $response =  BotExternalAction::sendTemplate($request);
                    } else {
                        // send a template message
                        $row[0]['text'] = $response->result->name;
                        $row[1]['text'] = $response->result->orderId;
                        $row[2]['text'] = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                        $row[3]['text'] = $response->result->id;
                        $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                        $row[5]['text'] = $response->result->OTP;
                        $row[6]['text'] = substr($response->result->delBToPhone, -4);
                        $request = array();
                        $request = (object) array('Account_Id' => '12', 'components' => 7, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_new_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                        $response =  BotExternalAction::sendTemplate($request);
                        print_r($response);
                    }
                }
            } else if ($msg_data->id == 111) {

                if (!is_numeric($text_message)) {
                    $message = 'Only Numbers allowed';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }
                $botformulatValue = BotmsgFormulaValue::where('fk_visitor_id', $visitor_id)->where('fk_botmsg_formula', '26')->where('status', 1)->get()->first();

                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $botformulatValue->value);
                $response = BotExternalAction::idzoAPI($arr);


                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {

                    //BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message, 0);
                    $botformulatValue2 = BotmsgFormulaValue::where('fk_visitor_id', $visitor_id)->where('fk_botmsg_formula', '27')->where('status', 1)->get()->first();
                    $message = "OrderID '.$botformulatValue->value.' OTP has been updated by card holder. ";
                    $values = [
                        "OTP" => $text_message,
                        "status" => $response->result->status
                    ];
                    $encodedValues = base64_encode(json_encode($values));
                    $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => $response->result->id, 'values' => $encodedValues);
                    $response2 = BotExternalAction::idzoAPI($arrr);
                    $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $botformulatValue->value);
                    $response = BotExternalAction::idzoAPI($arr);
                    BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));

                    $message = "New OTP has been updated ";
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 0);
                    if ($response->status == 'success') {
                        $productName = $response->result->name;
                        $orderId = $response->result->orderId;
                        $trackingId = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                        $courier = $response->result->courier;
                        $idzoId = $response->result->id;
                        $addressName = $response->result->addressName;
                        //    $status = $response->result->status;
                        $OTP = $response->result->OTP;
                        $phone = $response->result->delBToPhone;


                        $row[0]['text'] = $response->result->OTP == NULL ? 0 : $response->result->OTP;
                        $row[1]['text'] = $productName;
                        $row[2]['text'] = $orderId;
                        $row[3]['text'] = $trackingId == NULL ? 0 : $trackingId;
                        $row[4]['text'] = $courier == NULL ? 0 : $courier;
                        $row[5]['text'] = $idzoId == NULL ? 0 : $idzoId;
                        $row[6]['text'] = $addressName == NULL ? 0 : $addressName;
                        $row[7]['text'] = $response->result->status == NULL ? 0 : $response->result->status;
                        // $row[8]['text'] = $response->result->OTP == NULL ? 0 : $response->result->OTP;
                        $row[8]['text'] = substr($response->result->delBToPhone, -4);



                        $request = array();
                        $request = (object) array('Account_Id' => '12', 'components' => 9, 'row' => $row, 'to_number' => $response->result->buyerPhone, 'template_name' => 'chatbot_new_otp_request_buyer', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                        $response =  BotExternalAction::sendSimpleTemplate($request);
                        print_r($response);
                    }
                    // BotExternalAction::sendcautionMessage($botformulatValue2->value, $bot_number, $message, 1);
                }
            }
            //--------------------------(end of Buyer Ask for newly sent OTP)------------ //

            //-------------------------- (start of ASK of OTP with new direct message style) ----------- //
            else if ($msg_data->id == 115) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                if ($response->status == 'success') {
                    $row[0]['text'] = $response->result->name;
                    $row[1]['text'] = $response->result->orderId;
                    $row[2]['text'] = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                    $row[3]['text'] = $response->result->id;
                    $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                    $row[5]['text'] = substr($response->result->delBToPhone, -4);
                    $request = array();
                    $request = (object) array('Account_Id' => '12', 'components' => 6, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                    $response2 =  BotExternalAction::sendTemplate($request);
                }
            }
            //-------------------------- (start of ASK of new OTP with new direct message style) ----------- //
            else if ($msg_data->id == 116) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                if ($response->status == 'success') {
                    $row[0]['text'] = $response->result->name;
                    $row[1]['text'] = $response->result->orderId;
                    $row[2]['text'] = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;;
                    $row[3]['text'] = $response->result->id;
                    $row[4]['text'] = $response->result->addressName == NULL ? 0 : $response->result->addressName;
                    $row[5]['text'] = $response->result->OTP;
                    $row[6]['text'] = substr($response->result->delBToPhone, -4);
                    $request = array();
                    $request = (object) array('Account_Id' => '12', 'components' => 7, 'row' => $row, 'to_number' => $response->result->phone, 'template_name' => 'chatbot_new_otp_request', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' => $response->result->buyerPhone);
                    $response =  BotExternalAction::sendTemplate($request);
                    print_r($response);
                }
            }
            //-------------------------- (View order details for admin) ----------- //
            else if ($msg_data->id == 107) {


                $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
                $response = BotExternalAction::idzoAPI($arr);

                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
                if ($response->status != 'success') {

                    $message = $response->message;
                    $button_options = Botmessageoption::where('msgs_id', 107)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                } else if ($response->status == 'success') {
                    $productName = $response->result->name;
                    $orderId = $response->result->orderId;
                    $trackingId = $response->result->trackingId;
                    $courier = $response->result->courier;
                    $idzoId = $response->result->id;
                    $addressName = $response->result->addressName;
                    $status = $response->result->status;
                    $OTP = $response->result->OTP;
                    $phone = $response->result->delBToPhone;
                    $message = '';
                    $message = $message . "Product :" . $productName . '\n';
                    $message = $message . "Order Id :" . $orderId . '\n';
                    $message = $message . "Tracking Id :" . $trackingId . '\n';
                    $message = $message . "Courier name :" . $courier . '\n';
                    $message = $message . "IDZO Id :" . $idzoId . '\n';
                    $message = $message . "Address name :" . $addressName . '\n';
                    $message = $message . "Order status :" . $status . '\n';
                    $message = $message . "Otp :" . $OTP . '\n';
                    $message = $message . "Last 4 digits :" .  substr($phone, -4) . '\n';

                    $button_options = Botmessageoption::where('msgs_id', 107)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                    // if success then do nothing look for next sequence
                }
                BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $message, json_encode($response));
            }
            //--------------------------(// end View order details for admin)------------ //
        }
        if ($query[0]->is_api) {
            if ($msg_data->id == 95) {
            }
            if ($msg_data->id == 101 || $msg_data->id == 99) {
                if (!is_numeric($text_message)) {
                    $message = 'Only Numbers allowed';
                    $button_options = Botmessageoption::where('msgs_id', 95)->get();
                    BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
                }
            }
        }




        return 1;
    }

    //  Caution message alwasy exit the process
    public static function sendcautionMessage($vistor_phone_no, $bot_number, $message, $is_exit = Null)
    {
        $curl = curl_init();
        $obj_whatsbot = new WhatsappBotApi($bot_number);
        $URL = $obj_whatsbot->api_url . $obj_whatsbot->phone_number_id . '/messages';
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
                "messaging_product": "whatsapp",
                "recipient_type": "individual",
                "to": ' . $vistor_phone_no . ',
                "type": "text",
                "text": {
                "preview_url" : false,
                "body" : "' . $message . '",
                }
            }',
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "Authorization: Bearer $obj_whatsbot->token"
            ),
        ));
        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        echo $response;
        curl_close($curl);
        if ($is_exit) {
            exit();
        }
    }


    public static function sendcautionButtonMessage($visitor_phone, $bot_number,  $msg_data, $button_options = null, $is_exit)
    {
        $txt = Botmessageoption::formattingbuttonMessage($button_options);
        $curl = curl_init();
        $obj_whatsbot = new WhatsappBotApi($bot_number);
        $URL = $obj_whatsbot->api_url . $obj_whatsbot->phone_number_id . '/messages';
        //$URL = $this->api_url . $this->phone_number_id . '/messages';
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": ' . $visitor_phone . ',
        "type": "interactive",
        "interactive":{
            "type": "button",
             "body": {
                
              "text":"' . nl2br(($msg_data)) . '",
            },
          "action": {
          "buttons": [
            ' . $txt . '
            ] 
          }
        }
      }',
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "Authorization: Bearer $obj_whatsbot->token"
            ),
        ));

        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        echo $response;
        if ($is_exit) {
            exit();
        }
        return $httpcode;
    }

    public static function sendcustomcautionButtonMessage($title, $visitor_phone, $bot_number,  $msg_data, $button_options = null, $is_exit, $orderID, $buyerNo)
    {
        $txt = Botmessageoption::formattingbuttonMessage($button_options);
        $curl = curl_init();
        $obj_whatsbot = new WhatsappBotApi($bot_number);
        $URL = $obj_whatsbot->api_url . $obj_whatsbot->phone_number_id . '/messages';
        //$URL = $this->api_url . $this->phone_number_id . '/messages';
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": ' . $visitor_phone . ',
        "type": "interactive",
        "interactive":{
            "type": "button",
             "body": {
                
              "text":"' . nl2br(($msg_data)) . '",
            },
          "action": {
          "buttons": [
            {
                "type": "reply",
                "reply": {
                  "id": "' . $orderID . '--' . $buyerNo . '",
                  "title":"' . $title . '" 
                }
              }
            ] 
          }
        }
      }',
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "Authorization: Bearer $obj_whatsbot->token"
            ),
        ));

        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        echo $response;
        if ($is_exit) {
            exit();
        }
        return $httpcode;
    }

    public static function sendMedia($phoneNo, $mediaID, $accountID)
    {
        $accountData = AccountsModel::find($accountID);
        $api_url = $accountData->api_url;
        $phone_number_id = $accountData->phone_number_id;

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api_url . $phone_number_id . '/messages',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
              "messaging_product": "whatsapp",
              "recipient_type": "individual",
              "to": "' . $phoneNo . '",
              "type": "document",
              "document": {
              "id" : "' . $mediaID . '"
              }
          }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                "Authorization: Bearer $accountData->user_access_token"
            ),
        ));

        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($httpcode == 200) {
            curl_close($curl);
            // deleteting ID

            $url = 'https://graph.facebook.com/v13.0/' . $mediaID;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $headers = [];
            $headers[] = 'Content-Type:application/json';
            $token = $accountData->user_access_token;
            $headers[] = "Authorization: Bearer " . $token;
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $result = curl_exec($ch);
            $result = json_decode($result);
            curl_close($ch);
            print_r($result);
            return $response;
        }
    }

    public static function sendEmail($mail_to, $mail_subject, $mail_body)
    {
        $cURL_key = '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';
        $mail_from = 'makarand@kiranjadhav.com';

        $curl = curl_init();

        $mail_body = nl2br($mail_body);
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.sendgrid.com/v3/mail/send",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\"personalizations\": [{\"to\": [{\"email\": \"$mail_to\"}],\"cc\": [{\"email\":\"makarand@kiranjadhav.com\"}]}],\"from\": {\"email\": \"$mail_from\"},\"subject\": \"$mail_subject\",\"content\": [{\"type\": \"text/plain\", \"value\": \"$mail_body \"}]}",
            // CURLOPT_POSTFIELDS => "{\"personalizations\": [{\"email\": \"$mail_to\"}],\"cc\": [{\"email\":\"amol@voloteksoft.com\"}]}],\"from\": {\"email\": \"$mail_from\"},\"subject\": \"$mail_subject\",\"content\": [{\"type\": \"text/plain\", \"value\": \"$mail_body\"}]}",
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer $cURL_key",
                "cache-control: no-cache",
                "content-type: application/json"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
    }

    public static function idzoAPI($arr)
    {

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://idzo.in/app/?ver=3',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $arr,
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $response = (json_decode($response));

        return  $response;
    }

    public static function sendTemplate($request)
    {

        $account_id = $request->Account_Id;
        $components = $request->components;
        $row = $request->row;
        $to_number = $request->to_number;
        $template_name = $request->template_name;
        $lang = $request->lang;
        $accountData = AccountsModel::find($account_id);
        $api_url = $accountData->api_url;
        $token = $accountData->user_access_token;
        $phone_number_id = $accountData->phone_number_id;
        $orderID = $request->orderID;
        $buyerNo = $request->buyerNo;
        $waba_id = $accountData->waba_id;

        // if template is differetn then payload would chnage and we will capcher the payload 
        if ($template_name == 'askforotp') {
            $payload = $orderID . '--' . $buyerNo;
        } else {
            $payload = $orderID . '--' . $buyerNo;
        }

        $params = '';

        if ($components == 1) {

            $params = '{"type" : "text", "text" : "' . $row[0]['text'] . '"}';
        } else {

            $index = 0;
            for ($i = 0; $i < $components - 1; $i++) {
                $params =  $params . '{"type" : "text", "text" : "' . $row[$index++]['text'] . '"},';
            }

            // remove comman in last template
            $params =  $params . '{"type" : "text", "text": "' . $row[$i]['text'] . '"}';
        }

        $curl = curl_init();
        $URL = $api_url . $phone_number_id . '/messages';
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
          "messaging_product": "whatsapp",
          "recipient_type": "individual",
          "to": ' . $to_number . ',
          "type": "template",
          "template": {
            "name": "' .  $template_name . '",
            "language": {
              "code": "' .  $lang . '",
               "policy":"deterministic"
            },
            "components": [
                    
                        {
                            "type": "body",
                            "parameters": [
                                ' . $params . '
                        ]
                                    
                        
                    },
                    {
                        "type": "button",
                        "sub_type": "quick_reply",
                        "index": "0",
                        "parameters": [
                            {
                                "type": "payload",
                                "payload": "' .  $payload . '"
                            }
                        ]
                    },
                    {
                        "type": "button",
                        "sub_type": "quick_reply",
                        "index": "1",
                        "parameters": [
                              {
                                "type": "payload",
                                "payload": "PAYLOAD"
                              }
                        ]
                    }
                            
                    
                ]
            
            
          }
        }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                "Authorization: Bearer $token"
            ),
        ));


        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;
        return $response;
    }

    public static function sendSimpleTemplate($request)
    {

        $account_id = $request->Account_Id;
        $components = $request->components;
        $row = $request->row;
        $to_number = $request->to_number;
        $template_name = $request->template_name;
        $lang = $request->lang;
        $accountData = AccountsModel::find($account_id);
        $api_url = $accountData->api_url;
        $token = $accountData->user_access_token;
        $phone_number_id = $accountData->phone_number_id;
        $orderID = $request->orderID;
        $buyerNo = $request->buyerNo;
        $waba_id = $accountData->waba_id;
        $payload = $orderID . '--' . $buyerNo;
        $params = '';

        // if ($components == 1) {

        //     $params = '{"type" : "text", "text" : "' . $row[0]['text'] . '"}';
        // } else {

        //     $index = 0;
        //     for ($i = 0; $i < $components - 1; $i++) {
        //         $params =  $params . '{"type" : "text", "text" : "' . $row[$index++]['text'] . '"},';
        //     }

        //     // remove comman in last template
        //     $params =  $params . '{"type" : "text", "text": "' . $row[$i]['text'] . '"}';
        // }

        // $curl = curl_init();
        // $URL = $api_url . $phone_number_id . '/messages';
        // curl_setopt_array($curl, array(
        //     CURLOPT_URL => $URL,
        //     CURLOPT_RETURNTRANSFER => true,
        //     CURLOPT_ENCODING => '',
        //     CURLOPT_MAXREDIRS => 10,
        //     CURLOPT_TIMEOUT => 0,
        //     CURLOPT_FOLLOWLOCATION => true,
        //     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        //     CURLOPT_CUSTOMREQUEST => 'POST',
        //     CURLOPT_POSTFIELDS => '{
        //   "messaging_product": "whatsapp",
        //   "recipient_type": "individual",
        //   "to": ' . $to_number . ',
        //   "type": "template",
        //   "template": {
        //     "name": "' .  $template_name . '",
        //     "language": {
        //       "code": "' .  $lang . '",
        //        "policy":"deterministic"
        //     },
        //     "components": [

        //                 {
        //                     "type": "body",
        //                     "parameters": [
        //                         ' . $params . '
        //                 ]


        //             }


        //         ]


        //   }
        // }',
        //     CURLOPT_HTTPHEADER => array(
        //         'Content-Type: application/json',
        //         "Authorization: Bearer $token"
        //     ),
        // ));


        // $response = curl_exec($curl);

        // curl_close($curl);
        // echo $response;
        // return $response;



        if ($components == 0) {

            $options = '{
                "messaging_product": "whatsapp",
                "to": ' . $to_number . ',
                "type": "template",
                "template": {
                    "name": "' . $template_name . '",
                    "language": {
                        "code":"' . $lang . '" 
                    }
                }
            }';
        } else {
            $params = '';
            if ($components == 1) {

                $params = '{"type" : "text", "text" : "' . $row[0]['text'] . '"}';
            } else {
                $index = 0;
                for ($i = 0; $i < $components - 1; $i++) {
                    $params =  $params . '{"type" : "text", "text" : "' . $row[$index++]['text'] . '"},';
                }

                // remove comman in last template
                $params =  $params . '{"type" : "text", "text": "' . $row[$i]['text'] . '"}';
            }

            $options = '{
                "messaging_product": "whatsapp",
                "recipient_type": "individual",
                "to": "' . $to_number . '",
                "type": "template",
                "template": {
                    "name": "' . $template_name . '",
                    "language": {
                    "code": "' . $lang . '"
                    },
                    "components": [
                    {
                        "type": "body",
                        "parameters": [
                           ' . $params . '
                        ]
                    }
                    ]
                }
                }';
        }
        $URL = $api_url . $phone_number_id . '/messages';
        $response = WhatsappTeamboxApi::CURL($URL, $options, $token);
        return $response;
    }
}
