403Webshell
Server IP : 103.234.187.230  /  Your IP : 216.73.216.216
Web Server : Apache
System : Linux lserver42043-ind.megavelocity.net 3.10.0-1160.108.1.el7.x86_64 #1 SMP Thu Jan 25 16:17:31 UTC 2024 x86_64
User : apache ( 48)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/b2bzend/application/models/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/b2bzend/application/models/TblWhatsapp.php
<?php

/**
 * Class Package Master
 * Description 	This model contains the basic activity functions needed for packages.
 * @name	Package Master
 * @author	Prashant Kumar
 * @version 	1.0
 * @copyright 	Catabatic Automation Pvt. Ltd.
 * Handle 	Packate Related function
 *
 */
class Travel_Model_TblWhatsapp extends Zend_Db_Table_Abstract {

    private $db = NULL;

    /**
     * Class Constructors
     */
    public function __construct() {
        $this->db = Zend_Db_Table::getDefaultAdapter();
    }

    public function __destruct() {
        $this->db->closeConnection();
    }

    public function updateTable($table, $editData, $where) {
        $dbtable = new Zend_Db_Table("$table");
        $dbtable->update($editData, $where);
    }

    public function addAndUpdateTemplateData($SecurityKey, $agencySysId, $userSysId, $data = array()) {
        $return = array('status' => false, 'message' => 'Please Check Post Fields');
        if (!empty($data)) {
            $postData = $data['postData'];
            $TemplateName = $postData['name'];
            $language = $data['language'];
            $whatsappTextBody = $postData['whatsappTextBody'];
            $previewHtml = $data['previewHtml'];
            $category = $postData['category'];
            $whatsappTextHeader = $postData['whatsappTextHeader'];
            $whatsappTextFooter = $postData['whatsappTextFooter'];
            $type_of_button = $data['type_of_button'];
            $ButtonInfoArray = $data['ButtonInfoArray'];
            $VariableDataArray = $data['VariableDataArray'];
            $IsActive = $data['IsActive'];
            $IsDefault = (isset($data['IsDefault'])) ? (int) $data['IsDefault'] : 0;
            $TemplateSysID = isset($data['TemplateSysId']) ? $data['TemplateSysId'] : '';
            $savedata = [
                'AgencySysId' => $agencySysId,
                'AgentSysId' => $userSysId,
                'TemplateName' => $TemplateName,
                'WhatsAppMessage' => trim($whatsappTextBody),
                'TextMessage' => trim($previewHtml),
                'Language' => $language,
                'CreateDate' => date('Y-m-d'),
                'IsActive' => $IsActive,
                'IsMarkForDel' => 0,
                'TemplateType' => 1,
                'TemplateCategory' => $category,
                'TemplateHeader' => $whatsappTextHeader,
                'TemplateFooter' => $whatsappTextFooter,
                'ButtonType' => $type_of_button,
                'ButtonInfoJson' => (!empty($ButtonInfoArray)) ? json_encode($ButtonInfoArray) : '',
                'TemplateID' => '',
                'HeaderType' => (int) $postData['HeaderType'],
                'MediaType' => (int) $postData['MediaType'],
                'MediaFileName' => trim($postData['headerImageName']),
                'IsDefault' => $IsDefault,
                'IsBotTemplate' => isset($postData['IsBotTemplate']) ? (int) $postData['IsBotTemplate'] : 0,
            ];
            if ($TemplateSysID == '') {
                $TemplateSysID = $this->insertData('TB_Agency_WhatsAppEmail_Template', $savedata);
            } else {
                $where = array('AgencySysId = ? ' => $agencySysId, 'Id = ? ' => $TemplateSysID);
                $this->updateTable('TB_Agency_WhatsAppEmail_Template', $savedata, $where);
            }
            $objAgency = new Travel_Model_TblAgency();
            $objAgency->deleteTemplateVariable($TemplateSysID);
            foreach ($VariableDataArray as $key => $value) {
                $datath = array(
                    'HeaderType' => $value['type'],
                    'HeaderValue' => $value['value'],
                    'HeaderValueReference' => trim($value['reference']),
                    'MappingFromFB' => $value['key'],
                    'TemplateSysId' => $TemplateSysID,
                );
                $this->insertData('TB_Agency_Facebook_Template_Header', $datath);
            }
            $url = Catabatic_Helper::getSiteUrl() . 'gtxwebservices/whatsapp/create-whatsapp-template';
            $curl_p = curl_init($url);
            curl_setopt($curl_p, CURLOPT_POST, true);
            curl_setopt($curl_p, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($curl_p, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_p, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_p, CURLOPT_TIMEOUT, 300);
            curl_setopt(
                    $curl_p,
                    CURLOPT_HTTPHEADER,
                    array(
                        'SecurityKey:' . $SecurityKey
                    )
            );
            $response = curl_exec($curl_p);
            curl_close($curl_p);
            $responseArr = json_decode($response, 1);
//echo "<pre>";print_r($responseArr);exit;
            $TemplateID = (isset($responseArr['id']) && !empty($responseArr['id'])) ? trim($responseArr['id']) : '';
            $TemplateStatus = (isset($responseArr['status']) && !empty($responseArr['status'])) ? trim($responseArr['status']) : '';
            if (!empty($TemplateID)) {
                $return = array('status' => true);
                $updateData['TemplateID'] = $TemplateID;
                if (!empty($TemplateStatus)) {
                    $updateData['TemplateStatus'] = $TemplateStatus;
                }
                if (isset($TemplateSysID) && !empty($TemplateSysID)) {
                    $where = array('AgencySysId = ? ' => $agencySysId, 'Id = ? ' => $TemplateSysID);
                    $this->updateTable('TB_Agency_WhatsAppEmail_Template', $updateData, $where);
                    $return = array('status' => true, 'message' => '', 'Id' => $TemplateSysID, 'TemplateID' => $TemplateID, 'TemplateStatus' => $TemplateStatus);
                    return $return;
                }
            } else {
                if (isset($responseArr['error']) && !empty($responseArr['error'])) {
                    if (isset($responseArr['error']['error_user_msg']) && !empty($responseArr['error']['error_user_msg'])) {
                        $return = array('status' => false, 'message' => $responseArr['error']['error_user_msg']);
                    } else {
                        $return = array('status' => false, 'message' => $responseArr['error']['message']);
                    }
                } else {
                    $return = array('status' => false, 'message' => 'Error!!');
                }
            }
            return $return;
        }
        return $return;
    }

    public function getFlowFromdata($agencySysId, $FLowId) {
        $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Form"), array('FormId', 'IsApproved', 'IsJsonStatus', 'IsActive'))
                ->where("t1.AgencySysId =?", $agencySysId)
                ->where("t1.id =?", $FLowId)
//->where("t1.IsActive =?", 1)
                ->where("t1.IsMarkForDelete =?", 0);
        $result1 = $this->db->fetchRow($select1);
        return $result1;
    }

    public function getFixedDeparture($TPSysID) {
        $select1 = $this->db->select()->from(array("t1" => "TB_TravelPlan"), array('IsFixedDeparturePackage'))
                ->where("t1.TPSysId =?", $TPSysID);
        $result1 = $this->db->fetchRow($select1);
        return $result1;
    }

    public function getFixedDepartureDestination($TPSysID) {
        $select1 = $this->db->select()
                ->from(array("t1" => "Tb_TravelPlan_From_Destination_Fixed_Inventory"), array('DestinationSysId'))
                ->joinLeft(array('tb3' => "TB_Master_Geo_City"), "t1.DestinationSysId = tb3.CityId", array('Title'))
                ->where("t1.TPSysId =?", $TPSysID)
                ->where("t1.IsActive = 1")
                ->where("t1.IsMarkForDel =?", 0);
        $result1 = $this->db->fetchAll($select1);
        return $result1;
    }

    public function getPackageDate($TPSysID) {
        $select1 = $this->db->select()
                ->from(array("t1" => "TB_TravelPlan_Rate"), array("Convert(date,StartDate) AS StartDate"))
                ->where("t1.TPSysId =?", $TPSysID)
                ->where("t1.IsActive = 1")
                ->where("t1.IsMarkForDel =?", 0)
                ->where("t1.StartDate > ?", date("Y-m-d"))
                ->group("t1.StartDate");
        $result1 = $this->db->fetchAll($select1);
        return $result1;
    }

    public function setCustomerMessage($mobileno, $returnKeywordArray, $contact_name = '') {
        $TextMessage = isset($returnKeywordArray['TextMessage']['BodyText']) ? $returnKeywordArray['TextMessage']['BodyText'] : null;
        $WhatsAppmessage = str_replace('{CustomerName}', $contact_name, $TextMessage);
        $setWhatsAppTemplate = array(
            "messaging_product" => "whatsapp",
            "to" => $mobileno,
            "text" => array("body" => mb_convert_encoding($WhatsAppmessage, "UTF-8"))
        );
        return array("TextMessage" => $WhatsAppmessage, "Template" => $setWhatsAppTemplate);
    }

    public function getInteractiveId($SourceId, $FlowSysId, $TemplateId) {
        $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id'))
                ->where("t1.FlowSysId =?", $FlowSysId)
                ->where("t1.SourceId =?", $SourceId)
                ->where("t1.TemplateId =?", $TemplateId)
                ->where("t1.IsActive =?", 1)
                ->where("t1.IsMarkForDelete =?", 0);
        $result1 = $this->db->fetchRow($select1);
        if (isset($result1['id'])) {
            return isset($result1['id']) ? $result1['id'] : 'No';
        } else {
            $select2 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('TemplateId', 'TargetId'))
                    ->where("t1.id =?", $TemplateId)
                    ->where("t1.IsActive =?", 1)
                    ->where("t1.IsMarkForDelete =?", 0);
            $result2 = $this->db->fetchRow($select2);
            if (isset($result2['TargetId']) && isset($result2['TemplateId'])) {
                $select3 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id'))
                        ->where("t1.FlowSysId =?", $FlowSysId)
                        ->where("t1.TargetId =?", $result2['TargetId'])
                        ->where("t1.TemplateId =?", $result2['TemplateId'])
                        ->where("t1.IsActive =?", 1)
                        ->where("t1.IsMarkForDelete =?", 0)
                        ->order("t1.id DESC");
                $result3 = $this->db->fetchRow($select3);
                if (isset($result3['id'])) {
                    $select4 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id'))
                            ->where("t1.FlowSysId =?", $FlowSysId)
                            ->where("t1.SourceId =?", $SourceId)
                            ->where("t1.TemplateId =?", $result3['id'])
                            ->where("t1.IsActive =?", 1)
                            ->where("t1.IsMarkForDelete =?", 0);
                    $result4 = $this->db->fetchRow($select4);
                    return isset($result4['id']) ? $result4['id'] : 'No';
                } else {
                    return 'No';
                }
            } else {
                return 'No';
            }
        }
    }

    public function setInteractiveMessage($mobileno, $returnKeywordArray, $FlowSysId = null, $TemplateId = 'No', $PackageId = 'No', $contact_name = '', $serviceType = '') {
        $headerText = '';
        $buttonactionArray = $footerArray = $bodyArray = $headerArray = array();
        if ($returnKeywordArray['TextMessage']['HeaderType'] == 2) {
            $headerText = isset($returnKeywordArray['TextMessage']['HeaderText']) ? $returnKeywordArray['TextMessage']['HeaderText'] : '';
            $headerArray = array(
                "type" => "text",
                "text" => mb_convert_encoding($headerText, "UTF-8"),
            );
        } else if ($returnKeywordArray['TextMessage']['HeaderType'] == 3) {
            $agencySysId = $returnKeywordArray['TextMessage']['AgencySysId'];
            $MediaFileName = trim($returnKeywordArray['TextMessage']['MediaFileName']);
            $MediaType = trim($returnKeywordArray['TextMessage']['MediaType']);
            if ($MediaType == 3) {
                $type = "document";
                $headerArray = array(
                    "type" => $type,
                    $type => array(
                        "link" => "https://globaltravelexchange.com/public/upload/media/agency/$agencySysId/whatsapp/$MediaFileName"
                    ),
                );
            } else {
                $type = "image";
                $headerArray = array(
                    "type" => $type,
                    $type => array(
                        "link" => "https://globaltravelexchange.com/public/upload/media/agency/$agencySysId/whatsapp/$MediaFileName"
                    ),
                );
            }
        }
        $bodyText = isset($returnKeywordArray['TextMessage']['BodyText']) ? $returnKeywordArray['TextMessage']['BodyText'] : '';
        if ($bodyText != '') {
            $bodyArray = array(
                "text" => mb_convert_encoding(str_replace('{CustomerName}', $contact_name, $bodyText), "UTF-8"),
            );
        }
        $FooterText = isset($returnKeywordArray['TextMessage']['FooterText']) ? $returnKeywordArray['TextMessage']['FooterText'] : '';
        if ($FooterText != '') {
            $footerArray = array(
                "text" => mb_convert_encoding($FooterText, "UTF-8"),
            );
        }
        $buttonName1 = isset($returnKeywordArray['TextMessage']['ButtonName']) ? $returnKeywordArray['TextMessage']['ButtonName'] : '';
        $flowid = isset($returnKeywordArray['ActionType'][0]['ActionId']) ? $returnKeywordArray['ActionType'][0]['ActionId'] : '';
        $ButtonType = isset($returnKeywordArray['TextMessage']['ButtonType']) ? $returnKeywordArray['TextMessage']['ButtonType'] : 2;
        if ($ButtonType == 4) {
            $fromDestinationIdArray = $traveldate_fd = array();
            $IsFixedDeparture = '0';
            if ((int) $PackageId > 0) {
                if ($serviceType == 'Visa') {
                    $IsFixedDeparture = 6;
                } else {
                    $getFDArray = $this->getFixedDeparture($PackageId);
                    $IsFixedDeparture = isset($getFDArray['IsFixedDeparturePackage']) ? $getFDArray['IsFixedDeparturePackage'] : '0';
                    if ($IsFixedDeparture == 1) {
                        $getFixedDepartureDestinationArray = $this->getFixedDepartureDestination($PackageId);
                        if (!empty($getFixedDepartureDestinationArray)) {
                            $i = 0;
                            foreach ($getFixedDepartureDestinationArray as $destinationArray) {
                                $fromDestinationIdArray[$i]["id"] = (string) $destinationArray["DestinationSysId"];
                                $fromDestinationIdArray[$i]["title"] = trim($destinationArray["Title"]);
                                $i++;
                            }
                        }
                        $getPackageDateArray = $this->getPackageDate($PackageId);
                        if (!empty($getPackageDateArray)) {
                            $j = 0;
                            foreach ($getPackageDateArray as $getPackageDateval) {
                                $traveldate_fd[$j]["id"] = (string) trim($getPackageDateval["StartDate"]->format("Y-m-d"));
                                $traveldate_fd[$j]["title"] = trim($getPackageDateval["StartDate"]->format("d/m/Y"));
                                $j++;
                            }
                        }
                    }
                }
            }
            $actionArray = array(
                "name" => "flow",
                "parameters" => array(
                    "flow_message_version" => "3",
                    "flow_token" => $flowid,
                    "flow_id" => $flowid,
                    "flow_cta" => $returnKeywordArray['ActionType'][0]['ActionName'],
                    "flow_action" => "navigate",
                    "flow_action_payload" => array(
                        "screen" => $returnKeywordArray['ActionType'][0]['ActionDesc'],
                        "data" => array(
                            "PACKAGEID" => $PackageId,
                            "IsFixedDeparture" => (string) "$IsFixedDeparture",
                            "traveldate_fd" => $traveldate_fd,
                            "FromDestinationId_fd" => $fromDestinationIdArray
                        )
                    )
                )
            );
        } else if ($ButtonType == 2) {
            $buttonactionArray = array();
            $r = 0;
            foreach ($returnKeywordArray['ActionType'] as $actionval) {
                $SourceId = trim($actionval['id']);
                if ($FlowSysId) {
                    $NewtemplateId = $this->getInteractiveId($SourceId, $FlowSysId, $TemplateId);
                    if ($ButtonType == 3) {
                        $id = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId . '_' . trim($actionval['ActionId']));
                    } else {
                        $id = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId);
                    }
                } else {
                    $id = ($actionval['id']);
                }
                $buttonactionArray[$r]["type"] = "reply";
                $buttonactionArray[$r]["reply"] = array(
                    "id" => $id,
                    "title" => $actionval['ActionName']
                );
                $r++;
            }
            $actionArray = array("buttons" => $buttonactionArray);
        } else {
            $u = 0;
            foreach ($returnKeywordArray['ActionType'] as $actionval) {
                $SourceId = trim($actionval['id']);
                if ($FlowSysId) {
                    $NewtemplateId = $this->getInteractiveId($SourceId, $FlowSysId, $TemplateId);
                    if ($ButtonType == 3) {
                        $buttonactionArray[$u]['id'] = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId . '_' . trim($actionval['ActionId']) . '_Package');
                    } else if ($ButtonType == 6) {
                        $buttonactionArray[$u]['id'] = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId . '_' . trim($actionval['ActionId']) . '_Visa');
                    } else {
                        $buttonactionArray[$u]['id'] = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId);
                    }
                } else {
                    $buttonactionArray[$u]['id'] = ($actionval['id']);
                }
                $buttonactionArray[$u]['title'] = $actionval['ActionName'];
                if ($actionval['ActionDesc'] != '') {
                    $buttonactionArray[$u]['description'] = $actionval['ActionDesc'];
                }
                $u++;
            }
            $actionArray = array(
                "button" => $buttonName1,
                "sections" => [
                    array(
                        "title" => $buttonName1,
                        "rows" => $buttonactionArray
                    )
                ]
            );
        }
        if ($ButtonType == 2) {
            $ButtonType = 'button';
        } else if ($ButtonType == 4) {
            $ButtonType = 'flow';
        } else {
            $ButtonType = 'list';
        }
        $interactive = array(
            "type" => $ButtonType,
            "body" => $bodyArray,
            "action" => $actionArray
        );
        if (is_array($headerArray) && !empty($headerArray)) {
            $interactive["header"] = $headerArray;
        }
        if (is_array($headerArray) && !empty($footerArray)) {
            $interactive["footer"] = $footerArray;
        }
        $setWhatsAppTemplate = array(
            "messaging_product" => "whatsapp",
            "recipient_type" => "individual",
            "to" => $mobileno,
            "type" => "interactive",
            "interactive" => $interactive
        );
        $PreviewHtml = '';
        if ($headerText != '') {
            $PreviewHtml .= $headerText . '\n';
        }
        if ($bodyText != '') {
            $PreviewHtml .= $bodyText . '\n';
        }
        if ($FooterText != '') {
            $PreviewHtml .= $FooterText . '\n';
        }
//      //  echo json_encode($setWhatsAppTemplate);exit;
//        echo "<pre>";
//        print_r($setWhatsAppTemplate);
//        exit;
        return array("TextMessage" => $PreviewHtml, "Template" => $setWhatsAppTemplate);
    }

    public function saveVariableAccordingtoCustomer($MapVariable, $mobileId, $targetId, $TemplateType, $FlowSysId, $isLast = 0, $isFirst = 0) {
        if ($isFirst == 1) {
            $dataSet = array(
                'WAID' => $mobileId,
                'TargetID' => $targetId,
                'TemplateType' => $TemplateType,
                'FlowSysId' => $FlowSysId,
                'UpdateDate' => date("Y-m-d H:i:s")
            );
            $insertId = $this->insertData("Tb_Agency_Whatsapp_Save_Variable", $dataSet);
            $dataSetValiable = array(
                'SaveSysId' => $insertId,
                'VariableName' => $MapVariable,
                'AnsValue' => null,
                'UpdateDate' => date("Y-m-d H:i:s")
            );
            $this->insertData("Tb_Agency_Whatsapp_Save_Variable_All_Step", $dataSetValiable);
        } else {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Save_Variable"), array('id'))
                    ->where("t1.WAID =?", $mobileId)
                    ->order("t1.id DESC");
            $result1 = $this->db->fetchRow($select1);
            if (isset($result1['id'])) {
                $dataSetValiable = array(
                    'SaveSysId' => $result1['id'],
                    'VariableName' => $MapVariable,
                    'AnsValue' => null,
                    'UpdateDate' => date("Y-m-d H:i:s")
                );
                $this->insertData("Tb_Agency_Whatsapp_Save_Variable_All_Step", $dataSetValiable);
            }
        }
    }

    public function getAndUpdateTargetId($mobileId, $targetId, $TemplateType, $FlowSysId, $isLast = 0) {
        if ($TemplateType == 1) {
            return array(0 => "interactive");
        } else {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Step"), array('id'))
                    ->where("t1.WAID =?", $mobileId);
            $result1 = $this->db->fetchRow($select1);
            if (isset($result1['id'])) {
                $id = $result1['id'];
                $where = array('id =?' => $id);
                if ($isLast == 1) {
                    $dataSet = array(
                        'TargetID' => null,
                        'TemplateType' => null,
                        'FlowSysId' => null,
                        'UpdateDate' => date("Y-m-d H:i:s")
                    );
                } else {
                    $dataSet = array(
                        'TargetID' => $targetId,
                        'TemplateType' => $TemplateType,
                        'FlowSysId' => $FlowSysId,
                        'UpdateDate' => date("Y-m-d H:i:s")
                    );
                }
                $this->updateTable("Tb_Agency_Whatsapp_Flow_Step", $dataSet, $where);
            } else {
                if ($isLast == 0) {
                    $dataSet = array(
                        'WAID' => $mobileId,
                        'TargetID' => $targetId,
                        'TemplateType' => $TemplateType,
                        'FlowSysId' => $FlowSysId,
                        'UpdateDate' => date("Y-m-d H:i:s")
                    );
                    $this->insertData("Tb_Agency_Whatsapp_Flow_Step", $dataSet);
                }
            }
            return array(0 => "custome");
        }
    }

    public function getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId) {
        $returnArray['TextMessage'] = array();
        if ($TemplateType == 1) {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Interactive_Template"))
                    ->where("t1.AgencySysId =?", $agencySysId)
                    ->where("t1.InteractiveTemplateSysId =?", $TemplateId)
                    ->where("t1.IsActive =?", 1)
                    ->where("t1.IsStatic =?", 1)
                    ->where("t1.IsMarkForDelete =?", 0);
            $result1 = $this->db->fetchRow($select1);
            $result2 = array();
            if (isset($result1['InteractiveTemplateSysId'])) {
                $select2 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Interactive_List_Action"))
                        ->where("t1.AgencySysId =?", $agencySysId)
                        ->where("t1.InteractiveTemplateSysId =?", $TemplateId)
                        ->where("t1.IsActive =?", 1)
                        ->where("t1.InteractiveTemplateSysId = ?", $result1['InteractiveTemplateSysId'])
                        ->where("t1.IsMarkForDelete =?", 0);
                $result2 = $this->db->fetchAll($select2);
            }
            $returnArray['TextMessage'] = $result1;
            $returnArray['ActionType'] = $result2;
            $returnArray['TemplateType'] = $TemplateType;
        } else if ($TemplateType == 2) {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Interactive_Template"), array("BodyText", "MapVariable"))
                    ->where("t1.AgencySysId =?", $agencySysId)
                    ->where("t1.InteractiveTemplateSysId =?", $TemplateId)
                    ->where("t1.IsActive =?", 1)
                    ->where("t1.BodyText != ''")
                    ->where("t1.IsMarkForDelete =?", 0);
            $result1 = $this->db->fetchRow($select1);
            if (isset($result1['BodyText'])) {
                $returnArray['TextMessage'] = $result1;
                $returnArray['TemplateType'] = $TemplateType;
            }
        } else if ($TemplateType == 4) {
            
        } else if ($TemplateType == 3) {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array("id", "FlowSysId", "TemplateType", "TemplateId", "TargetId"))
                    ->where("t1.AgencySysId =?", $agencySysId)
                    ->where("t1.FlowSysId =?", $TemplateId)
                    ->where("t1.IsActive =?", 1)
                    ->where("t1.Seq =?", '1')
                    ->where("t1.IsMarkForDelete =?", 0);
            $result1 = $this->db->fetchRow($select1);
            $returnArray['TextMessage'] = $result1;
        }
        return $returnArray;
    }

    public function checkkeyword($agencySysId, $messageText) {
        $select = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Tags"), array("AgencySysId"))
                ->joinLeft(array('t2' => "Tb_Agency_Whatsapp_Keyword_Action"), "t1.TagsSysId = t2.TagsSysId AND t1.AgencySysId = t2.AgencySysId", array("TemplateType", "TemplateId"))
                ->where("t1.Title =?", $messageText)
                ->where("t1.AgencySysId =?", $agencySysId)
                ->where("t1.IsActive =?", 1)
                ->where("t1.IsMarkForDelete =?", 0)
                ->where("t2.IsActive =?", 1)
                ->where("t2.IsMarkForDelete =?", 0);
        $select->order("KeyActionSysId DESC");
        $result = $this->db->fetchAll($select);
        if (empty($result)) {
            $select = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Tags"), array("AgencySysId"))
                    ->joinLeft(array('t2' => "Tb_Agency_Whatsapp_Keyword_Action"), "t1.TagsSysId = t2.TagsSysId AND t1.AgencySysId = t2.AgencySysId", array("TemplateType", "TemplateId"))
                    ->where("t1.Title =?", '##default')
                    ->where("t1.AgencySysId =?", $agencySysId)
                    ->where("t1.IsActive =?", 1)
                    ->where("t1.IsMarkForDelete =?", 0)
                    ->where("t2.IsActive =?", 1)
                    ->where("t2.IsMarkForDelete =?", 0);
            $select->order("KeyActionSysId DESC");
            $result = $this->db->fetchAll($select);
        }
        return $result;
    }

    public function getNextFlowAction($TemplateId) {
        if ($TemplateId != 'No') {
            $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id', 'TemplateType', 'TargetId', 'TemplateId', 'IsLast'))
                    ->where("t1.id =?", $TemplateId)
                    ->order("t1.id DESC");
            $result1 = $this->db->fetchRow($select1);
            return $result1;
        } else {
            return array();
        }
    }

    public function checkSession($mobileno, $AnsValue) {
        $return = "";
        $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Save_Variable"), array('id'))
                ->where("t1.WAID =?", $mobileno)
                ->order("t1.id DESC");
        $result1 = $this->db->fetchRow($select1);
        if (isset($result1['id'])) {
            $select2 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Save_Variable_All_Step"), array('id', 'VariableName'))
                    ->where("t1.SaveSysId =?", $result1['id'])
                    ->order("t1.id DESC");
            $result2 = $this->db->fetchRow($select2);
            if (isset($result2['id'])) {
                $where = array('id =?' => $result2['id']);
                $dataSet = array(
                    'AnsValue' => $AnsValue,
                );
                $return = $result2['VariableName'];
                $this->updateTable("Tb_Agency_Whatsapp_Save_Variable_All_Step", $dataSet, $where);
            }
        }
        return $return;
    }

    public function sendAiMessage($mobileno, $getVariable, $contact_name) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://wa.globaltravelexchange.com/api/v1/wa/package-message/?query=' . $getVariable,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        ));
        $returnResponse = curl_exec($curl);
        curl_close($curl);
        $returnArray = json_decode(str_replace(array("```json", "```"), "", $returnResponse), true);
        $buttonactionArray = array();
        if (isset($returnArray['filtered_results']) && !empty($returnArray['filtered_results'])) {
            $jsonArray = json_decode($returnArray['filtered_results'], true);
            $u = 0;
            foreach ($jsonArray as $actionval) {
                if ($u >= 10) {
                    break;
                }
                $FlowSysId = 1598865427407919;
                $NewtemplateId = 484;
                $SourceId = trim($actionval['TPSysId']);
                if ($FlowSysId) {
                    $buttonactionArray[$u]['id'] = ($SourceId . '_' . trim($FlowSysId) . '_' . $NewtemplateId . '_' . trim($actionval['TPSysId']) . '_Package');
                    $title = substr($actionval['Title'], 0, 20);
                    $buttonactionArray[$u]['title'] = (strlen($actionval['Title']) > 20) ? rtrim($title) . "..." : $title;
                    if (!empty($actionval['Summary'])) {
                        $buttonactionArray[$u]['description'] = substr($actionval['Summary'], 0, 70);
                    }
                }
                $u++;
            }
            $actionArray = array(
                "button" => "View Packages",
                "sections" => [
                    array(
                        "title" => "View Packages",
                        "rows" => $buttonactionArray
                    )
                ]
            );
            $bodyText = "We've found the best travel packages for you! 🌍✨ Based on your preferences, here are some amazing options:👇";
            $bodyArray = array(
                "text" => mb_convert_encoding($bodyText, "UTF-8"),
            );
            $ButtonType = 'list';
            $interactive = array(
                "type" => $ButtonType,
                "body" => $bodyArray,
                "action" => $actionArray
            );
            $setWhatsAppTemplate = array(
                "messaging_product" => "whatsapp",
                "recipient_type" => "individual",
                "to" => $mobileno,
                "type" => "interactive",
                "interactive" => $interactive
            );
            return array("Template" => $setWhatsAppTemplate);
        }
    }

    public function sendAutoMessage($message_type, $text_type, $contact_name, $apiKey, $mobileno, $messageText, $interactive_id = null) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        $agencySysId = $isActivatedWhatsAppArray['AgencySysId'] ? $isActivatedWhatsAppArray['AgencySysId'] : null;
        $setWhatsAppTemplate = $returnResponse = array();
        if ($message_type == '0') {
            $getVariable = $this->checkSession($mobileno, $messageText);
            $returnKeywordArray[0]['TemplateType'] = "interactive";
        }
        if ($getVariable != 'AiHolidayInformation') {
            if ($text_type == 'interactive' && $interactive_id) {
                $returnKeywordArray[0]['TemplateType'] = "interactive";
            } else {
                $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Step"), array('id', 'TargetID', 'TemplateType', 'FlowSysId'))
                        ->where("t1.WAID =?", $mobileno)
                        ->order("t1.id DESC");
                $result1 = $this->db->fetchRow($select1);
                if (isset($result1['TargetID']) && $result1['TargetID'] != '') {
                    $returnKeywordArray[0]['TemplateType'] = "cusoooooooooMessage";
                } else {
                    $returnKeywordArray = $this->checkkeyword($agencySysId, $messageText);
                }
            }
        }
        if (!empty($returnKeywordArray) && $agencySysId) {
            if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
                } else {
                    $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
                }
                $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
                if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                    if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                        $resultSetArray = array(
                            "access_token" => $getAccessToken
                        );
                        $resultSet = json_encode($resultSetArray);
                    } else {
                        $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                    }
                    if (isset($resultSet)) {
                        $resultArray = json_decode($resultSet, true);
                        if (!empty($resultArray)) {
                            if (trim($getVariable) == 'AiHolidayInformation') {
                                $setWhatsAppTemplate = $this->sendAiMessage($mobileno, $messageText, $contact_name);
                            } else {
                                if ($returnKeywordArray[0]['TemplateType'] == "cusoooooooooMessage") {
                                    $select1 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Step"), array('id', 'TargetID', 'TemplateType', 'FlowSysId'))
                                            ->where("t1.WAID =?", $mobileno)
                                            ->order("t1.id DESC");
                                    $result1 = $this->db->fetchRow($select1);
                                    if (isset($result1['id'])) {
                                        $FlowSysId = $result1['FlowSysId'];
                                        $targetId = $result1['TargetID'];

                                        $select2 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id', 'TargetId', 'TemplateType', 'TemplateId'))
                                                ->where("t1.TemplateId =?", $targetId)
                                                ->where("t1.IsActive =?", 1)
                                                ->where("t1.IsMarkForDelete =?", 0)
                                                ->order("t1.id ASC");
                                        $result2 = $this->db->fetchRow($select2);
                                        if (isset($result2['id'])) {
                                            $TemplateId = $result2['TargetId'];
                                            $TemplateType = $result2['TemplateType'];
                                            if ($TemplateId && $TemplateType == 1) {
                                                $getFlowTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId);
                                                if (!empty($getFlowTemplateDataArray) && $TemplateId != "") {
                                                    if (isset($getFlowTemplateDataArray['TextMessage']['MapVariable']) && $getFlowTemplateDataArray['TextMessage']['MapVariable'] != "") {
                                                        $MapVariable = $getFlowTemplateDataArray['TextMessage']['MapVariable'];
                                                        $returnTemplateType = $TemplateType;
                                                        $this->saveVariableAccordingtoCustomer($MapVariable, $mobileno, $TemplateId, $returnTemplateType, $FlowSysId, 0, 0);
                                                    }
                                                    $TemplateId = $result2['id'];
                                                    $setWhatsAppTemplate = $this->setInteractiveMessage($mobileno, $getFlowTemplateDataArray, $FlowSysId, $TemplateId, $contact_name);
                                                    $where = array('id =?' => $result1['id']);
                                                    $dataSet = array(
                                                        'TargetID' => null,
                                                        'TemplateType' => null,
                                                        'FlowSysId' => null,
                                                        'UpdateDate' => date("Y-m-d H:i:s"),
                                                    );
                                                    $this->updateTable("Tb_Agency_Whatsapp_Flow_Step", $dataSet, $where);
                                                }
                                            } else if ($TemplateId && $TemplateType == 2) {
                                                $getTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId);
                                                if (!empty($getTemplateDataArray) && $TemplateId != "") {
                                                    if (isset($getTemplateDataArray['TextMessage']['MapVariable']) && $getTemplateDataArray['TextMessage']['MapVariable'] != "") {
                                                        $returnTemplateType = $TemplateType;
                                                        $MapVariable = $getTemplateDataArray['TextMessage']['MapVariable'];
                                                        $this->saveVariableAccordingtoCustomer($MapVariable, $mobileno, $TemplateId, $returnTemplateType, $FlowSysId, 0, 0);
                                                    }
                                                    $setWhatsAppTemplate = $this->setCustomerMessage($mobileno, $getTemplateDataArray, $contact_name);
                                                    $NewTemplateId = $result2['id'];
                                                    $select3 = $this->db->select()->from(array("t1" => "Tb_Agency_Whatsapp_Flow_Action"), array('id'))
                                                            ->where("t1.TemplateId =?", $NewTemplateId)
                                                            ->where("t1.IsActive =?", 1)
                                                            ->where("t1.IsMarkForDelete =?", 0)
                                                            ->where("t1.TargetId is not NULL")
                                                            ->order("t1.id ASC");
                                                    $result3 = $this->db->fetchRow($select3);
                                                    $id = $result1['id'];
                                                    $where = array('id =?' => $id);
                                                    if (isset($result3['id'])) {
                                                        $dataSet = array(
                                                            'TargetID' => $result2['id'],
                                                            'TemplateType' => $TemplateType,
                                                            'UpdateDate' => date("Y-m-d H:i:s"),
                                                        );
                                                    } else {
                                                        $dataSet = array(
                                                            'TargetID' => null,
                                                            'TemplateType' => null,
                                                            'FlowSysId' => null,
                                                            'UpdateDate' => date("Y-m-d H:i:s"),
                                                        );
                                                    }
                                                    $this->updateTable("Tb_Agency_Whatsapp_Flow_Step", $dataSet, $where);
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    if ($returnKeywordArray[0]['TemplateType'] == "interactive") {
                                        $interactive_decode_data = ($interactive_id);
                                        $interactiveArray = explode('_', $interactive_decode_data);
                                        $SourceIdData = isset($interactiveArray[0]) ? $interactiveArray[0] : null;
                                        $FlowSysId = isset($interactiveArray[1]) ? $interactiveArray[1] : null;
                                        $TemplateIdNew = isset($interactiveArray[2]) ? $interactiveArray[2] : 'No';
                                        $packageId = isset($interactiveArray[3]) ? $interactiveArray[3] : 'No';
                                        $serviceType = isset($interactiveArray[4]) ? $interactiveArray[4] : '';
                                        if ($SourceIdData && $FlowSysId) {
                                            $getTemplateDataArray = $this->getNextFlowAction($TemplateIdNew);
                                            $returnTemplateType = $getTemplateDataArray['TemplateType'];
                                            $returnTemplateid = isset($getTemplateDataArray['TargetId']) ? $getTemplateDataArray['TargetId'] : null;
                                            if ($returnTemplateid) {
                                                $getFlowTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $returnTemplateType, $returnTemplateid);
                                                if (isset($getFlowTemplateDataArray['TextMessage']['MapVariable']) && $getFlowTemplateDataArray['TextMessage']['MapVariable'] != "") {
                                                    $MapVariable = $getFlowTemplateDataArray['TextMessage']['MapVariable'];
                                                    $this->saveVariableAccordingtoCustomer($MapVariable, $mobileno, $TemplateId, $returnTemplateType, $FlowSysId, 0, 0);
                                                }
                                                if ($returnTemplateType == 2) {
                                                    $isLast = (int) $getTemplateDataArray['IsLast'];
                                                    $returnArray = $this->getAndUpdateTargetId($mobileno, $TemplateIdNew, $returnTemplateType, $FlowSysId, $isLast);
                                                    $setWhatsAppTemplate = $this->setCustomerMessage($mobileno, $getFlowTemplateDataArray, $contact_name);
                                                } else if ($returnTemplateType == 1) {
                                                    $TemplateId = $getTemplateDataArray['id'];
                                                    $setWhatsAppTemplate = $this->setInteractiveMessage($mobileno, $getFlowTemplateDataArray, $FlowSysId, $TemplateId, $packageId, $contact_name, $serviceType);
                                                }
                                            }
                                        }
                                    } else if (isset($returnKeywordArray[0]['TemplateType']) && $returnKeywordArray[0]['TemplateType'] == 4) {
                                        $TemplateId = $returnKeywordArray[0]['TemplateId'];
                                        $TemplateType = $returnKeywordArray[0]['TemplateType'];
                                        $setWhatsAppTemplate = $this->createApiMessage($agencySysId, $TemplateId, $mobileno, $contact_name);
                                    } else if (isset($returnKeywordArray[0]['TemplateType']) && $returnKeywordArray[0]['TemplateType'] == 2) {
                                        $TemplateId = $returnKeywordArray[0]['TemplateId'];
                                        $TemplateType = $returnKeywordArray[0]['TemplateType'];
                                        $getTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId);
                                        if (!empty($getTemplateDataArray)) {
                                            $setWhatsAppTemplate = $this->setCustomerMessage($mobileno, $getTemplateDataArray, $contact_name);
                                        }
                                    } else if (isset($returnKeywordArray[0]['TemplateType']) && $returnKeywordArray[0]['TemplateType'] == 1) {
                                        $TemplateId = $returnKeywordArray[0]['TemplateId'];
                                        $TemplateType = $returnKeywordArray[0]['TemplateType'];
                                        $getTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId);
                                        if (!empty($getTemplateDataArray)) {
                                            $setWhatsAppTemplate = $this->setInteractiveMessage($mobileno, $getTemplateDataArray, null, 'No', 'No', $contact_name);
                                        }
                                    } else if (isset($returnKeywordArray[0]['TemplateType']) && $returnKeywordArray[0]['TemplateType'] == 3) {
                                        $TemplateId = $returnKeywordArray[0]['TemplateId'];
                                        $TemplateType = $returnKeywordArray[0]['TemplateType'];
                                        $getTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $TemplateType, $TemplateId);
                                        if (isset($getTemplateDataArray['TextMessage']) && !empty($getTemplateDataArray['TextMessage'])) {
                                            $FlowSysId = $getTemplateDataArray['TextMessage']['FlowSysId'];
                                            $returnTemplateType = $getTemplateDataArray['TextMessage']['TemplateType'];
                                            $returnTemplateid = $getTemplateDataArray['TextMessage']['TargetId'];
                                            $TemplateId = $getTemplateDataArray['TextMessage']['id'];
                                            if ($returnTemplateType == 1) {
                                                $getFlowTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $returnTemplateType, $returnTemplateid);
                                                if (isset($getFlowTemplateDataArray['TextMessage']['MapVariable']) && $getFlowTemplateDataArray['TextMessage']['MapVariable'] != "") {
                                                    $MapVariable = $getFlowTemplateDataArray['TextMessage']['MapVariable'];
                                                    $this->saveVariableAccordingtoCustomer($MapVariable, $mobileno, $TemplateId, $returnTemplateType, $FlowSysId, 0, 1);
                                                }
                                                $setWhatsAppTemplate = $this->setInteractiveMessage($mobileno, $getFlowTemplateDataArray, $FlowSysId, $TemplateId, $packageId, $contact_name);
                                            } else {
                                                $returnArray = $this->getAndUpdateTargetId($mobileno, $TemplateId, $returnTemplateType, $FlowSysId);
                                                $getFlowTemplateDataArray = $this->getDataFormTemplateType($agencySysId, $returnTemplateType, $returnTemplateid);
                                                if (isset($getFlowTemplateDataArray['TextMessage']['MapVariable']) && $getFlowTemplateDataArray['TextMessage']['MapVariable'] != "") {
                                                    $MapVariable = $getFlowTemplateDataArray['TextMessage']['MapVariable'];
                                                    $this->saveVariableAccordingtoCustomer($MapVariable, $mobileno, $TemplateId, $returnTemplateType, $FlowSysId, 0, 1);
                                                }
                                                $setWhatsAppTemplate = $this->setCustomerMessage($mobileno, $getFlowTemplateDataArray, $contact_name);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!empty($setWhatsAppTemplate)) {
                                $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                                $json = json_encode($setWhatsAppTemplate['Template'], JSON_UNESCAPED_UNICODE);
                                $curl = curl_init();
                                curl_setopt_array($curl, array(
                                    CURLOPT_URL => 'https://graph.facebook.com/v17.0/' . $WhatsAppNumberId . '/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 => $json,
                                    CURLOPT_HTTPHEADER => array(
                                        "Authorization: Bearer $fbexchangeToken",
                                        'Content-Type: application/json'
                                    ),
                                ));
                                $returnResponse = curl_exec($curl);
                                curl_close($curl);
                                $returnArray = json_decode($returnResponse, 1);
                                $AgentName = "";
                                $CustomerMobile = $mobileno;
                                $CustomerName = "";
                                if (isset($returnArray['messages'][0]['id']) && !empty($returnArray['messages'][0]['id'])) {
                                    $whatsapp_messages[0] = array(
                                        'message_type' => 1,
                                        'message_text' => isset($setWhatsAppTemplate["TextMessage"]) ? $setWhatsAppTemplate["TextMessage"] : '',
                                        'whatsapp_message_id' => $returnArray['messages'][0]['id'],
                                        'whatsapp_status' => isset($returnArray['messages'][0]['message_status']) ? $returnArray['messages'][0]['message_status'] : '',
                                        'text_type' => '',
                                        'text_path' => '',
                                        'button_text' => '',
                                        'agent_name' => $AgentName,
                                    );
                                    $postArray = array(
                                        'phone_number_id' => $WhatsAppNumberId,
                                        'contact_id' => trim(str_replace('+', '', $CustomerMobile)),
                                        'contact_name' => $CustomerName,
                                        'whatsapp_messages' => $whatsapp_messages
                                    );
                                    $curl1 = curl_init();
                                    curl_setopt_array($curl1, array(
                                        CURLOPT_URL => 'https://wa.globaltravelexchange.com/api/v1/wa/create-get-whatsapp-message/',
                                        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 => json_encode($postArray),
                                        CURLOPT_HTTPHEADER => array(
                                            "Authorization: Bearer $fbexchangeToken",
                                            'Content-Type: application/json'
                                        ),
                                    ));
                                    curl_exec($curl1);
                                    curl_close($curl1);
                                }
                            }
                        }
                    }
                }
            }
        }
        return $returnResponse;
    }

    public function sendTestAutoMessage($apiKey, $mobileno, $templateName, $templateType = null) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    if (!empty($resultArray)) {
                        $language_code = "en";
                        if ($templateType == 'flow') {
                            $setWhatsAppTemplate = array(
                                "messaging_product" => "whatsapp",
                                "recipient_type" => "individual",
                                "to" => "919015562063", // Replace with the recipient's phone number
                                "type" => "interactive",
                                "interactive" => array(
                                    "type" => "button",
                                    "header" => array(
                                        "type" => "text",
                                        "text" => "Select your options"
                                    ),
                                    "body" => array(
                                        "text" => "Please choose your Packages preferences"
                                    ),
                                    "footer" => array(
                                        "text" => "You can select one options"
                                    ),
                                    "action" => array(
                                        "buttons" => [
                                            array(
                                                "type" => "reply",
                                                "reply" => array(
                                                    "id" => "unique-postback-id",
                                                    "title" => "First Button"
                                                )
                                            ),
                                            array(
                                                "type" => "reply",
                                                "reply" => array(
                                                    "id" => "unique-postback-id333",
                                                    "title" => "Second Button"
                                                )
                                            )
                                        ]
                                    )
//                                    "action" => array(
//                                        "button" => "Select Packages",
//                                        "sections" => [
//                                            array(
//                                                "title" => "Category 1",
//                                                "rows" => [
//                                                    array(
//                                                        "id" => "option1",
//                                                        "title" => "Package For Manali",
//                                                        "description" => "4 Night / 5 Days Cost INR 6000PP "
//                                                    ),
//                                                    array(
//                                                        "id" => "option3",
//                                                        "title" => "Package For Manali",
//                                                        "description" => "4 Night / 5 Days Cost INR 8000PP "
//                                                    ),
//                                                ]
//                                            ),
////        array(
////          "title": "Category 2",
////          "rows": [
////            {
////              "id": "option3",
////              "title": "Option 3",
////              "description": "Description for option 3"
////            },
////            {
////              "id": "option4",
////              "title": "Option 4",
////              "description": "Description for option 4"
////            }
////          ]
////        }
//                                        ]
//                                    )
                                )
                            );
//                            $setWhatsAppTemplate = array(
//                                "messaging_product" => "whatsapp",
//                                "to" => $mobileno,
//                                "type" => "template",
//                                "template" => array(
//                                    "name" => trim($templateName),
//                                    "language" => array(
//                                        "code" => $language_code
//                                    ),
//                                    "components" => array(
//                                        array(
//                                            "type" => "button",
//                                            "sub_type" => "flow",
//                                            "index" => "0",
//                                            "parameters" => array(
//                                                array(
//                                                    "type" => "action",
//                                                    "action" => array(
//                                                        "flow_token" => "unused",
//                                                    )
//                                                )
//                                            )
//                                        )
//                                    )
//                                )
//                            );
                        } else {
                            $setWhatsAppTemplate = array(
                                "messaging_product" => "whatsapp",
                                "to" => $mobileno,
                                "type" => "template",
                                "template" => array(
                                    "name" => trim($templateName),
                                    "language" => array(
                                        "code" => $language_code
                                    )
                                )
                            );
                        }

                        echo json_encode($setWhatsAppTemplate);

                        $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                        $curl = curl_init();
                        curl_setopt_array(
                                $curl,
                                array(
                                    CURLOPT_URL => 'https://graph.facebook.com/v17.0/' . $WhatsAppNumberId . '/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 => json_encode($setWhatsAppTemplate),
                                    CURLOPT_HTTPHEADER => array(
                                        "Authorization: Bearer $fbexchangeToken",
                                        'Content-Type: application/json'
                                    ),
                                )
                        );
                        $returnResponse = curl_exec($curl);
                        curl_close($curl);
                        echo $returnResponse;
                        exit;
                        $returnArray = json_decode($returnResponse, 1);
                        $WhatsAppmessage = "Auto Messgae Sent";
                        $AgentName = "";
                        $CustomerMobile = $mobileno;
                        $CustomerName = "";
                        if (isset($returnArray['messages'][0]['id']) && !empty($returnArray['messages'][0]['id'])) {
                            $whatsapp_messages[0] = array(
                                'message_type' => 1,
                                'message_text' => $WhatsAppmessage,
                                'whatsapp_message_id' => $returnArray['messages'][0]['id'],
                                'whatsapp_status' => $returnArray['messages'][0]['message_status'],
                                'text_type' => '',
                                'text_path' => '',
                                'button_text' => '',
                                'agent_name' => $AgentName,
                            );
                            $postArray = array(
                                'phone_number_id' => $WhatsAppNumberId,
                                'contact_id' => trim(str_replace('+', '', $CustomerMobile)),
                                'contact_name' => $CustomerName,
                                'whatsapp_messages' => $whatsapp_messages
                            );
                            $curl1 = curl_init();
                            curl_setopt_array(
                                    $curl1,
                                    array(
                                        CURLOPT_URL => 'https://wa.globaltravelexchange.com/api/v1/wa/create-get-whatsapp-message/',
                                        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 => json_encode($postArray),
                                        CURLOPT_HTTPHEADER => array(
                                            "Authorization: Bearer $fbexchangeToken",
                                            'Content-Type: application/json'
                                        ),
                                    )
                            );
                            curl_exec($curl1);
                            curl_close($curl1);
                        }
                    }
                }
            }
        }
        return $returnResponse;
    }

    public function insertData($table, $data) {
        $this->db->insert($table, $data);
        return $this->db->lastInsertId();
    }

    public function createFlow($apiKey, array $param = null) {
        $Flow_Name = isset($param['FormName']) && !empty($param['FormName']) ? $param['FormName'] : 'My Form Flow';
        $agencySysId = trim($param['AgencySysId']);
        $flowJson = '{
            "name": "' . $Flow_Name . '",
             "categories": [ "OTHER" ]
         }';
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            $FacebookBusinessId = isset($isActivatedWhatsAppArray['FacebookBusinessId']) ? trim($isActivatedWhatsAppArray['FacebookBusinessId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                    $apiUrl = 'https://graph.facebook.com/v17.0/' . $FacebookBusinessId . '/flows';
                    $curl = curl_init();
                    curl_setopt_array(
                            $curl,
                            array(
                                CURLOPT_URL => $apiUrl,
                                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 => $flowJson,
                                CURLOPT_HTTPHEADER => array(
                                    "Authorization: Bearer $fbexchangeToken",
                                    'Content-Type: application/json'
                                ),
                            )
                    );
                    $returnResponse = curl_exec($curl);
                    $returnArray = json_decode($returnResponse, true);
                    $flowId = isset($returnArray['id']) ? $returnArray['id'] : null;
                    if ($flowId) {
                        $param["FormId"] = $flowId;
                        $updatedId = $this->insertData('Tb_Agency_Whatsapp_Flow_Form', $param);
                        $url = "https://graph.facebook.com/v17.0/$flowId/assets";
                        $filePath = $_SERVER['DOCUMENT_ROOT'] . "/public/upload/media/agency/" . $agencySysId . "/flow.json";
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                            "Authorization: Bearer $fbexchangeToken"
                        ]);
                        $formData = [
                            'file' => new CURLFile($filePath, 'application/json'),
                            'name' => 'flow.json',
                            'asset_type' => 'FLOW_JSON'
                        ];
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
                        $response = curl_exec($ch);
                        if (curl_errno($ch)) {
                            $error_msg = curl_error($ch);
                            return array("Status" => false, "message" => $error_msg);
                        } else {
                            $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            $responseJson = json_decode($response, true);
                            if ($httpStatus == 200 && (isset($responseJson['success']) && $responseJson['success'] == 1)) {
                                $editData = array(
                                    "IsJsonStatus" => true
                                );
                                $where = array('id =?' => $updatedId);
                                $this->updateTable("Tb_Agency_Whatsapp_Flow_Form", $editData, $where);
                                return array("Status" => true, "message" => "Successfully Created");
                            } else {
                                return array("Status" => false, "message" => "An error occurred. Please try again later.");
                            }
                        }
                        curl_close($ch);
                    } else {
                        return array("Status" => false, "message" => $returnResponse);
                    }
                }
            }
        }
    }

    public function updateFlowJsondata($apiKey, $fid, array $param = null) {
        $flowId = $param['FormID'];
        $id = $fid;
        $agencySysId = trim($param['AgencySysId']);
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            $FacebookBusinessId = isset($isActivatedWhatsAppArray['FacebookBusinessId']) ? trim($isActivatedWhatsAppArray['FacebookBusinessId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                    if ($flowId) {
                        $url = "https://graph.facebook.com/v17.0/$flowId/assets";
                        $filePath = $_SERVER['DOCUMENT_ROOT'] . "/public/upload/media/agency/" . $agencySysId . "/flow.json";
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                            "Authorization: Bearer $fbexchangeToken"
                        ]);
                        $formData = [
                            'file' => new CURLFile($filePath, 'application/json'),
                            'name' => 'flow.json',
                            'asset_type' => 'FLOW_JSON'
                        ];
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
                        $response = curl_exec($ch);
                        if (curl_errno($ch)) {
                            $error_msg = curl_error($ch);
                            return array("Status" => false, "message" => $error_msg);
                        } else {
                            $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            $responseJson = json_decode($response, true);
                            if ($httpStatus == 200 && (isset($responseJson['success']) && $responseJson['success'] == 1)) {
                                $param['IsJsonStatus'] = true;
                                $where = array('id =?' => $id);
                                $this->updateTable("Tb_Agency_Whatsapp_Flow_Form", $param, $where);
                                return array("Status" => true, "message" => "Successfully Updated");
                            } else {
                                return array("Status" => false, "message" => "An error occurred. Please try again later.");
                            }
                        }
                        curl_close($ch);
                    }
                }
            }
        }
    }

    public function updateFormFlow($apiKey, $flowId, $request) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    if (!empty($resultArray)) {
                        $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                        $url_status = "https://graph.facebook.com/v22.0/$flowId/$request";
                        $curl = curl_init();
                        curl_setopt_array(
                                $curl,
                                array(
                                    CURLOPT_URL => $url_status,
                                    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_HTTPHEADER => array(
                                        "Authorization: Bearer $fbexchangeToken",
                                        'Content-Type: application/json'
                                    ),
                                )
                        );
                        $response_status = curl_exec($curl);
                        curl_close($curl);
                        return $response_status;
                    }
                }
            }
        }
    }

    public function deleteFormFlow($apiKey, $flowId) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    if (!empty($resultArray)) {
                        $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                        $url_status = "https://graph.facebook.com/v17.0/$flowId";
                        $curl = curl_init();
                        curl_setopt_array(
                                $curl,
                                array(
                                    CURLOPT_URL => $url_status,
                                    CURLOPT_RETURNTRANSFER => true,
                                    CURLOPT_ENCODING => '',
                                    CURLOPT_MAXREDIRS => 10,
                                    CURLOPT_TIMEOUT => 0,
                                    CURLOPT_FOLLOWLOCATION => true,
                                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                    CURLOPT_CUSTOMREQUEST => 'DELETE',
                                    CURLOPT_HTTPHEADER => array(
                                        "Authorization: Bearer $fbexchangeToken",
                                        'Content-Type: application/json'
                                    ),
                                )
                        );
                        $response_status = curl_exec($curl);
                        curl_close($curl);
                        return $response_status;
                    }
                }
            }
        }
    }

    public function checkInteractiveTemplateWithFlow($apiKey) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    if (!empty($resultArray)) {
                        $language_code = "en";
                        $setWhatsAppTemplate = '{"recipient_type": "individual",
  "messaging_product": "whatsapp",
  "to": "919015562063",
  "type": "interactive",
  "interactive": {
    "type": "flow",
    "header": {
      "type": "text",
      "text": "Flow message header"
    },
    "body": {
      "text": "Flow message body"
    },
    "footer": {
      "text": "Flow message footer"
    },
    "action": {
      "name": "flow",
      "parameters": {
        "flow_message_version": "3",
        "flow_token": "AQAAAAACS5FpgQ_cAAAAAD0QI3s.",
        "flow_id": "447506214735741",
        "flow_cta": "Book!",
        "flow_action": "navigate",
        "flow_action_payload": {
          "screen": "FIXED",
          "data": {
            "PACKAGEID": "YYYYYYY",
            "traveldate":   [
            {
              "id": "2",
              "title": "2 days a week"
            },
            {
              "id": "3",
              "title": "3 days a week"
            },
            {
              "id": "4",
              "title": "4 days a week"
            },
            {
              "id": "5",
              "title": "5 days a week"
            },
            {
              "id": "6",
              "title": "6 days a week"
            }
          ],
          "FromDestinationId":  [
            {
              "id": "2",
              "title": "2024-12-16"
            },
            {
              "id": "3",
              "title": "3 days a week"
            },
            {
              "id": "4",
              "title": "4 days a week"
            },
            {
              "id": "5",
              "title": "5 days a week"
            },
            {
              "id": "6",
              "title": "6 days a week"
            }
          ]
          }
        }
      }
    }
  }
}';
                        echo "<pre>";
                        print_r(json_decode($setWhatsAppTemplate, true));
                        exit;
                        $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                        $curl = curl_init();
                        curl_setopt_array(
                                $curl,
                                array(
                                    CURLOPT_URL => 'https://graph.facebook.com/v17.0/' . $WhatsAppNumberId . '/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 => ($setWhatsAppTemplate),
                                    CURLOPT_HTTPHEADER => array(
                                        "Authorization: Bearer $fbexchangeToken",
                                        'Content-Type: application/json'
                                    ),
                                )
                        );
                        $returnResponse = curl_exec($curl);
                        curl_close($curl);
                        echo $returnResponse;
                        exit;
                    }
                }
            }
        }
    }

    public function getRoomJson($param) {
        $TotAdultCount = $TotChildCount = $TotInfantCount = 0;
        $childwithbed2T4 = (int) $param['childWithSharing2'];
        $childwithbed2T4Calculate = (int) $param['childWithSharing2'];
        $childwithoutbed2T4 = (int) $param['childSharing2'];
        $childwithoutbed2T4Calculate = (int) $param['childSharing2'];
        $childwithbed = (int) $param['childWithSharing'] + $childwithbed2T4;
        $childwithbedCalculate = (int) $param['childWithSharing'] + $childwithbed2T4Calculate;
        $childwithoutbed = (int) $param['childSharing'] + $childwithoutbed2T4;
        $childwithoutbedCalculate = (int) $param['childSharing'] + $childwithoutbed2T4Calculate;
        $infant1 = $TotInfantCount = (int) $param['InfentSharingnew'];
        $infant1Calculate = (int) $param['InfentSharingnew'];
        $adultTwinSharing = (int) $param['adultTwinSharing'];
        $adultTripleSharing = (int) $param['adultTripleSharing'];
        $adultSingleSharing = (int) $param['adultSingleSharing'];
        $QuadSharingnew = (int) $param['QuadSharingnew'];
        $QuintSharingnew = (int) $param['QuintSharingnew'];
        $HexaSharingnew = (int) $param['HexaSharingnew'];
        if (($adultTwinSharing + $adultTripleSharing + $adultSingleSharing + $QuadSharingnew + $QuintSharingnew + $HexaSharingnew) == 0) {
            $response = ['status' => 'error', 'message' => 'Total Adult(s) can not be 0 '];
            return $response;
        }
        $adultTwinSharing1 = floor($adultTwinSharing / 2);
        $adultTwinSharing2 = $adultTwinSharing % 2;
        $adultTripleSharing1 = floor($adultTripleSharing / 3);
        $adultTripleSharing2 = $adultTripleSharing % 3;
        $QuadSharingnew1 = floor($QuadSharingnew / 4);
        $QuadSharingnew2 = $QuadSharingnew % 4;
        $QuintSharingnew1 = floor($QuintSharingnew / 5);
        $QuintSharingnew2 = $QuintSharingnew % 5;
        $HexaSharingnew1 = floor($HexaSharingnew / 6);
        $HexaSharingnew2 = $HexaSharingnew % 6;
        if ($adultTwinSharing2 == 1 && $adultTwinSharing > 1) {
            $adultTwinSharing2 = 0;
            $adultTripleSharing1 = 1;
            $adultTwinSharing1 = $adultTwinSharing1 - 1;
        }
        for ($m = 1;
                $m <= $adultTwinSharing1;
                $m++) {
            $param['adult'][] = ($adultTwinSharing == 1) ? 1 : 2;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'twin';
        }
        if ($adultTwinSharing2 == 1) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'twin';
        }
        for ($m = 1;
                $m <= $adultTripleSharing1;
                $m++) {
            $param['adult'][] = 3;
            $param['adult_bed_type'][] = 'extrabed';
            $param['adult_type'][] = 'triple';
        }

        if ($adultTripleSharing2 == 2) {
            $param['adult'][] = 2;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'triple';
        } else if ($adultTripleSharing2 == 1) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'single';
        }
        for ($m = 1;
                $m <= $adultSingleSharing;
                $m++) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'single';
        }
        for ($m = 1;
                $m <= $QuadSharingnew1;
                $m++) {
            $param['adult'][] = 4;
            $param['adult_type'][] = 'quad';
        }
        if ($QuadSharingnew2 == 3) {
            $param['adult'][] = 3;
            $param['adult_type'][] = 'quad';
        } else if ($QuadSharingnew2 == 2) {
            $param['adult'][] = 2;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quad';
        } else if ($QuadSharingnew2 == 1) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quad';
        }
        for ($m = 1;
                $m <= $QuintSharingnew1;
                $m++) {
            $param['adult'][] = 5;
            $param['adult_type'][] = 'quint';
        }
        if ($QuintSharingnew2 == 4) {
            $param['adult'][] = 4;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quint';
        } else if ($QuintSharingnew2 == 3) {
            $param['adult'][] = 3;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quint';
        } else if ($QuintSharingnew2 == 2) {
            $param['adult'][] = 2;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quint';
        } else if ($QuintSharingnew2 == 1) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'quint';
        }
        for ($m = 1;
                $m <= $HexaSharingnew1;
                $m++) {
            $param['adult'][] = 6;
            $param['adult_type'][] = 'hexa';
        }
        if ($HexaSharingnew2 == 5) {
            $param['adult'][] = 5;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'hexa';
        } else if ($HexaSharingnew2 == 4) {
            $param['adult'][] = 4;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'hexa';
        } else if ($HexaSharingnew2 == 3) {
            $param['adult'][] = 3;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'hexa';
        } else if ($HexaSharingnew2 == 2) {
            $param['adult'][] = 2;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'hexa';
        } else if ($HexaSharingnew2 == 1) {
            $param['adult'][] = 1;
            $param['adult_bed_type'][] = '';
            $param['adult_type'][] = 'hexa';
        }
        $mn = 0;
        foreach ($param['adult'] as $adkey => $advalue) {
            $adult_type = (isset($param['adult_type'][$adkey])) ? trim($param['adult_type'][$adkey]) : '';
            $param['child'][$mn] = 0;
            if ($advalue == 3 && $adult_type != 'quad' && $adult_type != 'quint' && $adult_type != 'hexa') {
                if ($childwithoutbedCalculate > 0) {
                    $param['child'][$mn] = 1;
                    $param['child_bed_type'][$mn][] = 'withoutbed';
                    $childwithoutbedCalculate = $childwithoutbedCalculate - 1;
                    if ($childwithoutbed2T4Calculate > 0) {
                        $param['child_age'][$mn][] = 2;
                        $childwithoutbed2T4Calculate = $childwithoutbed2T4Calculate - 1;
                    } else {
                        $param['child_age'][$mn][] = 6;
                    }
                } else if ($childwithbedCalculate > 0) {
                    $param['child'][$mn] = 1;
                    $param['child_bed_type'][$mn][] = 'extrabed';
                    $childwithbedCalculate = $childwithbedCalculate - 1;
                    if ($childwithbed2T4Calculate > 0) {
                        $param['child_age'][$mn][] = 2;
                        $childwithbed2T4Calculate = $childwithbed2T4Calculate - 1;
                    } else {
                        $param['child_age'][$mn][] = 6;
                    }
                }
                if ($infant1Calculate > 0) {
                    $param['infant'][$mn] = 1;
                    $infant1Calculate = $infant1Calculate - 1;
                }
                $mn++;
            }
            if (($advalue != 3 || $adult_type == 'quad' || $adult_type == 'quint' || $adult_type == 'hexa') && $mn < ($childwithoutbed + $childwithbed + $infant1)) {
                if ($adult_type == 'single') {
                    $param['child'][$mn] = 0;
                    $param['infant'][$mn] = 0;
                    $mn++;
                } else {
                    if ($childwithoutbedCalculate > 0 || $childwithbedCalculate > 0 || $infant1Calculate > 0) {
                        if ($childwithoutbedCalculate > 0 && $childwithbedCalculate > 0) {
                            $param['child'][$mn] = 2;
                            $param['child_bed_type'][$mn][] = 'extrabed';
                            $param['child_bed_type'][$mn][] = 'withoutbed';
                            $childwithoutbedCalculate = $childwithoutbedCalculate - 1;
                            $childwithbedCalculate = $childwithbedCalculate - 1;
                            if ($childwithbed2T4Calculate > 0) {
                                $param['child_age'][$mn][] = 2;
                                $childwithbed2T4Calculate = $childwithbed2T4Calculate - 1;
                            } else {
                                $param['child_age'][$mn][] = 6;
                            }
                            if ($childwithoutbed2T4Calculate > 0) {
                                $param['child_age'][$mn][] = 2;
                                $childwithoutbed2T4Calculate = $childwithoutbed2T4Calculate - 1;
                            } else {
                                $param['child_age'][$mn][] = 6;
                            }
                        } else if ($childwithoutbedCalculate > 0 && $childwithbedCalculate < 1) {
                            if ($childwithoutbedCalculate == 1) {
                                $param['child'][$mn] = 1;
                                $param['child_bed_type'][$mn][] = 'withoutbed';
                                $childwithoutbedCalculate = $childwithoutbedCalculate - 1;

                                if ($childwithoutbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithoutbed2T4Calculate = $childwithoutbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                            }
                            if ($childwithoutbedCalculate > 1) {
                                $param['child'][$mn] = 2;
                                $param['child_bed_type'][$mn][] = 'withoutbed';
                                $param['child_bed_type'][$mn][] = 'withoutbed';
                                $childwithoutbedCalculate = $childwithoutbedCalculate - 2;

                                if ($childwithoutbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithoutbed2T4Calculate = $childwithoutbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                                if ($childwithoutbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithoutbed2T4Calculate = $childwithoutbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                            }
                        } else if ($childwithbedCalculate > 0 && $childwithoutbedCalculate < 1) {

                            if ($childwithbedCalculate == 1) {
                                $param['child'][$mn] = 1;
                                $param['child_bed_type'][$mn][] = 'extrabed';
                                $childwithbedCalculate = $childwithbedCalculate - 1;
                                if ($childwithbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithbed2T4Calculate = $childwithbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                            }
                            if ($childwithbedCalculate > 1) {
                                $param['child'][$mn] = 2;
                                $param['child_bed_type'][$mn][] = 'extrabed';
                                $param['child_bed_type'][$mn][] = 'extrabed';
                                $childwithbedCalculate = $childwithbedCalculate - 2;
                                if ($childwithbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithbed2T4Calculate = $childwithbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                                if ($childwithbed2T4Calculate > 0) {
                                    $param['child_age'][$mn][] = 2;
                                    $childwithbed2T4Calculate = $childwithbed2T4Calculate - 1;
                                } else {
                                    $param['child_age'][$mn][] = 6;
                                }
                            }
                        }
                        if ($infant1Calculate > 0) {
                            if ($infant1Calculate == 1) {
                                $param['infant'][$mn] = 1;
                                $infant1Calculate = $infant1Calculate - 1;
                            }
                            if ($infant1Calculate > 1) {
                                $param['infant'][$mn] = 2;
                                $infant1Calculate = $infant1Calculate - 2;
                            }
                        }
                        $mn++;
                    }
                }
            }
        }

        if ($adultTripleSharing2 == 2) {
            $adultTripleSharing2 = 1;
        }
        if ($QuadSharingnew2 == 3 || $QuadSharingnew2 == 2 || $QuadSharingnew2 == 1) {
            $$QuadSharingnew2 = 1;
        }
        if ($QuintSharingnew2 == 4 || $QuintSharingnew2 == 3 || $QuintSharingnew2 == 2 || $QuintSharingnew2 == 1) {
            $QuintSharingnew2 = 1;
        }
        if ($HexaSharingnew2 == 5 || $HexaSharingnew2 == 4 || $HexaSharingnew2 == 3 || $HexaSharingnew2 == 2 || $HexaSharingnew2 == 1) {
            $HexaSharingnew2 = 1;
        }
        $countRooms = $adultTwinSharing1 + $adultTwinSharing2 + $adultTripleSharing1 + $adultTripleSharing2 + $adultSingleSharing + $QuadSharingnew1 + $QuadSharingnew2 + $QuintSharingnew1 + $QuintSharingnew2 + $HexaSharingnew1 + $HexaSharingnew2;
        $childSharing = $childwithbed + $childwithoutbed;
        $roomCountMatchChild = (($adultTwinSharing1 * 2) + ($adultTripleSharing1 * 1) + ($adultSingleSharing * 2) + ($QuadSharingnew1 * 2) + ($QuadSharingnew2 * 2) + ($QuintSharingnew1 * 2) + ($QuintSharingnew2 * 2) + ($HexaSharingnew1 * 2) + ($HexaSharingnew2 * 2));
        if ($roomCountMatchChild < ($childSharing)) {
            $response = ['status' => 'error', 'message' => 'Child count must be less than ' . $childSharing . '. Otherwise take extra Adult on twin/triple/single/quad sharing to accommodate the ' . $childSharing . ' child. '];
            return $response;
        }
        $roomjson = array();
        for ($i = 0, $k = 1;
                $k <= $countRooms;
                $k++, $i++) {
            $totalAdultChild = (int) $param['adult'][$i] + (int) $param['child'][$i];
            if (!empty($param['adult'][$i])) {
                $roomjson[$k]['Adult'] = $param['adult'][$i];
                $roomjson[$k]['adult_type'] = $param['adult_type'][$i];
                $roomjson[$k]['Child'] = (int) $param['child'][$i];
                $roomjson[$k]['Infant'] = (int) $param['infant'][$i];
            }
            $TotAdultCount = $TotAdultCount + $param['adult'][$i];
            $TotChildCount = $TotChildCount + $param['child'][$i];
            $noOfAdultsar[$k] = $param['adult'][$i];
            if ($param['adult'][$i] == 3) {
                $roomjson[$k]['bedtype'] = $param['adult_bed_type'][$i];
            }
            if ($param['child'][$i] > 0) {
                for ($c = 1;
                        $c <= (int) $param['child'][$i];
                        $c++) {
                    $roomjson[$k]['ChildBedType_' . $c] = $param['child_bed_type'][$i][$c - 1];
                    $roomjson[$k]['ChildAge_' . $c] = $param['child_age'][$i][$c - 1];
                    $selectnoOfChildar[$k] = $param['child'][$i];
                }
            }
        }
        $roominfojson = array("status" => true, "roomjson" => $roomjson);
        return $roominfojson;
    }

    public function separateMobileNumber($fullNumber, $countryCodes) {
        $fullNumber = ltrim($fullNumber, '+');
        $result = array();
        foreach ($countryCodes as $countryCode) {
            $countryCode = ltrim($countryCode, '+');
            if (strpos($fullNumber, $countryCode) === 0) {
                $mobileNumber = substr($fullNumber, strlen($countryCode));
                if (preg_match('/^\d{6,15}$/', $mobileNumber)) {
                    $result['status'] = true;
                    $result['country_code'] = $countryCode;
                    $result['mobile_number'] = $mobileNumber;
                    return $result;
                } else {
                    $result['status'] = false;
                    $result['error'] = 'Invalid mobile number length';
                    return $result;
                }
            }
        }
        $result['status'] = false;
        $result['error'] = 'Invalid country code';
        return $result;
    }

    public function createApiMessage($AgencySysId, $TemplateSysId, $mobileno, $contact_name = '') {
        $objAgency = new Travel_Model_TblAgency();
        $getWhatsappMessageById = $objAgency->getWhatsappMessage($AgencySysId, $TemplateSysId);
//echo "<pre>";print_r($getWhatsappMessageById);exit;
        $getWhatsappMessageVariable = $objAgency->getWhatsappMessageVariable($TemplateSysId);
        $getWhatsappMessageVariableArray = array();
        $replacedDataArr = array();
        if ($contact_name != '') {
            $ContactName = ucfirst(strtolower(trim($contact_name)));
            $replacedDataArr['{CustomerName}'] = $ContactName;
        }
        foreach ($getWhatsappMessageVariable as $mvKey => $mvValue) {
            $getWhatsappMessageVariableArray[$mvValue['HeaderType']][] = $mvValue;
        }
        if ($getWhatsappMessageById[0]['TemplateType'] == 2) {
            $getWhatsappCarouselMessageById = $objAgency->getWhatsappCarouselMessage($AgencySysId, $TemplateSysId, 1);
            $getWhatsappCarouselMessageByIdArray = $getWhatsappCarouselMessageVariableArray = array();
            foreach ($getWhatsappCarouselMessageById as $carouselkey => $carouselvalue) {
                $getWhatsappCarouselMessageByIdArray[$carouselvalue['Id']] = array(
                    'TemplateName' => $carouselvalue['TemplateName'],
                    'HeaderType' => $carouselvalue['HeaderType'],
                    'ButtonType' => $carouselvalue['ButtonType'],
                    'ButtonInfoJson' => $carouselvalue['ButtonInfoJson'],
                    'WhatsAppMessage' => $carouselvalue['WhatsAppMessage'],
                    'MediaFileName' => $carouselvalue['MediaFileName'],
                );
                $getWhatsappCarouselMessageVariableArray[$carouselvalue['Id']][] = array(
                    'TemplateHeaderSysId' => $carouselvalue['TemplateHeaderSysId'],
                    'HeaderType' => $carouselvalue['VarHeaderType'],
                    'HeaderValue' => $carouselvalue['HeaderValue'],
                    'MappingFromFB' => $carouselvalue['MappingFromFB'],
                    'HeaderValueReference' => $carouselvalue['HeaderValueReference'],
                    'HeaderValueText' => $carouselvalue['HeaderValueText'],
                );
            }
        }
        $PreviewHtmlNew = '';
        if ($getWhatsappMessageById[0]['HeaderType'] == 2) {
            $TemplateHeader = $getWhatsappMessageById[0]['TemplateHeader'];
            if (isset($getWhatsappMessageVariableArray[1]) && !empty($getWhatsappMessageVariableArray[1])) {
                foreach ($getWhatsappMessageVariableArray[1] as $key => $value) {
                    $TemplateHeader = str_replace('{{' . ($value['MappingFromFB']) . '}}', ($value['HeaderValue']), $TemplateHeader);
                    $TemplateHeader = str_replace($value['HeaderValue'], $replacedDataArr[$value['HeaderValue']], $TemplateHeader);
                }
            }
            $PreviewHtmlNew .= $TemplateHeader;
        }
        $WhatsAppMessage = $getWhatsappMessageById[0]['WhatsAppMessage'];
        $TemplateFooter = $getWhatsappMessageById[0]['TemplateFooter'];
        $WhatsAppMessage = preg_replace('/\r?\n|\r/', '<br>', $WhatsAppMessage);
        if (isset($getWhatsappMessageVariableArray[2]) && !empty($getWhatsappMessageVariableArray[2])) {
            foreach ($getWhatsappMessageVariableArray[2] as $key => $value) {
                if ($value['HeaderValue'] == '{DynamicValue}') {
                    if ($value['HeaderValueText'] == '') {
                        $WhatsAppMessage = str_replace('{{' . ($value['MappingFromFB']) . '}}', '<span class="TemplateHeaderSysId_' . ($value['TemplateHeaderSysId']) . '">' . '{' . ($value["HeaderValueReference"]) . '}' . '</span>', $WhatsAppMessage);
                    } else {
                        $WhatsAppMessage = str_replace('{{' . ($value['MappingFromFB']) . '}}', '<span class="TemplateHeaderSysId_' . ($value['TemplateHeaderSysId']) . '">' . ($value["HeaderValueText"]) . '</span>', $WhatsAppMessage);
                    }
                } else {
//echo '{{' . ($value['MappingFromFB']) . '}}';
                    $WhatsAppMessage = str_replace('{{' . ($value['MappingFromFB']) . '}}', ($value['HeaderValue']), $WhatsAppMessage);
                    $WhatsAppMessage = str_replace($value['HeaderValue'], $replacedDataArr[$value['HeaderValue']], $WhatsAppMessage);
                }
            }
        }
        $PreviewHtmlNew .= $WhatsAppMessage;
        $PreviewHtmlNew .= '<br><br><span style="font-size:16px;color:#9b9797;">' . $TemplateFooter . '</span>';
        if ($mobileno != '') {
            $PreviewHtml = $PreviewHtmlNew;
            $PreviewHtml = str_replace('<br>', '\n', $PreviewHtml);
            $PreviewHtml = str_replace('CustomerName', $contact_name, $PreviewHtml);
            $PreviewHtml = strip_tags($PreviewHtml);
            $components = $headerArray = array();
            if ($getWhatsappMessageById[0]['HeaderType'] == 2 && isset($getWhatsappMessageVariableArray[1][0])) {
                $Text = isset($getWhatsappMessageVariableArray[1][0]['HeaderValue']) ? $replacedDataArr[$getWhatsappMessageVariableArray[1][0]['HeaderValue']] : '';
                $headerArray = array(
                    "type" => "HEADER",
                    "parameters" => array(
                        array(
                            "type" => "text",
                            "text" => $Text,
                        )
                    )
                );
            } else if ($getWhatsappMessageById[0]['HeaderType'] == 3) {
                $headerImageName = $getWhatsappMessageById[0]['MediaFileName'];
                $imagePath = 'https://globaltravelexchange.com/public/upload/media/agency/' . ($AgencySysId) . '/whatsapp' . '/' . $headerImageName;
                if ($headerImageName != '') {
                    $headTypeText = "image";
                    if ($getWhatsappMessageById[0]['MediaType'] == 3) {
                        $headTypeText = "document";
                    }
                    $headerArray = array(
                        "type" => "HEADER",
                        "parameters" => array(
                            array(
                                "type" => $headTypeText,
                                $headTypeText => array(
                                    "link" => "$imagePath"
                                )
                            )
                        )
                    );
                }
            }
//echo "<pre>";print_r($headerArray);exit;
            if (!empty($headerArray)) {
                array_push($components, $headerArray);
            }
            $bodyParameters = array();
            if (isset($getWhatsappMessageVariableArray[2])) {
                foreach ($getWhatsappMessageVariableArray[2] as $mvKey => $mvValue) {
                    if ($mvValue['HeaderValue'] == '{DynamicValue}') {
                        $Text = (isset($HeaderValueText[$mvValue['MappingFromFB']]) && !empty($HeaderValueText[$mvValue['MappingFromFB']])) ? $HeaderValueText[$mvValue['MappingFromFB']] : '';
                    } else {
                        $Text = isset($mvValue['HeaderValue']) ? isset($replacedDataArr[$mvValue['HeaderValue']]) ? $replacedDataArr[$mvValue['HeaderValue']] : '110687PRA' : ' ';
                    }
                    if ($Text == '') {
                        $returnResponse = array("status" => false, "message" => 'Body text can not be blank.');
                        echo json_encode($returnResponse);
                        exit;
                    }
                    if ($Text != '110687PRA') {
                        $Parameters = array(
                            "type" => "text",
                            "text" => $Text
                        );
                        array_push($bodyParameters, $Parameters);
                    }
                }
            }
            if (!empty($bodyParameters)) {
                $bodyArray = array(
                    "type" => "body",
                    "parameters" => $bodyParameters
                );
                array_push($components, $bodyArray);
            }
            $button_text = array();
            $ButtonInfoJson = json_decode($getWhatsappMessageById[0]['ButtonInfoJson'], 1);
            $btnIndex = 0;
            foreach ($ButtonInfoJson as $bjKey => $bjValue) {
                if ($bjValue['type'] == 'FLOW') {
                    $footerArray = array(
                        "type" => "button",
                        "sub_type" => "flow",
                        "index" => 0,
                        "parameters" => array(
                            array(
                                "type" => "action",
                                "action" => array(
                                    "flow_token" => "unused"
                                )
                            )
                        )
                    );
                    array_push($components, $footerArray);
                } else {
                    if ($bjValue['type'] == 2 && (isset($bjValue['url_type']) && $bjValue['url_type'] == 2)) {
                        if ($urlid == '') {
                            $returnResponse = array("status" => false, "message" => 'Leading Page URL Id Can Not Be Blank.');
                            echo json_encode($returnResponse);
                            exit;
                        }
                        $footerArray = array(
                            "type" => "button",
                            "sub_type" => "URL",
                            "index" => $btnIndex,
                            "parameters" => array(
                                array(
                                    "type" => "text",
                                    "text" => "$urlid"
                                )
                            )
                        );
                        array_push($components, $footerArray);
                        $button_text[] = array('title' => $bjValue['button_text'], 'url' => $bjValue['website_url'] . $urlid, 'phone_number' => '', 'icon' => 'external-link');
                    } else if ($bjValue['type'] == 2 && (isset($bjValue['url_type']) && $bjValue['url_type'] == 1)) {
                        $button_text[] = array('title' => $bjValue['button_text'], 'url' => $bjValue['website_url'], 'phone_number' => '', 'icon' => 'external-link');
                    } else if ($bjValue['type'] == 1 && (isset($bjValue['url_type']) && $bjValue['url_type'] == 1)) {
                        $button_text[] = array('title' => $bjValue['button_text'], 'url' => "", 'phone_number' => $bjValue['country_code'] . $bjValue['phone_number'], 'icon' => 'phone');
                    }
                    $btnIndex++;
                }
            }
//echo "<pre>";print_r($getWhatsappCarouselMessageByIdArray);
            if (!empty($getWhatsappCarouselMessageByIdArray)) {
                $carouselArray = $cards = array();
                $incC = 0;
                foreach ($getWhatsappCarouselMessageByIdArray as $carouselkey => $carouselvalue) {
                    $componentsCr = array();
                    if (!empty($carouselvalue['MediaFileName'])) {
                        $imagePathH = 'https://globaltravelexchange.com/public/upload/media/agency/' . ($AgencySysId) . '/whatsapp' . '/' . $carouselvalue['MediaFileName'];
                        $parametersH = array();
                        $parametersH[] = array(
                            'type' => 'IMAGE',
                            'image' => array(
                                'link' => $imagePathH
                            )
                        );
                        $componentsCr[] = array(
                            'type' => 'HEADER',
                            'parameters' => $parametersH,
                        );
                    }

                    if (isset($getWhatsappCarouselMessageVariableArray[$carouselkey]) && !empty($getWhatsappCarouselMessageVariableArray[$carouselkey])) {
                        $parametersB = array();
                        foreach ($getWhatsappCarouselMessageVariableArray[$carouselkey] as $cvkey => $cvvalue) {
                            if ($cvvalue['HeaderValue'] == '{DynamicValue}') {
                                $TextV = (isset($CarouselHeaderValueText[$carouselkey][$cvvalue['MappingFromFB']]) && !empty($CarouselHeaderValueText[$carouselkey][$cvvalue['MappingFromFB']])) ? $CarouselHeaderValueText[$carouselkey][$cvvalue['MappingFromFB']] : '';
                            } else {
                                $TextV = isset($cvvalue['HeaderValue']) ? isset($replacedDataArr[$cvvalue['HeaderValue']]) ? $replacedDataArr[$cvvalue['HeaderValue']] : '110687PRA' : ' ';
                            }
                            if ($TextV == '') {
                                $returnResponse = array("status" => false, "message" => 'Body text can not be blank.');
                                echo json_encode($returnResponse);
                                exit;
                            }
                            $parametersB[] = array(
                                'type' => 'text',
                                'text' => $TextV,
                            );
                        }
                        $componentsCr[] = array(
                            'type' => 'BODY',
                            'parameters' => $parametersB,
                        );
                    }
                    $button_text = array();
                    $ButtonInfoJsonC = json_decode($carouselvalue['ButtonInfoJson'], 1);
                    $btnIndex = 0;
                    $urlidC = isset($CarouselUrlId[$carouselkey]) ? $CarouselUrlId[$carouselkey] : '';
                    foreach ($ButtonInfoJsonC as $cbjKey => $cbjValue) {
                        if ($cbjValue['type'] == 'FLOW') {
                            $footerArrayC = array(
                                "type" => "button",
                                "sub_type" => "flow",
                                "index" => 0,
                                "parameters" => array(
                                    array(
                                        "type" => "action",
                                        "action" => array(
                                            "flow_token" => "unused"
                                        )
                                    )
                                )
                            );
                            array_push($componentsCr, $footerArrayC);
                        } else {
                            if ($cbjValue['type'] == 2 && (isset($cbjValue['url_type']) && $cbjValue['url_type'] == 2)) {
                                if ($urlidC == '') {
                                    $returnResponse = array("status" => false, "message" => 'Leading Page URL Id Can Not Be Blank.');
                                    echo json_encode($returnResponse);
                                    exit;
                                }
                                $footerArrayC = array(
                                    "type" => "button",
                                    "sub_type" => "URL",
                                    "index" => $btnIndex,
                                    "parameters" => array(
                                        array(
                                            "type" => "text",
                                            "text" => "$urlidC"
                                        )
                                    )
                                );
                                array_push($componentsCr, $footerArrayC);
                            }
                            $btnIndex++;
                        }
                    }


                    $cards[] = array(
                        'card_index' => $incC,
                        'components' => $componentsCr,
                    );
                    $incC++;
                }
                $carouselArray['type'] = 'CAROUSEL';
                $carouselArray['cards'] = $cards;
                array_push($components, $carouselArray);
            }


            $setWhatsAppApiTemplate = array(
                "messaging_product" => "whatsapp",
                "to" => "$mobileno",
                "type" => "template",
                "template" => array(
                    "name" => $getWhatsappMessageById[0]['TemplateName'],
                    "language" => array(
                        "code" => 'en'
                    ),
                    "components" => $components,
                )
            );
// echo $PreviewHtml; exit;
            return array("Template" => $setWhatsAppApiTemplate, "TextMessage" => $PreviewHtml);
        }
    }

    public function sendOptWhatsapp($mobileNo, $otpCode, $apiKey = '7A739273-D037-4386-9B23-BCD6A4B1ED8B') {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $FacebookBusinessId = isset($isActivatedWhatsAppArray['FacebookBusinessId']) ? trim($isActivatedWhatsAppArray['FacebookBusinessId']) : '';
            if (($getAccessToken != '') && ($FacebookBusinessId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (isset($resultSet)) {
                    $resultArray = json_decode($resultSet, true);
                    if (!empty($resultArray)) {
                        $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';

                        $setWhatsAppTemplate = '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "' . $mobileNo . '",
  "type": "template",
  "template": {
    "name": "login_otp",
    "language": {
      "code": "en"
    },
    "components": [
      {
        "type": "body",
        "parameters": [
          {
            "type": "text",
            "text": "' . $otpCode . '"
          }
        ]
      },
      {
        "type": "button",
        "sub_type": "url",
        "index": "0",
        "parameters": [
          {
            "type": "text",
            "text": "' . $otpCode . '"
          }
        ]
      }
    ]
  }
}';
                        $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
                        $CURLOPT_CUSTOMREQUEST = "POST";
                        $apiUrl = "https://graph.facebook.com/v20.0/$WhatsAppNumberId/messages";
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => $apiUrl,
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => $CURLOPT_CUSTOMREQUEST,
                            CURLOPT_POSTFIELDS => $setWhatsAppTemplate,
                            CURLOPT_HTTPHEADER => array(
                                "Authorization: Bearer $fbexchangeToken",
                                'Content-Type: application/json'
                            ),
                        ));
                        $returnResponse = curl_exec($curl);
                        curl_close($curl);
                    }
                }
            }
        }
        return $returnResponse;
    }

    public function sendCustomeMessage($apiKey, $setWhatsAppTemplate) {
        $modelFaceBook = new Travel_Model_TblFacebook();
        $isActivatedWhatsAppArray = $modelFaceBook->isWhatsAppActivatedInAgency($apiKey);
        if (isset($isActivatedWhatsAppArray['IsWhatsApp']) && $isActivatedWhatsAppArray['IsWhatsApp'] == true) {
            if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                $getAccessToken = isset($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) ? trim($isActivatedWhatsAppArray['WhatsAppStaticAccessToken']) : '';
            } else {
                $getAccessToken = isset($isActivatedWhatsAppArray['AccessToken']) ? trim($isActivatedWhatsAppArray['AccessToken']) : '';
            }
            $WhatsAppNumberId = isset($isActivatedWhatsAppArray['WhatsAppNumberId']) ? trim($isActivatedWhatsAppArray['WhatsAppNumberId']) : '';
            if (($getAccessToken != '') && ($WhatsAppNumberId != '')) {
                if ($isActivatedWhatsAppArray['WhatsAppApiType'] == 1) {
                    $resultSetArray = array(
                        "access_token" => $getAccessToken
                    );
                    $resultSet = json_encode($resultSetArray);
                } else {
                    $resultSet = $modelFaceBook->WAExchangeToken($getAccessToken);
                }
                if (!empty($setWhatsAppTemplate)) {
                    $resultArray = json_decode($resultSet, true);
                    $fbexchangeToken = isset($resultArray['access_token']) ? trim($resultArray['access_token']) : '';
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://graph.facebook.com/v17.0/' . $WhatsAppNumberId . '/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 => json_encode($setWhatsAppTemplate),
                        CURLOPT_HTTPHEADER => array(
                            "Authorization: Bearer $fbexchangeToken",
                            'Content-Type: application/json'
                        ),
                    ));
                    $returnResponse = curl_exec($curl);
                    curl_close($curl);
                    $returnArray = json_decode($returnResponse, 1);
                    $AgentName = "";
                    $CustomerMobile = $setWhatsAppTemplate['to'];
                    $CustomerName = "";
                    if (isset($returnArray['messages'][0]['id']) && !empty($returnArray['messages'][0]['id'])) {
                        $whatsapp_messages[0] = array(
                            'message_type' => 1,
                            'message_text' => "Package Proposal Sent",
                            'whatsapp_message_id' => $returnArray['messages'][0]['id'],
                            'whatsapp_status' => isset($returnArray['messages'][0]['message_status']) ? $returnArray['messages'][0]['message_status'] : '',
                            'text_type' => '',
                            'text_path' => '',
                            'button_text' => '',
                            'agent_name' => $AgentName,
                        );
                        $postArray = array(
                            'phone_number_id' => $WhatsAppNumberId,
                            'contact_id' => trim(str_replace('+', '', $CustomerMobile)),
                            'contact_name' => $CustomerName,
                            'whatsapp_messages' => $whatsapp_messages
                        );
                        $curl1 = curl_init();
                        curl_setopt_array($curl1, array(
                            CURLOPT_URL => 'https://wa.globaltravelexchange.com/api/v1/wa/create-get-whatsapp-message/',
                            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 => json_encode($postArray),
                            CURLOPT_HTTPHEADER => array(
                                "Authorization: Bearer $fbexchangeToken",
                                'Content-Type: application/json'
                            ),
                        ));
                        curl_exec($curl1);
                        $file_name = trim(str_replace('+', '', $CustomerMobile)) . '.txt';
                        file_put_contents("public/logs/whatsapp/$file_name", $returnResponse);
                        curl_close($curl1);
                    }
                }
            }
        }
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit