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/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/b2bzend/application/controllers/RegisterController.php
<?php

/*
 * Catabatic Technology Pvt. Ltd.
 * File Name :RegisterController.php
 * File Description :Register controller managed all registration process
 * Created By : Pooja Choudhary
 * Created Date: 01-June-2016
 */

class RegisterController extends Catabatic_ValidateCustomer {
    
    public $smtpUserName;
    public $smtpPassword;
    public $smtpPort;
    public $smtpHost;
    public $fromEmail;
    public $fromName;
    public $siteUrl;
    public $SMSURL;
    public $SMSMETHOD;
    public $SMSAPIKEY;
    public $SMSSENDER;
    public $SMSFORMAT;
    public $SENDREGISTERSMSCONFIG;
    public $_HtmlPurifier;
    public $_captcha;

    public function init() {
        $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
        $this->smtpUserName = $aConfig['smtpUserName'];
        $this->smtpPassword = $aConfig['smtpPassword'];
        $this->smtpPort = $aConfig['smtpPort'];
        $this->smtpHost = $aConfig['smtpHost'];
        $this->fromEmail = $aConfig['fromEmail'];
        $this->fromName = $aConfig['fromName'];
        $this->siteUrl = $aConfig['bootstrap']['siteUrl'];
        $this->SMSURL = Catabatic_Helper::getSMSURL();
        $this->SMSMETHOD = Catabatic_Helper::getSMSMETHOD();
        $this->SMSAPIKEY = Catabatic_Helper::getSMSAPIKEY();
        $this->SMSSENDER = Catabatic_Helper::getSMSSENDER();
        $this->SMSFORMAT = Catabatic_Helper::getSMSFORMAT();
        $this->SENDREGISTERSMSCONFIG = Catabatic_Helper::getSENDREGISTERSMSCONFIG();
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();

        //set layout
        $this->_helper->layout->setLayout('layout-signup');
        $this->_captcha = new Zend_Session_Namespace('Captcha');
        //$this->_helper->layout->disableLayout();
    }

    public function indexAction() {
        $objLocation = new Travel_Model_TblLocation();
        $countryListArray = $objLocation->getCountryList();
        $this->view->countryListArray = $countryListArray;
        $this->_captcha->sessionc = array('captcha' => rand(10000, 99999));
        $this->view->captcha = $this->_captcha->sessionc;
        //        echo '<pre>'; print_r($countryListArray);
    }

    public function emailExistsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $emailId = $this->getRequest()->getParam('emailId');

        $objAgency = new Travel_Model_TblAgency();
        if ($objAgency->isAgencyEmailExists(trim($emailId))) {
            // echo true;
            echo json_encode(false);
        } else {
            echo json_encode(true);
        }
    }

    public function emailExistsMobileAction() {
        $emailId = $this->getRequest()->getParam('emailId');
        $data['status'] = false;
        $data['message'] = '';
        if ($this->getRequest()->isPost()) {
            $objAgency = new Travel_Model_TblAgency();
            if ($objAgency->isAgencyEmailExists(trim($emailId))) {
                $data['status'] = false;
                $data['message'] = 'Email Id Already Exist';
            } else {
                $data['status'] = true;
                $data['message'] = '';
            }
        } else {
            $data['status'] = false;
            $data['message'] = 'Please use Post Method';
        }
        json_encode($data);
        exit;
    }

    public function saveSignUpMobileAction() {
        $data['status'] = false;
        $data['message'] = '';
        $isSave = true;
        if ($this->getRequest()->isPost()) {
            $agencyName = trim($this->getRequest()->getParam('agencyName'));
            $contactName = $this->getRequest()->getParam('contactName');
            $emailId = $this->getRequest()->getParam('emailId');
            $mobileNo = $this->getRequest()->getParam('mobileNo');
            $countrycode = $this->getRequest()->getParam('countrycode');
            $shortDetail = $this->getRequest()->getParam('shortDetail');
            $cityId = $this->getRequest()->getParam('city_id');
            $countryId = $this->getRequest()->getParam('country_id');
            if ($agencyName == '') {
                $data['status'] = false;
                $data['message'] = 'Enter Agency Name';
                $isSave = false;
            }
            if ($contactName == '') {
                $data['status'] = false;
                $data['message'] = 'Enter Contact Name';
                $isSave = false;
            }
            if ($emailId == '') {
                $data['status'] = false;
                $data['message'] = 'Enter Email Id';
                $isSave = false;
            }
            if ($mobileNo == '') {
                $data['status'] = false;
                $data['message'] = 'Enter Mobile No.';
                $isSave = false;
            }
            if ((int) $cityId == 0) {
                $data['status'] = false;
                $data['message'] = 'Enter City Id';
                $isSave = false;
            }
            if ((int) $countryId == 0) {
                $data['status'] = false;
                $data['message'] = 'Enter Country Id';
                $isSave = false;
            }
            if ($countrycode == '') {
                $data['status'] = false;
                $data['message'] = 'Enter Country Code';
                $isSave = false;
            }
            $objAgency = new Travel_Model_TblAgency();
            if (!$objAgency->isAgencyEmailExists(trim($emailId)) && $isSave == true) {
                $currentDate = date('Y-m-d h:i:s');
                $agencyData = array(
                    'agencyName' => $agencyName,
                    'selectCountry' => $countryId,
                    'selectState' => 0,
                    'selectCity' => $cityId,
                    'contactName' => $contactName,
                    'emailId' => $emailId,
                    'mobileNo' => $mobileNo,
                    'countrycode' => $countrycode,
                    'shortDetail' => $shortDetail,
                    'CreateDate' => $currentDate,
                    'IsApproved' => 0,
                );
                $result = $objAgency->registerAgency($agencyData);
                $emailData = base64_encode($emailId);
                $link = base64_encode('byEmail');
                if ($this->SENDREGISTERSMSCONFIG == 1) {
                    $url = $this->siteUrl . "register/verify-contact-data/data/$emailData/link/$link";
                } else {
                    $url = $this->siteUrl . "/register/verify-contact-email/data/$emailData/link/$link";
                }
                $params = array('agent_name' => ucfirst($contactName), 'verification_link' => $url);
                $subject = 'You\'re almost there, verify your email with ' . SITE_NAME;
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/emails/');
                $html->assign($params);
                $bodyText = $html->render('agent_registration.phtml');
                $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => $subject, 'to' => array($emailId), 'bodyHtml' => $bodyText, 'bodyText' => '');
                try {
                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $arrEmailStatistics = array(
                        "TPSysId" => 0,
                        "TypeSysId" => 1, // 1 For Email 2 For SMS
                        "AgencySysId" => 0,
                        "AgentSysId" => 0,
                        "Title" => $bodyText,
                        "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => date('Y-m-d H:i:s')
                    );
                    $this->mailSentByElastice($emailData, $arrEmailStatistics);
                    $bodyTextForAgent = 'New agency is registered on <a href="' . SITE_FULL_URL . 'admin">' . SITE_FULL_URL . '/admin</a> !';
                    $emailDataFOrGTXADMIN = array('fromEmail' => $emailId, 'fromName' => $contactName, 'subject' => 'New Registration alert on GTX', 'to' => array('nikita@catpl.co.in', 'gaurav@catpl.co.in'), 'bodyHtml' => $bodyTextForAgent, 'bodyText' => '');
                    $this->mailSentByElastice($emailDataFOrGTXADMIN, $arrEmailStatistics);
                    $data['status'] = true;
                    $data['message'] = '';
                } catch (Exception $err) {
                    $data['status'] = false;
                    $data['message'] = $err->getMessage();
                }
            } else {
                $data['status'] = false;
                $data['message'] = 'Email Id Already Exist';
            }
        } else {
            $data['status'] = false;
            $data['message'] = 'Please use post Method';
        }
        echo json_encode($data);
        exit;
    }

    public function saveSignUpAction() {
        //disable layout
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isXmlHttpRequest()) {
            $agencyName = $this->getRequest()->getParam('agencyName');
            $countryTitle = $this->getRequest()->getParam('selectCountry');
            $selectState = $this->getRequest()->getParam('selectState');
            $cityTitle = $this->getRequest()->getParam('selectCity');
            $contactName = $this->getRequest()->getParam('contactName');
            $emailId = $this->getRequest()->getParam('emailId');
            $mobileNo = $this->getRequest()->getParam('mobileNo');
            $countrycode = $this->getRequest()->getParam('countrycode');
            $shortDetail = $this->getRequest()->getParam('shortDetail');
            $captcha = $this->getRequest()->getParam('captcha');
            $cityId = $this->getRequest()->getParam('city_id');
            $countryId = $this->getRequest()->getParam('country_id');
            $captcha = $this->getRequest()->getParam('captcha');
            if (strtolower($captcha) != $this->_captcha->sessionc['captcha']) {
                echo 3;
                exit;
            } else {
                $objAgency = new Travel_Model_TblAgency();
                if (!$objAgency->isAgencyEmailExists(trim($emailId))) {
                    $currentDate = date('Y-m-d h:i:s');
                    $objLocation = new Travel_Model_TblLocation();
                    if (trim($countryId) == '') {
                        $countryId = $objLocation->addCountry($countryTitle, $currentDate);
                    }
                    if (trim($cityId) == '') {
                        $cityId = $objLocation->addCity($cityTitle, $countryId, $countryTitle, $currentDate);
                    }
                    $agencyData = array(
                        'agencyName' => $agencyName,
                        'selectCountry' => $countryId,
                        'selectState' => $selectState,
                        'selectCity' => $cityId,
                        'contactName' => $contactName,
                        'emailId' => $emailId,
                        'mobileNo' => $mobileNo,
                        'countrycode' => $countrycode,
                        'shortDetail' => $shortDetail,
                        'CreateDate' => $currentDate,
                        'IsApproved' => 0,
                        'AgencyType' => 0,
                    );
                    $result = $objAgency->registerAgency($agencyData);
                    $emailData = base64_encode($emailId);
                    $link = base64_encode('byEmail');
                    if ($this->SENDREGISTERSMSCONFIG == 1) {
                        $url = $this->siteUrl . "register/verify-contact-data/data/$emailData/link/$link";
                    } else {
                        $url = $this->siteUrl . "/register/verify-contact-email/data/$emailData/link/$link";
                    }
                    $params = array('agent_name' => ucfirst($contactName), 'verification_link' => $url);
                    #Set subject
                    $subject = 'You\'re almost there, verify your email with ' . SITE_NAME;
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/emails/');
                    $html->assign($params);
                    $bodyText = $html->render('agent_registration.phtml');
                    $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => $subject, 'to' => array($emailId), 'bodyHtml' => $bodyText, 'bodyText' => '');
                    try {
                        //echo "success";
                        $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                        $arrEmailStatistics = array(
                            "TPSysId" => 0,
                            "TypeSysId" => 1, // 1 For Email 2 For SMS
                            "AgencySysId" => 0,
                            "AgentSysId" => 0,
                            "Title" => $bodyText,
                            "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                            "Status" => 0,
                            "RefSysId" => "",
                            "RefSysStatus" => "",
                            "CreateDate" => date('Y-m-d H:i:s')
                        );
                        $this->mailSentByElastice($emailData, $arrEmailStatistics);
                        $bodyTextForAgent = 'New agency is registered on <a href="' . SITE_FULL_URL . 'admin">' . SITE_FULL_URL . '/admin</a> !';
                        $emailDataFOrGTXADMIN = array('fromEmail' => $emailId, 'fromName' => $contactName, 'subject' => 'New Registration alert on GTX', 'to' => array('nikita@catpl.co.in', 'gaurav@catpl.co.in'), 'bodyHtml' => $bodyTextForAgent, 'bodyText' => '');
                        $this->mailSentByElastice($emailDataFOrGTXADMIN, $arrEmailStatistics);
                    } catch (Exception $err) {
                        
                    }
                    echo 1;
                    exit;
                    //end Mail code
                } else {
                    echo 2;
                    exit;
                }
            }
        }
    }

    public function verifyContactEmailAction() {
        //set layout
        $this->_helper->layout->setLayout('layout-register');

        if ($this->getRequest()->getParams()) {
            $objAgency = new Travel_Model_TblAgency();
            $getData = $this->getRequest()->getParams();
            $emailId = base64_decode($this->getRequest()->getParam('data'));
            $link = isset($getData['link']) ? base64_decode($getData['link']): '';
            $verify = isset($getData['verify']) ? base64_decode($getData['verify']) : '';

            if (@$emailId) {
                $result = $this->getDataByEmail($emailId);

                $params = array('data' => base64_encode($result['PrimaryEmail']), 'param' => 2);
            } else {
                $agencyId = $this->getRequest()->getParam('id');
                $result = $objAgency->getUserDataByAgency($agencyId);
                $params = array('id' => $agencyId, 'param' => 2);
            }
            // code for redirection if user is not valid @Pooja 22Feb2017
            $isRegisterUrlValidForEdit = Zend_Controller_Action_HelperBroker::getStaticHelper('User')->isRegisterUrlValidForEdit($result);

            if (!empty($isRegisterUrlValidForEdit) && empty($link)) {
                //                Please use your login credentials to login into your agency portal.
                $this->_helper->flashMessenger->addMessage("Please use your login credentials to login into your agency portal.");
                $this->_helper->redirector('login', 'login');
                exit;
            }

            if ($link == 'byEmail' && $result['IsActive'] == 1) {
                $params = array('data' => base64_encode($emailId), 'param' => 6);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }

            if ($verify == 'sendersEmail') {
                $updateData['IsEmailIdForCustVarified'] = 1;
                $objAgency->updateAgencyData($updateData, $result['AgencySysId']);
                $this->view->verificationSendersEmail = 'done';
            }
            if ($link == 'bySendersEmail' && $result['IsEmailIdForCustVarified'] == 1 && $result['IsActive'] == 1) {
                $params = array('data' => base64_encode($emailId), 'param' => 6);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }

            if (!empty($result)) {

                $this->view->verifyData = $result;
                $param = $this->_getParam('param');
                $this->view->param = $param;

                if (@$result['IsVarified'] == 1 && @$param == '') {
                    $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                }

                //Verify email id of Agency's User
                $agencyData = array('IsVarified' => 1);
                $objAgency->updateAgencyData($agencyData, $result['AgencySysId']);
                //                print_r($param);
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
    }

    public function verifyContactAction() {
        //set layout
        $this->_helper->layout->disableLayout();

        if ($this->getRequest()->getParams()) {
            $objAgency = new Travel_Model_TblAgency();
            $emailId = $this->getRequest()->getParam('data');
            if ($emailId) {
                $result = $this->getDataByEmail($emailId);
            } else {
                $agencyId = $this->getRequest()->getParam('id');
                $result = $objAgency->getUserDataByAgency($agencyId);
            }
            if (!empty($result)) {
                return $this->view->verifyData = $result;
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
    }

    public function personalDetailsAction() {
        $this->_helper->layout->disableLayout();

        if ($this->getRequest()->getParams()) {
            $objAgency = new Travel_Model_TblAgency();
            $emailId = $this->getRequest()->getParam('data');
            //            $link = base64_decode($this->getRequest()->getParam('link'));
            //            $verify = base64_decode($this->getRequest()->getParam('verify'));


            if ($emailId) {
                $result = $this->getDataByEmail($emailId);
            } else {
                $agencyId = $this->getRequest()->getParam('id');
                $result = $objAgency->getUserDataByAgency($agencyId);
            }
            //            if($verify == 'sendersEmail'){
            //             $updateData['IsEmailIdForCustVarified'] = 1;
            //             $objAgency->updateAgencyData($updateData,$agencyId);
            //             $this->view->verificationSendersEmail = 'done';
            //            }
            //            if($link == 'bySendersEmail' && $result['IsEmailIdForCustVarified'] == 1){
            //                $params = array('data' => base64_encode($emailId), 'param' => 6);
            //                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
            //                exit;
            //            }
            //            Zend_Debug::dump($result);
            $nameArr = explode(' ', $result['PrimaryContactName']);
            $result['FirstName'] = $nameArr[0];
            $result['LastName'] = @$nameArr[1];

            if (!empty($result)) {

                $roleTitle = unserialize(AGENCY_USER_ROLE);
                $ownerPersonalDetailsArray = $objAgency->getPersonalDetailsByAgency($result['AgencySysId'], $roleTitle[0]);
                $sAdminPersonalDetailsArray = $objAgency->getPersonalDetailsByAgency($result['AgencySysId'], $roleTitle[1]);
                //                echo '<pre>';
                //                print_r($ownerPersonalDetailsArray);
                //                 print_r($sAdminPersonalDetailsArray);
                //                die;
                $this->view->ownerData = $ownerPersonalDetailsArray;
                $this->view->superadminData = $sAdminPersonalDetailsArray;
                $this->view->verifyData = $result;
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
    }

    public function savePersonalDetailsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();

            $firstName = $getData['1_firstName'];
            $lastName = $getData['1_lastName'];
            $designation = $getData['1_designation'];
            $contactNo = $getData['1_contactNo'];
            $mobileNo = $getData['1_mobileNo'];
            $emailId = $getData['1_emailId'];

            $senderEmailId = $getData['senderEmailId'];
            $AgencyId = $getData['AgencyId'];

            $agencyUserRoleArr = unserialize(AGENCY_USER_ROLE);

            //add user role 
            $agencyPrimaryUserRoleData = array(
                'AgencySysId' => $AgencyId,
                'RoleTitle' => $agencyUserRoleArr[0],
                'IsAdmin' => 1,
                'IsAbleToManageMember' => 1
            );
            $objAgency = new Travel_Model_TblAgency();
            $userRoleId = $objAgency->addUserRole($agencyPrimaryUserRoleData);

//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            $oRandStrPass = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->generateRandomString(5);
            $agencyPrimaryUserData = array(
                'AgencySysId' => $AgencyId,
                'FirstName' => $firstName,
                'LastName' => $lastName,
                'Designation' => $designation,
                'ContNo' => $contactNo,
                'mobileNo' => $mobileNo,
                'countrycode' => $getData['1_cCode'],
                'countrycode2' => $getData['1_mCode'],
                'EmailId' => $emailId,
                'EmailIdForCustomer' => $senderEmailId, // to be updated in TblAgency
                'userRole' => $userRoleId,
                'Password' => md5($oRandStrPass),
                'UserAccessLevelType' => 1,
                //                'RandStr' => $oRandStrPass,
                'CreateDate' => $currentDate
            );
            /* Upload Photo ID Proof */

            $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $AgencyId . "/";

            $tmpFilePath = $_FILES['photoIdProofFile']['tmp_name'];
            //Make sure we have a filepath
            $fileName = $_FILES['photoIdProofFile']['name'];

            $newFileName = 'photo_id_' . rand(0, 99);

            $newFileName = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);
            //add agency user in agency user table and update primary user in agency table
            $userId = $objAgency->addAgencyUser($agencyPrimaryUserData, $agencyUserRoleArr[0]);
            //            below email is commented because it will send by admin aftr verification from admin
            //            if($userId){
            //                $url = $this->siteUrl . "login";
            //
            //                    //Mail code to send login link to staff  
            //                    $message = "Dear " . ucfirst($firstName) . ", <br><br>";
            //                    $message .= "Please find following your login details:<br><br>";
            //                    $message .= "Email Id/ Username: $emailId <br>";
            //                    $message .= "Password: $oRandStrPass <br>";
            //                    $message .= "Please <a href=" . $url . ">Click Here</a> to login your account. <br><br>";                    
            //                    $message .= "Thanks,<br>";
            //                    $message .= "Team Global Travel Exchange<br><br>";
            //
            //                    $mailConfig = array(
            //                        'ssl' => 'ssl',
            //                        'auth' => 'login',
            //                        'port' => $this->smtpPort,
            //                        'username' => $this->smtpUserName,
            //                        'password' => $this->smtpPassword
            //                    );
            //
            //                    $transport = new Zend_Mail_Transport_Smtp($this->smtpHost, $mailConfig);
            //
            //                    $mail = new Zend_Mail("iso-8859-1");
            //                    $mail->addTo($emailId)
            //                            ->setSubject('Login Details')
            //                            ->setBodyHtml($message)
            //                            ->setFrom($this->fromEmail, $this->fromName);
            //
            //                    try { 
            //                        $mail->send($transport);
            //                    } catch (Exception $err) {
            //                        print_r($err, true);
            //                    }
            //            }
            if (!empty($newFileName)) {
                /* Insert into database */
                $FileType = explode('_', $getData['photoIdProof']);
                $agencyUploadData = array(
                    'UserSysId' => $userId,
                    'fileName' => $newFileName,
                    'docType' => $FileType[0],
                    'originalFileName' => $FileType[1],
                    'Title' => $FileType[1],
                    'CreateDate' => $currentDate
                );
                $objAgency->addAgencyUserDocument($agencyUploadData);
                //echo "Success";
            }

            $isSameAsPrimaryContact = $getData['isSameAsPrimaryContact'];

            // insert second user 
            if ($isSameAsPrimaryContact == 'No') {

                $agencyOperationalUserRoleData = array(
                    'AgencySysId' => $AgencyId,
                    'RoleTitle' => $agencyUserRoleArr[1]
                );
                $objAgency = new Travel_Model_TblAgency();
                $userRoleId2 = $objAgency->addUserRole($agencyOperationalUserRoleData);


                $firstName2 = $getData['2_firstName'];
                $lastName2 = $getData['2_lastName'];
                $designation2 = $getData['2_designation'];
                $contactNo2 = $getData['2_contactNo'];
                $mobileNo2 = $getData['2_mobileNo'];
                $emailId2 = $getData['2_emailId'];

                $RandStrPass = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->generateRandomString(5);
                $agencyOperationalUserData = array(
                    'AgencySysId' => $AgencyId,
                    'FirstName' => $firstName2,
                    'LastName' => $lastName2,
                    'Designation' => $designation2,
                    'ContNo' => $contactNo2,
                    'mobileNo' => $mobileNo2,
                    'countrycode' => $getData['2_cCode'],
                    'EmailId' => $emailId2,
                    'userRole' => $userRoleId2,
                    'Password' => md5($RandStrPass),
                    'UserAccessLevelType' => 1,
                    //                    'RandStr' => $RandStrPass,
                    'CreateDate' => $currentDate
                );

                $res = $objAgency->addAgencyUser($agencyOperationalUserData, $agencyUserRoleArr[1]);
                //                if($res){
                //                $url = $this->siteUrl . "login";
                //
                //                    //Mail code to send login link to staff  
                //                    $message = "Dear " . ucfirst($firstName2) . ", <br><br>";
                //                    $message .= "Please find following your login details:<br><br>";
                //                    $message .= "Email Id/ Username: $emailId2 <br>";
                //                    $message .= "Password: $RandStrPass <br>";
                //                    $message .= "Please <a href=" . $url . ">Click Here</a> to login your account. <br><br>";                    
                //                    $message .= "Thanks,<br>";
                //                    $message .= "Team Global Travel Exchange<br><br>";
                //
                //                    $mailConfig = array(
                //                        'ssl' => 'ssl',
                //                        'auth' => 'login',
                //                        'port' => $this->smtpPort,
                //                        'username' => $this->smtpUserName,
                //                        'password' => $this->smtpPassword
                //                    );
                //
                //                    $transport = new Zend_Mail_Transport_Smtp($this->smtpHost, $mailConfig);
                //
                //                    $mail = new Zend_Mail("iso-8859-1");
                //                    $mail->addTo($emailId2)
                //                            ->setSubject('Login Details')
                //                            ->setBodyHtml($message)
                //                            ->setFrom($this->fromEmail, $this->fromName);
                //
                //                    try { 
                //                        $mail->send($transport);
                //                    } catch (Exception $err) {
                //                        print_r($err, true);
                //                    }
                //                }
            }
            //exit;
            $this->_helper->flashMessenger->addMessage("Personal Details added successfully.");
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 3);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
        }
    }

    public function companyDetailsAction() {
        $this->_helper->layout->disableLayout();

        if ($this->getRequest()->getParams()) {
            $objAgency = new Travel_Model_TblAgency();
            $emailId = $this->getRequest()->getParam('data');

            if ($emailId) {
                $result = $this->getDataByEmail($emailId);
            } else {
                $agencyId = $this->getRequest()->getParam('id');
                $result = $objAgency->getUserDataByAgency($agencyId);
            }
            if (!empty($result)) {

                $companyTypeArray = array_keys(unserialize(AGENCY_COMPANY_TYPE));
                $agencyDocTypeKeys = array_keys(unserialize(AGENCY_DOC_TYPE));
                $agencyDocTypeArray = unserialize(AGENCY_DOC_TYPE);
                //        echo '<pre>';   print_r($agencyDocTypeKeys);
                //            print_r($agencyDocTypeArray); die;

                if ($result['FirmType'] == $companyTypeArray[1]) {
                    $docType1 = $agencyDocTypeKeys[1];
                    $docType2 = $agencyDocTypeKeys[2];
                } else if ($result['FirmType'] == $companyTypeArray[2]) {
                    $docType1 = $agencyDocTypeKeys[3];
                    $docType2 = $agencyDocTypeKeys[4];
                } else {
                    $docType1 = $agencyDocTypeKeys[0];
                    $docType2 = $agencyDocTypeKeys[4];
                }

                $agencynBankDetails = $objAgency->getBankDetailsByAgency($result['AgencySysId']);
                $registeredAddress = $objAgency->getAddressByAgency($result['AgencySysId'], 1); // for owner
                $corporateAddress = $objAgency->getAddressByAgency($result['AgencySysId'], 2); // for superadmin
                $compFile1 = $objAgency->getAgencyFiles($result['AgencySysId'], $docType1);
                $compFile2 = $objAgency->getAgencyFiles($result['AgencySysId'], $docType2);
                $agencyUserDetailsArr = $objAgency->getAgencyUserDataById($result['PrimaryUserSysId']);

                //get data by masking
                $valNatureOfBusinessMask = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->getNatureOfBusinessBitMask($result['BusinessTypeMask']);

                // For getting All currency Array
                $objCurrency = new Travel_Model_TblCurrency();
                $currencyListArr = $objCurrency->getCurrencyIdsAndSymbolList();
                //                echo '<pre>'; print_r($currencyListArr); die;

                $this->view->messages = $this->_helper->flashMessenger->getMessages();
                $this->view->agencynBankDetails = $agencynBankDetails;
                $this->view->registeredAddress = $registeredAddress;
                $this->view->corporateAddress = $corporateAddress;
                $this->view->compFile1 = $compFile1;
                $this->view->compFile2 = $compFile2;
                $this->view->verifyData = $result;
                $this->view->currencyListArr = $currencyListArr;
                $this->view->valNatureOfBusinessMask = $valNatureOfBusinessMask;
                $this->view->agencyUserDetailsArr = $agencyUserDetailsArr;
                $this->view->AgencyPrimaryUserSignature = $agencyUserDetailsArr['Signature'];
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
            //            $objLocation = new Travel_Model_TblLocation();
            //            $countryListArray = $objLocation->getCountryList();
            //            $this->view->countryListArray = $countryListArray;
            $this->view->verifyData = $result;
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
        //for country list
        $objCountry = new Travel_Model_TblCountry();
        $countryList = $objCountry->getCountryList();
        //echo "<pre>";print_r($result);die;
        $this->view->countryList = $countryList;
        $selectedCityList = array();
        if (isset($result['ExpertiseDestinationsId']) && !empty($result['ExpertiseDestinationsId'])) {
            $cityobj = new Travel_Model_TblCity();
            //echo $SupplierList['ExpertiseDestinationsId'];die;
            $cityIds = trim($result['ExpertiseDestinationsId']);
            $selectedCityList = $cityobj->getCityDetailsByMultipleId($cityIds);
            //print_r($selectedCityList);die;
        }
        $this->view->selectedCityList = $selectedCityList;
    }

    public function saveCompanyDetailsAction() {
        $this->_helper->layout->disableLayout();
        $objAgency = new Travel_Model_TblAgency();
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            $getAgencyData = $this->getDataByEmail($getData['regEmail']);
            $pathToUploadFile = USER_FILE_UPLOAD_PATH . 'agency/' . $getData['AgencyId'] . "/";
            if (!file_exists($pathToUploadFile)) {
                mkdir($pathToUploadFile, 0755, true);
            }
//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            $filesArray = array();
            $i = 0;
            foreach ($_FILES as $key => $value) {
                $tmpFilePath = $_FILES[$key]['tmp_name'];
                if ($tmpFilePath != "") {
                    $shortname = $_FILES[$key]['name'];
                    //save the url and the file
                    $ext = @substr($shortname, strrpos($shortname, '.'));
                    $res = explode('File', $key);
                    $newNAme = $res[0] . '_' . $i . time() . $ext;
                    $filePath = $pathToUploadFile . $newNAme;
                    if ($key == 'companyLogo') {
                        $fileUpload = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImage($tmpFilePath, $pathToUploadFile, $_FILES[$key]['name'], $newNAme);
                    } else {
                        $fileUpload = move_uploaded_file($tmpFilePath, $filePath);
                    }
                    if ($fileUpload) {
                        $filesArray[$key] = ($newNAme) ? $newNAme : '';
                    }
                }
            }
            //             Array ( [5] => Certificate Of Incorporation [6] => Shop & Establishment Certificate [7] => Owner/Director's PAN Number [8] => Partnership Deed [9] => Company PAN Card Number ) 
            $companyTypeArray = array_keys(unserialize(AGENCY_COMPANY_TYPE));
            $agencyDocTypeKeys = array_keys(unserialize(AGENCY_DOC_TYPE));
            $agencyDocTypeArray = unserialize(AGENCY_DOC_TYPE);
            //         echo '<pre>';   print_r($agencyDocTypeKeys);
            //  print_r($filesArray); die;

            if ($getData['companyType'] == $companyTypeArray[1]) {
                $fileName1 = $filesArray['sole_copyShopCertFile'];
                $docType1 = $agencyDocTypeKeys[1];
                $origFileName1 = $agencyDocTypeArray[6];
                $fileName2 = @$filesArray['sole_ownerPanNoFile'];
                $docType2 = $agencyDocTypeKeys[2];
                $origFileName2 = $agencyDocTypeArray[7];
            } else if ($getData['companyType'] == $companyTypeArray[2]) {
                $fileName1 = @$filesArray['firm_copyPartnershipDeed'];
                $docType1 = $agencyDocTypeKeys[3];
                $origFileName1 = $agencyDocTypeArray[8];
                $fileName2 = @$filesArray['firm_compPanNoFile'];
                $docType2 = $agencyDocTypeKeys[4];
                $origFileName2 = $agencyDocTypeArray[9];
            } else {
                $fileName1 = @$filesArray['pvtltd_CinNOFile'];
                $docType1 = $agencyDocTypeKeys[0];
                $origFileName1 = $agencyDocTypeArray[5];
                $fileName2 = @$filesArray['pvtltd_compPanNoFile'];
                $docType2 = $agencyDocTypeKeys[4];
                $origFileName2 = $agencyDocTypeArray[9];
            }


            $agencyUploadDoc1Data = array(
                'AgencySysId' => $getAgencyData['AgencySysId'],
                'fileName' => $fileName1,
                'DocType' => $docType1,
                'Title' => $origFileName1,
                'originalFileName' => $origFileName1,
                'CreateDate' => $currentDate
            );
            //print_r($agencyUploadDoc1Data);
            $objAgency->addAgencyFile($agencyUploadDoc1Data);

            $agencyUploadDoc2Data = array(
                'AgencySysId' => $getAgencyData['AgencySysId'],
                'fileName' => $fileName2,
                'DocType' => $docType2,
                'Title' => $origFileName2,
                'originalFileName' => $origFileName2,
                'CreateDate' => $currentDate
            );
            //            print_r($agencyUploadDoc2Data); die;
            $objAgency->addAgencyFile($agencyUploadDoc2Data);



            $regCountryId = $getData['registered_country_id'];
            $regCityId = $getData['registered_city_id'];

            $objLocation = new Travel_Model_TblLocation();
            // save country to data base if not exists and get country id
            $cId = trim(@$regCountryId);
            if (empty($cId)) {
                $regCountryId = $objLocation->addCountry($getData['selectCountry']);
            }
            // save City to data base if not exists and get city id
            if (trim($regCityId) == '') {
                $regCityId = $objLocation->addCity($getData['selectCity'], $regCountryId, $getData['selectCountry'], $currentDate);
            }

            // create masking for nature of business
            $natureOfBusinessArray = unserialize(AGENCY_NATURE_OF_BUSINESS);

            $natureOfBusinessMasking = 1;
            foreach ($natureOfBusinessArray as $key => $value) {
                $natureOfBusinessMasking .= (in_array($key, $getData['natureOfBusiness'])) ? 1 : 0;
            }

            //array to update agency data
            $agencyData = array(
                'Title' => $getData['companyName'] ? $getData['companyName'] : '',
                'FirmType' => $getData['companyType'] ? $getData['companyType'] : 0,
                'ServiceTaxNo' => $getData['companyServiceTaxNo'] ? $getData['companyServiceTaxNo'] : '',
                'BusinessTypeMask' => $natureOfBusinessMasking,
                'DisplayName' => $getData['compDisplayName'] ? $getData['compDisplayName'] : '',
                'Url' => $getData['websiteUrl'] ? $getData['websiteUrl'] : '',
                'Logo' => $filesArray['companyLogo'] ? $filesArray['companyLogo'] : '',
                'InvoiceSignature' => $filesArray['InvoiceSignature'] ? $filesArray['InvoiceSignature'] : '',
                'TrxCurrency' => $getData['trxcurrency'] ? $getData['trxcurrency'] : '',
            );
            $companyTypeArray = array_keys(unserialize(AGENCY_COMPANY_TYPE));
            if ($getData['companyType'] == $companyTypeArray[1]) {
                $agencyData['PanCardNo'] = $getData['sole_ownerPanNo'] ? $getData['sole_ownerPanNo'] : '';
            } else if ($getData['companyType'] == $companyTypeArray[2]) {
                $agencyData['PanCardNo'] = $getData['firm_compPanNo'] ? $getData['firm_compPanNo'] : '';
            } else {
                $agencyData['CIN'] = $getData['pvtltd_CinNO'] ? $getData['pvtltd_CinNO'] : '';
                $agencyData['PanCardNo'] = $getData['pvtltd_compPanNo'] ? $getData['pvtltd_compPanNo'] : '';
            }
            $geographyCountryId = $getData['geographyCountry'];
            $geographyCountryId = implode(',', $getData['geographyCountry']);
            $regExpertiseCityId = $getData['expertisecity'];
            $agencyData['Expertisecountriesid'] = $geographyCountryId ? $geographyCountryId : 0;
            $agencyData['Expertisedestinationsid'] = $regExpertiseCityId ? $regExpertiseCityId : 0;
            /* Added by mangal for signature image  27-05-2020 Start */
            $pathToUploadFileAgencyPhoto = USER_FILE_UPLOAD_PATH . 'agency/' . $getData['AgencyId'] . "/photo/";
            if (!file_exists($pathToUploadFileAgencyPhoto)) {
                mkdir($pathToUploadFileAgencyPhoto, 0755, true);
            }
            $tmpFilePathAgencyPhoto = ($_FILES['AgencyPhoto']['tmp_name']) ? $_FILES['AgencyPhoto']['tmp_name'] : '';
            if ($tmpFilePathAgencyPhoto != "") {
                $shortnameAgencyPhoto = $_FILES['AgencyPhoto']['name'];
                $extAgencyPhoto = @substr($shortnameAgencyPhoto, strrpos($shortnameAgencyPhoto, '.'));
                $newNAmeAgencyPhoto = 'AgencyPhoto_' . $getAgencyData['AgencySysId'] . $extAgencyPhoto;
                $filePathAgencyPhoto = $pathToUploadFileAgencyPhoto . $newNAmeAgencyPhoto;
                if ($extAgencyPhoto == '.jpg' || $extAgencyPhoto == '.png' || strtolower($extAgencyPhoto) == '.jpeg') {
                    //echo $newNAmeAgencyPhoto.'- ',$pathToUploadFileAgencyPhoto;die;
                    //$fileUploadAgencyPhoto = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImage($tmpFilePathAgencyPhoto, $pathToUploadFileAgencyPhoto, $_FILES['AgencyPhoto']['name'], $newNAmeAgencyPhoto);
                    if (move_uploaded_file($tmpFilePathAgencyPhoto, $pathToUploadFileAgencyPhoto . "/" . $newNAmeAgencyPhoto)) {
                        if ($newNAmeAgencyPhoto) {
                            $agencyData['AgencyPhoto'] = ($newNAmeAgencyPhoto) ? $newNAmeAgencyPhoto : '';
                        }
                    }
                    //echo $fileUploadAgencyPhoto;die;
                }
            }
            /* Added by mangal for signature image  27-05-2020 End */
            $objAgency->updateAgencyData($agencyData, $getAgencyData['AgencySysId']);


            //array to update and insert registered data
            $agencyRegAddressData = array();

            $agencyRegAddressData['AgencySysId'] = $getAgencyData['AgencySysId'];
            $agencyRegAddressData['AddressType'] = 1; //registered address
            $agencyRegAddressData['CreateDate'] = $currentDate;
            if ($getData['address'] != '' && $getData['address2'] != '') {
                $agencyRegAddressData['address'] = $getData['address'] . '___' . $getData['address2'];
            } else if ($getData['address'] != '') {
                $agencyRegAddressData['address'] = $getData['address'];
            }
            if ($regCountryId != '') {
                $agencyRegAddressData['selectCountry'] = $regCountryId;
            }
            if ($getData['selectState'] != '') {
                $agencyRegAddressData['selectState'] = $getData['selectState'] ? $getData['selectState'] : 0;
            }
            if ($regCityId != '') {
                $agencyRegAddressData['selectCity'] = $regCityId;
            }
            if ($getData['pinCode'] != '') {
                $agencyRegAddressData['pinCode'] = $getData['pinCode'];
            }
            if ($filesArray['copyAddressProofFile'] != '') {
                $agencyRegAddressData['copyAddressProofFile'] = $filesArray['copyAddressProofFile'];
            }

            $objAgency->addAgencyAddressData($agencyRegAddressData);

            if ($getData['isSameAsRegisteredAddress'] == 'No') {

                $corpCountryId = $getData['corporate_country_id'];
                $corpCityId = $getData['corporate_city_id'];
                $objLocation = new Travel_Model_TblLocation();
                // save country to data base if not exists and get country id
                if (trim($corpCountryId) == '') {
                    $corpCountryId = $objLocation->addCountry($getData['selectCountry2']);
                }
                // save City to data base if not exists and get city id
                if (trim($corpCityId) == '') {
                    $corpCityId = $objLocation->addCity($getData['selectCity2'], $corpCountryId, $getData['selectCountry2'], $currentDate);
                }

                if ($getData['corpAddress'] != '' && $getData['corpAddress2'] != '') {
                    $corpAddress = $getData['corpAddress'] . '___' . $getData['corpAddress2'];
                } else if ($getData['corpAddress'] != '') {
                    $corpAddress = $getData['corpAddress'];
                }
                $agencyCorpAddressData = array(
                    'AgencySysId' => $getAgencyData['AgencySysId'],
                    'AddressType' => 2, //corporate address
                    'address' => $corpAddress,
                    'selectCountry' => $corpCountryId,
                    //                    'selectState' => $getData['selectState2'],
                    'selectCity' => $corpCityId,
                    'pinCode' => $getData['pinCode2'],
                    'copyAddressProofFile' => $filesArray['copyAddressProofFile2'],
                    'CreateDate' => $currentDate
                );
                $objAgency->addAgencyAddressData($agencyCorpAddressData);
            }

            $bankCountryId = $getData['bank_country_id'];
            $bankCityId = $getData['bank_city_id'];
            $objLocation = new Travel_Model_TblLocation();
            // save country to data base if not exists and get country id
            if (trim($bankCountryId) == '') {
                $bankCountryId = $objLocation->addCountry($getData['selectCountry3']);
            }
            // save City to data base if not exists and get city id
            if (trim($bankCityId) == '') {
                $bankCityId = $objLocation->addCity($getData['selectCity3'], $bankCountryId, $getData['selectCountry3'], $currentDate);
            }

            $agencyBankDetailsData = array(
                'AgencySysId' => $getAgencyData['AgencySysId'],
                'accountHolderName' => $getData['accountHolderName'],
                'accountNumber' => $getData['accountNumber'],
                'ifscCode' => $getData['ifscCode'],
                'accountType' => $getData['accountType'],
                'BankName' => $getData['BankName'],
                'branchName' => $getData['branchName'],
                'selectCountry3' => $bankCountryId,
                //                'selectState3' => $getData['selectState3'],
                'selectCity3' => $bankCityId,
                'CancelledChequeFile' => $filesArray['cancelledChequeCopy'],
                'CreateDate' => $currentDate
            );
            $objAgency->addAgencyBankData($agencyBankDetailsData);

            $staffSignData = array();
            $staffSignData['UpdateDate'] = $currentDate;
            $staffSignData['SecondaryEmail'] = (isset($getData['SecondaryEmail']) && !empty($getData['SecondaryEmail'])) ? trim($getData['SecondaryEmail']) : '';
            $staffSignData['ContactNo2'] = (isset($getData['ContactNo2']) && !empty($getData['ContactNo2'])) ? trim($getData['ContactNo2']) : '';
            $staffSignData['countrycode2'] = (isset($getData['countrycode2']) && !empty($getData['countrycode2'])) ? trim($getData['countrycode2']) : '';
            $staffSignData['signature'] = !empty($getData['signature']) ? $this->_HtmlPurifier->filter($getData['signature']) : '';
            $objStaff = new Travel_Model_TblAgencyStaff();
            $userSysId = $getData['UserId'];
            $objStaff->editUserDetails($staffSignData, $userSysId); //update Agency User
            //$this->redirect('register/verify-contact-email/param/4');
            //            $this->_helper->redirector('verify-contact-email');
            $this->_helper->flashMessenger->addMessage("Company Details added successfully.");
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 4);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
        }
        exit;
    }

    public function moreAboutCompanyAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->getParams()) {

            $emailId = $this->getRequest()->getParam('data');
            $result = $this->getDataByEmail($emailId);
            if (!empty($result)) {
                $objAdmin = new Travel_Model_TblAdminUser();
                $this->view->AdminUserList = $objAdmin->getAdminUserList();
                $rmData = $objAdmin->getAgencyRelationshipMgr($result['AgencySysId']);
                $this->view->messages = $this->_helper->flashMessenger->getMessages();
                $objAgency = new Travel_Model_TblAgency();
                $agencyOtherDetails = $objAgency->getAgencyOtherDetails($result['AgencySysId']);
                $certOfTrade = $objAgency->getAgencyDocDataByParentId($result['AgencySysId'], 11);
                $recogGovt = $objAgency->getAgencyDocDataByParentId($result['AgencySysId'], 15);
                //                echo '<pre>';   print_r($agencyOtherDetails); '</pre>'; 
                //                 print_r($recogGovt);
                $this->view->verifyData = $result;
                $this->view->certOfTrade = $certOfTrade;
                $this->view->recogGovt = $recogGovt;
                $this->view->agencyOtherDetails = $agencyOtherDetails;
                $this->view->rmDetails = $rmData;
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
    }

    public function saveMoreAboutCompanyAction() {
        $this->_helper->layout->disableLayout();
        $objAgency = new Travel_Model_TblAgency();


        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //            echo '<pre>';
            //            print_r($getData);
            //            print_r($_FILES); die;
            if (trim($getData['aboutCompany']) == '') {
                $this->_helper->flashMessenger->addMessage("Please fill all mandatory fields.");
                $params = array('data' => base64_encode($getData['regEmail']), 'param' => 4);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }


            // validate extension of file
            $invalidCOT = '';
            if (!empty($_FILES['certOfTradeFile']['name'])) {
                foreach ($_FILES['certOfTradeFile']['name'] as $key => $fileName) {
                    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                    if (!in_array($ext, unserialize(FILE_EXTENSIONS)) && $fileName != '') {
                        $invalidCOT = 1;
                    }
                }
            }

            // validate extension of file
            $invalidRFG = '';
            if (!empty($_FILES['recognitionFromGovtFile']['name'])) {
                foreach ($_FILES['recognitionFromGovtFile']['name'] as $key => $fileName) {
                    echo $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                    if (!in_array($ext, unserialize(FILE_EXTENSIONS)) && $fileName != '') {
                        $invalidRFG = 1;
                    }
                }
            }

            if ($invalidCOT == 1 || $invalidRFG == 1) {
                $this->_helper->flashMessenger->addMessage("Please upload valid extension. Ex gif,jpg,png,pdf.");
                $params = array('data' => base64_encode($getData['regEmail']), 'param' => 4);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }


            $result = $this->getDataByEmail($getData['regEmail']);
            //print_r($_FILES);

//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');

            $agencyAboutData = array(
                'AgencySysId' => $result['AgencySysId'],
                'AboutUs' => $getData['aboutCompany'],
                'FacebookURL' => $getData['FacebookURL'],
                'GoogleURL' => $getData['GoogleURL'],
                'YouTubeURL' => $getData['YouTubeURL'],
                'TwitterURL' => $getData['TwitterURL'],
                'InstagramURL' => $getData['InstagramURL'],
                'PintrestURL' => $getData['PintrestURL'],
                'FacebookFeedbackPostURL' => $getData['FacebookFeedbackPostURL'],
                'GoogleFeedbackPostURL' => $getData['GoogleFeedbackPostURL'],
                'CreateDate' => $currentDate
            );

            $objAgency->addAgencyAboutData($agencyAboutData);

            //array to update agency data
            $agencyData = array(
                'ActivationDate' => $currentDate,
                'IsActive' => 1,
            );
            $objAgency->updateAgencyData($agencyData, $result['AgencySysId']);
            $this->addPermissionControlAction($result['AgencySysId']);
            $pathToUploadFile = USER_FILE_UPLOAD_PATH . 'agency/' . $result['AgencySysId'] . "/";
            //            $pathToUploadFile = "Media/" . strtolower($result['Title']) . "/";
            //            $this->mkdir_r($pathToUploadFile);
            if (!file_exists($pathToUploadFile)) {
                mkdir($pathToUploadFile, 0755, true);
            }

            if (!empty($_FILES['certOfTradeFile']['name'])) {
                //Loop through each file
                for ($i = 0; $i < count($_FILES['certOfTradeFile']['name']); $i++) {
                    //Get the temp file path
                    $tmpFilePath = $_FILES['certOfTradeFile']['tmp_name'][$i];
                    //Make sure we have a filepath
                    if ($tmpFilePath != "") {

                        //save the filename
                        $shortname = $_FILES['certOfTradeFile']['name'][$i];

                        //save the url and the file
                        $ext = @substr($shortname, strrpos($shortname, '.'));
                        $newNAme = "certOfTrade_" . $getData['certOfTrade'][$i] . '_' . time() . $ext;
                        $filePath = $pathToUploadFile . $newNAme;

                        //Upload the file into the temp dir
                        if (move_uploaded_file($tmpFilePath, $filePath)) {
//                            $date = new Zend_Date();
                            $currentDate = date('Y-m-d H:i:s');
                            $certOfTradeArr = explode('_', $getData['certOfTrade'][$i]);

                            $agencyUploadData = array(
                                'AgencySysId' => $result['AgencySysId'],
                                'fileName' => $newNAme,
                                'ParentDocSysId' => $certOfTradeArr[1],
                                'originalFileName' => $certOfTradeArr[2],
                                'DocType' => $certOfTradeArr[0],
                                'Title' => 'Certification Of Trade',
                                'CreateDate' => $currentDate
                            );

                            $objAgency->addAgencyFile($agencyUploadData);
                        }
                    }
                }
            }

            if (!empty($_FILES['recognitionFromGovtFile']['name'])) {
                //Loop through each file
                for ($i = 0; $i < count($_FILES['recognitionFromGovtFile']['name']); $i++) {
                    //Get the temp file path
                    $tmpFilePath = $_FILES['recognitionFromGovtFile']['tmp_name'][$i];
                    //Make sure we have a filepath
                    if ($tmpFilePath != "") {

                        //save the filename
                        $shortname = $_FILES['recognitionFromGovtFile']['name'][$i];

                        //save the url and the file
                        $ext = @substr($shortname, strrpos($shortname, '.'));
                        $newNAme = "recognitionFromGovt_" . $getData['recognitionFromGovt'][$i] . '_' . time() . $ext;
                        $filePath = $pathToUploadFile . $newNAme;

                        //Upload the file into the temp dir
                        if (move_uploaded_file($tmpFilePath, $filePath)) {
//                            $date = new Zend_Date();
                            $currentDate = date('Y-m-d H:i:s');
                            $recognitionFromGovtArr = explode('_', $getData['recognitionFromGovt'][$i]);
                            $agencyUploadData = array(
                                'AgencySysId' => $result['AgencySysId'],
                                'fileName' => $newNAme,
                                'originalFileName' => $recognitionFromGovtArr[2],
                                'ParentDocSysId' => $recognitionFromGovtArr[1],
                                'DocType' => $recognitionFromGovtArr[0],
                                'Title' => 'Recognition from Government',
                                'CreateDate' => $currentDate
                            );
                            $objAgency->addAgencyFile($agencyUploadData);
                        }
                    }
                }
            }



            //Mail code to send agencry creation notification to admin.  
            //            $emailId = $getData['regEmail'];
            //             $agencyName = $result['Title'];
            //                    $message = "Dear Admin, <br><br>";
            //                    $message .= "New agency is registered with GTX:<br><br>";
            //                    $message .= "Agency Name: $agencyName <br>";
            //                    $message .= "Email Id: $emailId <br>";
            //                    $message .= "Thanks,<br>";
            //                    $message .= $this->fromName;
            //
            //                    #Set subject
            //                    $subject = 'Notification for new agency registration with ' . SITE_NAME;
            //
            //
            //                        $mailConfig = array(
            //                            'ssl' => 'ssl',
            //                            'auth' => 'login',
            //                            'port' => $this->smtpPort,
            //                            'username' => $this->smtpUserName,
            //                            'password' => $this->smtpPassword
            //                        );
            //
            //                        $transport = new Zend_Mail_Transport_Smtp($this->smtpHost, $mailConfig);
            //
            //                        $mail = new Zend_Mail("iso-8859-1");
            //                        $mail->addTo('pooja@catpl.co.in')
            //                                ->addBcc('pooja@catpl.co.in') // should be removed after testing
            //                                ->setSubject($subject)
            //                                ->setBodyHtml($message)
            //                                ->setFrom($this->fromEmail, $this->fromName);
            //
            //                        try {
            //                            $mail->send($transport);
            //                        } catch (Exception $err) {
            //                            print_r($err, true);
            //                        }
            //$this->redirect('register/verify-contact-email/param/4');
            // $this->_helper->redirector('verify-contact-email/');
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 5);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);


            //designation  is skip for now
        }
        exit;
    }

    private function getDataByEmail($emailId) {
        $objAgency = new Travel_Model_TblAgency();
        $result = $objAgency->getDataByEmail($emailId);
        return $result;
    }

    public function loginAction() {
        
    }

    public function getStateAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $contId = $this->getRequest()->getParam('CountryID');
            $objLocation = new Travel_Model_TblLocation();
            $stateListArray = $objLocation->getStateList($contId);
            $select = '<option value="">Select State</option>';
            if ($contId != '') {
                foreach ($stateListArray as $stateData) { //print_r($countryData);
                    $select .= "<option value='" . $stateData['StateId'] . "'>" . ucfirst($stateData['Title']) . "</option>";
                }
            }

            echo $select;
        }
    }

    public function getCityByStateAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $StateId = $this->getRequest()->getParam('StateId');
            $CountryID = $this->getRequest()->getParam('CountryID');
            $objLocation = new Travel_Model_TblLocation();
            $State = $objLocation->getStateName($StateId); // state id is 0 in city table so name requited
            $cityListArray = $objLocation->getCityList($CountryID);
            //print_r($cityListArray); die;
            $select = '<option value="">Select City</option>';

            foreach ($cityListArray as $cityData) { //print_r($countryData);
                $select .= "<option value='" . $cityData['CityId'] . "'>" . ucfirst($cityData['Title']) . "</option>";
            }

            echo $select;
        }
    }

    public function getCityListAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $CountryID = $this->getRequest()->getParam('CountryID');
            $objLocation = new Travel_Model_TblLocation();
            $cityListArray = $objLocation->getCityList($CountryID);

            $select = '<option value="">Select City</option>';

            foreach ($cityListArray as $cityData) { //print_r($countryData);
                $select .= "<option value='" . $cityData['CityId'] . "'>" . ucfirst($cityData['Title']) . "</option>";
            }

            echo $select;
        }
    }

    public function testAction() {
        echo "<pre>";
        print_r(stream_get_transports());
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $message = "Test";
        $message .= "DCB Bank Team";
        $subject = "Check Mail Religare Home Loan";
        //Start code fot smtp mail details                         
        $config_details = array(
            'ssl' => 'tls',
            'auth' => 'plain',
            'port' => 587,
            'username' => "prashant.gupta11687@gmail.com",
            'password' => "banpwd123"
        );

        try {
            $transport = new Zend_Mail_Transport_Smtp("smtp.gmail.com", $config_details);
            $mail = new Zend_Mail("utf-8");
            $mail->setBodyHtml($message);
            $mail->setFrom("prashant.gupta11687@gmail.com", "Religare Home Loan");
            $mail->addTo("prashant@catpl.co.in", "Prashant Kumar Gupta");
            $mail->setSubject($subject);
            // echo "sdasdasdas"; 


            try {
                $mail->send($transport);
            } catch (Exception $e) {
                echo $e->getMessage();
            }
            exit;


            if (!$mail->send($transport)) {
                echo 'Message could not be sent.';
                echo 'Mailer Error: ' . $mail->ErrorInfo;
            } else {
                echo 'Message has been sent';
            }
            echo "File Completed";
            exit;
        } catch (Exception $ex) {
            echo "<pre>";
            print_r($ex, true);
            exit;
        }
    }

    public function uploadAction() {
        $this->_helper->layout->disableLayout();
        session_start();

        echo "You entered " . htmlentities($_POST['answer']) . " which is ";

        if ($_SESSION['answer'] == $_POST['answer'])
            echo 'correct';
        else
            echo 'wrong. We expected ' . $_SESSION['answer'];
    }

    public function autosuggestCountryAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $arrResponse = array();
        $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
        if ($term) {

            $countryId = $this->getRequest()->getParam("countryId");
            $objLocation = new Travel_Model_TblLocation();
            $arrResponse = $objLocation->getAutoSuggestCountry($term, $countryId);
        }
        echo json_encode($arrResponse);
        exit;
    }

    public function autosuggestCityAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $arrResponse = array();
        if ($this->getRequest()->getParam("term")) {
            $term = $this->getRequest()->getParam("term");
            $countryId = $this->getRequest()->getParam("countryId");
            $objLocation = new Travel_Model_TblLocation();
            $arrResponse = $objLocation->getAutoSuggestCityForInvoice($term, $countryId);
        }
        echo json_encode($arrResponse);
        exit;
    }

    public function mkdir_r($dirName, $rights = 0755) {
        $dirs = explode('/', $dirName);
        $dir = '';
        foreach ($dirs as $part) {
            $dir .= $part . '/';
            if (!is_dir($dir) && strlen($dir) > 0)
                mkdir($dir, $rights);
        }
    }

    public function updatePersonalDetailsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //            echo '<pre>';print_r($getData);      

            $objStaff = new Travel_Model_TblAgencyStaff();
            $objAgency = new Travel_Model_TblAgency();
            $ownerUserSysId = base64_decode($getData['primaryContactId']);
            $ownerResult = $objStaff->getUserDetailsById($ownerUserSysId);

            $sAdminUserSysId = base64_decode(@$getData['operationalContactId']);
            $sAdminResult = $objStaff->getUserDetailsById($sAdminUserSysId);
            //            echo $ownerUserSysId. '  '.$sAdminUserSysId;
            //            print_r($ownerResult);
            //            print_r($sAdminResult);
            //            die;
            $firstName = $getData['1_firstName'];
            $lastName = $getData['1_lastName'];
            $designation = $getData['1_designation'];
            $contactNo = $getData['1_contactNo'];
            $mobileNo = $getData['1_mobileNo'];
            $countrycode = $getData['1_cCode'];
            $countrycode2 = $getData['1_mCode'];
            $emailId = $getData['1_emailId'];

            $senderEmailId = $getData['senderEmailId'];
            $AgencyId = $getData['AgencyId'];

            $agencyUserRoleArr = unserialize(AGENCY_USER_ROLE);


//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            $agencyPrimaryUserData = array(
                'FirstName' => $firstName,
                'LastName' => $lastName,
                'Designation' => $designation,
                'ContactNo1' => $contactNo,
                'ContactNo2' => $mobileNo,
                'countrycode' => $countrycode,
                'countrycode2' => $countrycode2,
                //                'EmailId' => $emailId,
                //                'EmailIdForCustomer' => $senderEmailId, // to be updated in TblAgency
                //                'userRole' => $userRoleId,
                'UpdateDate' => $currentDate
            );
            //update agency user in agency user table 
            $objStaff->editUserDetails($agencyPrimaryUserData, $ownerUserSysId);
            $editAgencyDetails['EmailIdForCustomer'] = $senderEmailId;
            $objAgency->editAgencyDetails($editAgencyDetails, $AgencyId);
            // echo $ownerUserSysId.''.$AgencyId;
            //echo '<pre>';print_r($agencyPrimaryUserData); die('edt');

            $isSameAsPrimaryContact = @$getData['isSameAsPrimaryContact'];

            /* Upload Photo ID Proof */
            if (!empty(@$_FILES['photoIdProofFile'])) {
                $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $AgencyId . "/";

                $tmpFilePath = $_FILES['photoIdProofFile']['tmp_name'];
                //Make sure we have a filepath
                $fileName = $_FILES['photoIdProofFile']['name'];

                $newFileName = 'photo_id_' . rand(0, 99);

                $newFileName = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);
                if (!empty($newFileName)) {
                    /* Insert into database */
                    $FileType = explode('_', $getData['photoIdProof']);
                    $agencyUploadData = array(
                        'UserSysId' => $ownerUserSysId,
                        'fileName' => $newFileName,
                        'docType' => $FileType[0],
                        'originalFileName' => $FileType[1],
                        'Title' => $FileType[1],
                        'CreateDate' => $currentDate
                    );
                    $objAgency->addAgencyUserDocument($agencyUploadData);
                    //echo "Success";
                }
            }

            // insert second user 
            if ($isSameAsPrimaryContact == 'No') {

                $firstName2 = $getData['2_firstName'];
                $lastName2 = $getData['2_lastName'];
                $designation2 = $getData['2_designation'];
                $contactNo2 = $getData['2_contactNo'];
                $mobileNo2 = $getData['2_mobileNo'];
                $countrycode = $getData['2_cCode'];
                $emailId2 = $getData['2_emailId'];

                if (empty($sAdminUserSysId)) {
                    //add role     
                    $agencyOperationalUserRoleData = array(
                        'AgencySysId' => $AgencyId,
                        'RoleTitle' => $agencyUserRoleArr[1]
                    );
                    $objAgency = new Travel_Model_TblAgency();
                    $userRoleId2 = $objAgency->addUserRole($agencyOperationalUserRoleData);

                    $RandStrPass = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->generateRandomString(5);
                    $agencyOperationalUserData = array(
                        'AgencySysId' => $AgencyId,
                        'FirstName' => $firstName2,
                        'LastName' => $lastName2,
                        'Designation' => $designation2,
                        'ContNo' => $contactNo2,
                        'mobileNo' => $mobileNo2,
                        'countrycode' => $countrycode,
                        'EmailId' => $emailId2,
                        'userRole' => $userRoleId2,
                        'Password' => md5($RandStrPass),
                        'UserAccessLevelType' => 1,
                        'RandStr' => $RandStrPass,
                        'CreateDate' => $currentDate
                    );
                    //echo '<pre>';print_r($agencyOperationalUserData); die('edt');
                    $res = $objAgency->addAgencyUser($agencyOperationalUserData, $agencyUserRoleArr[1]);
                } else {
                    $agencysAdminUserData = array(
                        'FirstName' => $firstName2,
                        'LastName' => $lastName2,
                        'Designation' => $designation2,
                        'ContactNo1' => $contactNo2,
                        'ContactNo2' => $mobileNo2,
                        'countrycode' => $countrycode,
                        'EmailId' => $emailId2,
                        'UpdateDate' => $currentDate
                    );

                    //update agency user in agency user table 
                    $objStaff->editUserDetails($agencysAdminUserData, $sAdminUserSysId);
                }
            }
            //exit;
            //die('ed');
            $this->_helper->flashMessenger->addMessage("Personal Details updated successfully.");
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 3);
            //            $params = array('id' => $AgencyId, 'param' => 3);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
        }
    }

    public function updateCompanyDetailsAction() { //error_reporting(E_ALL);
        $this->_helper->layout->disableLayout();
        $objAgency = new Travel_Model_TblAgency();

        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            // echo "<pre>"; print_r($getData); die(" bank data");
            $getAgencyData = $this->getDataByEmail($getData['regEmail']);

//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            $agencyDocTypeKeys = array_keys(unserialize(AGENCY_DOC_TYPE));
            $agencyDocTypeArray = unserialize(AGENCY_DOC_TYPE);
            //         echo '<pre>';   print_r($agencyDocTypeKeys);
            //            print_r($agencyDocTypeArray); die;
            $regCountryId = $getData['registered_country_id'];
            $regCityId = $getData['registered_city_id'];
            $objLocation = new Travel_Model_TblLocation();
            // save country to data base if not exists and get country id
            if (trim($regCountryId) == '') {
                $regCountryId = $objLocation->addCountry($getData['selectCountry']);
            }
            // save City to data base if not exists and get city id
            if (trim($regCityId) == '') {
                $regCityId = $objLocation->addCity($getData['selectCity'], $regCountryId, $getData['selectCountry'], $currentDate);
            }

            // create masking for nature of business
            $natureOfBusinessArray = unserialize(AGENCY_NATURE_OF_BUSINESS);

            $natureOfBusinessMasking = 1;
            foreach ($natureOfBusinessArray as $key => $value) {
                $natureOfBusinessMasking .= (in_array($key, $getData['natureOfBusiness'])) ? 1 : 0;
            }

            //array to update agency data
            $agencyData = array(
                'Title' => $getData['companyName'] ? $getData['companyName'] : '',
                //                'FirmType' => $getData['companyType'] ? $getData['companyType'] : 0,
                'ServiceTaxNo' => $getData['companyServiceTaxNo'] ? $getData['companyServiceTaxNo'] : '',
                'BusinessTypeMask' => $natureOfBusinessMasking,
                'DisplayName' => $getData['compDisplayName'] ? $getData['compDisplayName'] : '',
                'Url' => $getData['websiteUrl'] ? $getData['websiteUrl'] : '',
                'CountrySysId' => (int) $regCountryId,
                'CitySysId' => (int) $regCityId,
            );

            $objAgency->updateAgencyData($agencyData, $getAgencyData['AgencySysId']);

            //array to update registered data

            if ($getData['address'] != '' && $getData['address2'] != '') {
                $regAddress = $getData['address'] . '___' . $getData['address2'];
            } else if ($getData['address'] != '') {
                $regAddress = $getData['address'];
            }


            $agencyRegAddressData = array(
                'Address' => $regAddress,
                'CountrySysId' => $regCountryId,
                //    'selectState' => $getData['selectState2'],
                'CitySysId' => $regCityId,
                'Pincode' => $getData['pinCode'],
                //   'copyAddressProofFile' => $filesArray['copyAddressProofFile2'],
                'UpdateDate' => $currentDate
            );

            $AddressSeqReg = $getData['registeredAddress'];
            $objAgency->updateAgencyAdressDetails($agencyRegAddressData, $AddressSeqReg);

            if ($getData['isSameAsRegisteredAddress'] == 'No') {
                if ($getData['corpAddress'] != '' && $getData['corpAddress2'] != '') {
                    $corpAddress = $getData['corpAddress'] . '___' . $getData['corpAddress2'];
                } else if ($getData['corpAddress'] != '') {
                    $corpAddress = $getData['corpAddress'];
                }

                $corpCountryId = $getData['corporate_country_id'];
                $corpCityId = $getData['corporate_city_id'];
                $objLocation = new Travel_Model_TblLocation();
                // save country to data base if not exists and get country id
                if (trim(@$corpCountryId) == '') {
                    $corpCountryId = $objLocation->addCountry($getData['selectCountry2']);
                }
                // save City to data base if not exists and get city id
                if (trim(@$corpCityId) == '') {
                    $corpCityId = $objLocation->addCity($getData['selectCity2'], $corpCountryId, $getData['selectCountry2'], $currentDate);
                }

                $AddressSeqCorp = $getData['corporateAddress'];

                if (empty($AddressSeqCorp)) {

                    $fileName = $_FILES['copyAddressProofFile2']['name'];
                    //save the url and the file
                    $ext = @substr($fileName, strrpos($fileName, '.'));
                    $res = explode('File', $key);
                    $newFileName = $res[0] . '_' . time() . $ext;
                    $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $AgencyId . "/";

                    $tmpFilePath = $_FILES['copyAddressProofFile2']['tmp_name'];
                    //Make sure we have a filepath
                    $newFileNameR = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);

                    $agencyCorpAddressData = array(
                        'AgencySysId' => $getAgencyData['AgencySysId'],
                        'AddressType' => 2, //corporate address
                        'address' => $corpAddress,
                        'selectCountry' => $corpCountryId,
                        //                    'selectState' => $getData['selectState2'],
                        'selectCity' => $corpCityId,
                        'pinCode' => $getData['pinCode2'],
                        'copyAddressProofFile' => $newFileNameR,
                        'CreateDate' => $currentDate
                    );
                    $objAgency->addAgencyAddressData($agencyCorpAddressData);
                } else {
                    $agencyCorpAddressData = array(
                        'Address' => $corpAddress,
                        'CountrySysId' => $corpCountryId,
                        //                    'selectState' => $getData['selectState2'],
                        'CitySysId' => $corpCityId,
                        'Pincode' => $getData['pinCode2'],
                        //                    'copyAddressProofFile' => $filesArray['copyAddressProofFile2'],
                        'UpdateDate' => $currentDate
                    );
                    $objAgency->updateAgencyAdressDetails($agencyCorpAddressData, $AddressSeqCorp);
                }
            }

            //bank detail update//
            $bankCountryId = $getData['bank_country_id'];
            $bankCityId = $getData['bank_city_id'];


            $agencyBankDetailsData = array(
                'AccountName' => $getData['accountHolderName'],
                'AccountNo' => $getData['accountNumber'],
                'IFSCCode' => $getData['ifscCode'],
                // 'AccountType' => $getData['accountType'],
                'BankName' => $getData['BankName'],
                'Branch' => $getData['branchName'],
                'CountrySysId' => $bankCountryId,
                'CitySysId' => $bankCityId,
            );



            $pathToUploadFile = USER_FILE_UPLOAD_PATH . 'agency/' . $getData['AgencyId'] . "/";
            if (!file_exists($pathToUploadFile)) {
                mkdir($pathToUploadFile, 0755, true);
            }
            $tmpFilePath = $_FILES['companyLogo']['tmp_name'];
            if ($tmpFilePath != "") {
                $shortname = $_FILES['companyLogo']['name'];
                $ext = @substr($shortname, strrpos($shortname, '.'));
                $newNAme = 'companyLogo_' . time() . $ext;
                $filePath = $pathToUploadFile . $newNAme;
                $fileUpload = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImage($tmpFilePath, $pathToUploadFile, $_FILES['companyLogo']['name'], $newNAme);
                if ($fileUpload) {
                    $agencyData['Logo'] = ($newNAme) ? $newNAme : '';
                }
            }

            $tmpFilePathInvoice = $_FILES['InvoiceSignature']['tmp_name'];
            if ($tmpFilePathInvoice != "") {
                $shortnameInvoice = $_FILES['InvoiceSignature']['name'];
                $ext = @substr($shortnameInvoice, strrpos($shortnameInvoice, '.'));
                $newNAmeIn = 'InvoiceSignature_' . time() . $ext;
                $filePath = $pathToUploadFile . $newNAmeIn;
                $fileUpload = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImageS($tmpFilePathInvoice, $pathToUploadFile, $_FILES['InvoiceSignature']['name'], $newNAmeIn);
                if ($fileUpload) {
                    $agencyData['InvoiceSignature'] = ($newNAmeIn) ? $newNAmeIn : '';
                }
            }



            /* Added by mangal for signature image  27-05-2020 Start */
            $pathToUploadFileAgencyPhoto = USER_FILE_UPLOAD_PATH . 'agency/' . $getData['AgencyId'] . "/photo/";
            if (!file_exists($pathToUploadFileAgencyPhoto)) {
                mkdir($pathToUploadFileAgencyPhoto, 0755, true);
            }
            $tmpFilePathAgencyPhoto = ($_FILES['AgencyPhoto']['tmp_name']) ? $_FILES['AgencyPhoto']['tmp_name'] : '';
            if ($tmpFilePathAgencyPhoto != "") {
                $shortnameAgencyPhoto = $_FILES['AgencyPhoto']['name'];
                $extAgencyPhoto = @substr($shortnameAgencyPhoto, strrpos($shortnameAgencyPhoto, '.'));
                $newNAmeAgencyPhoto = 'AgencyPhoto_' . $getAgencyData['AgencySysId'] . $extAgencyPhoto;
                $filePathAgencyPhoto = $pathToUploadFileAgencyPhoto . $newNAmeAgencyPhoto;
                if ($extAgencyPhoto == '.jpg' || $extAgencyPhoto == '.png' || strtolower($extAgencyPhoto) == '.jpeg') {
                    //echo $newNAmeAgencyPhoto.'- ',$pathToUploadFileAgencyPhoto;die;
                    //$fileUploadAgencyPhoto = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImage($tmpFilePathAgencyPhoto, $pathToUploadFileAgencyPhoto, $_FILES['AgencyPhoto']['name'], $newNAmeAgencyPhoto);
                    if (move_uploaded_file($tmpFilePathAgencyPhoto, $pathToUploadFileAgencyPhoto . "/" . $newNAmeAgencyPhoto)) {
                        if ($newNAmeAgencyPhoto) {
                            $agencyData['AgencyPhoto'] = ($newNAmeAgencyPhoto) ? $newNAmeAgencyPhoto : '';
                        }
                    }
                    //echo $fileUploadAgencyPhoto;die;
                }
            }
            // echo "<pre>";print_r($agencyData);die;
            /* Added by mangal for signature image  27-05-2020 End */
            $objAgency->updateAgencyData($agencyData, $getAgencyData['AgencySysId']);


            $staffSignData = array();
//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            $staffSignData['UpdateDate'] = $currentDate;
            $staffSignData['SecondaryEmail'] = (isset($getData['SecondaryEmail']) && !empty($getData['SecondaryEmail'])) ? trim($getData['SecondaryEmail']) : '';
            $staffSignData['ContactNo2'] = (isset($getData['ContactNo2']) && !empty($getData['ContactNo2'])) ? trim($getData['ContactNo2']) : '';
            $staffSignData['countrycode2'] = (isset($getData['countrycode2']) && !empty($getData['countrycode2'])) ? trim($getData['countrycode2']) : '';
            
            if (isset($getData['signature']) && !empty($getData['signature'])) {
                $getData['signature'] = $this->createImageFromCkeditor($getData['signature'], 'quick');
            }
            $staffSignData['signature'] = !empty($getData['signature']) ? $this->_HtmlPurifier->filter($getData['signature']) : '';
            if ((int) $regCountryId > 0) {
                $staffSignData['CountrySysId'] = $regCountryId;
            }
            if ((int) $regCityId > 0) {
                $staffSignData['CitySysId'] = $regCityId;
            }
            $objStaff = new Travel_Model_TblAgencyStaff();
            $userSysId = $getData['UserId'];
            $objStaff->editUserDetails($staffSignData, $userSysId); //update Agency User
            $objAgency->updateAgencyBankDetails($agencyBankDetailsData, $getData['BankId']);  //bank detail update

            $this->_helper->flashMessenger->addMessage("Company Details updated successfully.");
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 4);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
        }
        exit;
    }

    public function updateCompanyDetailsAction_Bak_B4_editdisable_25jan2017() {
        $this->_helper->layout->disableLayout();
        $objAgency = new Travel_Model_TblAgency();
        //        echo '<pre>'; print_r($this->getRequest()->isPost()); die;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            $getAgencyData = $this->getDataByEmail($getData['regEmail']);



//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');

            //             Array ( [5] => Certificate Of Incorporation [6] => Shop & Establishment Certificate [7] => Owner/Director's PAN Number [8] => Partnership Deed [9] => Company PAN Card Number ) 
            //            $companyTypeArray = array_keys(unserialize(AGENCY_COMPANY_TYPE));
            $agencyDocTypeKeys = array_keys(unserialize(AGENCY_DOC_TYPE));
            $agencyDocTypeArray = unserialize(AGENCY_DOC_TYPE);
            //         echo '<pre>';   print_r($agencyDocTypeKeys);
            //            print_r($agencyDocTypeArray); die;

            $regCountryId = $getData['registered_country_id'];
            $regCityId = $getData['registered_city_id'];

            $objLocation = new Travel_Model_TblLocation();
            // save country to data base if not exists and get country id
            if (trim($regCountryId) == '') {
                $regCountryId = $objLocation->addCountry($getData['selectCountry']);
            }
            // save City to data base if not exists and get city id
            if (trim($regCityId) == '') {
                $regCityId = $objLocation->addCity($getData['selectCity'], $regCountryId, $getData['selectCountry'], $currentDate);
            }

            // create masking for nature of business
            $natureOfBusinessArray = unserialize(AGENCY_NATURE_OF_BUSINESS);

            $natureOfBusinessMasking = 1;
            foreach ($natureOfBusinessArray as $key => $value) {
                $natureOfBusinessMasking .= (in_array($key, $getData['natureOfBusiness'])) ? 1 : 0;
            }

            //array to update agency data
            $agencyData = array(
                'Title' => $getData['companyName'] ? $getData['companyName'] : '',
                //                'FirmType' => $getData['companyType'] ? $getData['companyType'] : 0,
                'ServiceTaxNo' => $getData['companyServiceTaxNo'] ? $getData['companyServiceTaxNo'] : '',
                'BusinessTypeMask' => $natureOfBusinessMasking,
                'DisplayName' => $getData['compDisplayName'] ? $getData['compDisplayName'] : '',
                'Url' => $getData['websiteUrl'] ? $getData['websiteUrl'] : '',
            );
            //            $companyTypeArray = array_keys(unserialize(AGENCY_COMPANY_TYPE));
            //            if ($getData['companyType'] == $companyTypeArray[1]) {
            //                $agencyData['PanCardNo'] = $getData['sole_ownerPanNo'] ? $getData['sole_ownerPanNo'] : '';
            //            } else if ($getData['companyType'] == $companyTypeArray[2]) {
            //                $agencyData['PanCardNo'] = $getData['firm_compPanNo'] ? $getData['firm_compPanNo'] : '';
            //            } else {
            //                $agencyData['CIN'] = $getData['pvtltd_CinNO'] ? $getData['pvtltd_CinNO'] : '';
            //                $agencyData['PanCardNo'] = $getData['pvtltd_compPanNo'] ? $getData['pvtltd_compPanNo'] : '';
            //            }
            $objAgency->updateAgencyData($agencyData, $getAgencyData['AgencySysId']);


            //array to update registered data

            if ($getData['address'] != '' && $getData['address2'] != '') {
                $regAddress = $getData['address'] . '___' . $getData['address2'];
            } else if ($getData['address'] != '') {
                $regAddress = $getData['address'];
            }


            $agencyRegAddressData = array(
                'Address' => $regAddress,
                'CountrySysId' => $regCountryId,
                //                    'selectState' => $getData['selectState2'],
                'CitySysId' => $regCityId,
                'Pincode' => $getData['pinCode'],
                //                    'copyAddressProofFile' => $filesArray['copyAddressProofFile2'],
                'UpdateDate' => $currentDate
            );

            $AddressSeqReg = $getData['registeredAddress'];
            $objAgency->updateAgencyAdressDetails($agencyRegAddressData, $AddressSeqReg);

            if ($getData['isSameAsRegisteredAddress'] == 'No') {
                if ($getData['corpAddress'] != '' && $getData['corpAddress2'] != '') {
                    $corpAddress = $getData['corpAddress'] . '___' . $getData['corpAddress2'];
                } else if ($getData['corpAddress'] != '') {
                    $corpAddress = $getData['corpAddress'];
                }

                $corpCountryId = $getData['corporate_country_id'];
                $corpCityId = $getData['corporate_city_id'];
                $objLocation = new Travel_Model_TblLocation();
                // save country to data base if not exists and get country id
                if (trim(@$corpCountryId) == '') {
                    $corpCountryId = $objLocation->addCountry($getData['selectCountry2']);
                }
                // save City to data base if not exists and get city id
                if (trim(@$corpCityId) == '') {
                    $corpCityId = $objLocation->addCity($getData['selectCity2'], $corpCountryId, $getData['selectCountry2'], $currentDate);
                }

                $AddressSeqCorp = $getData['corporateAddress'];

                if (empty($AddressSeqCorp)) {

                    $fileName = $_FILES['copyAddressProofFile2']['name'];

                    //save the url and the file
                    $ext = @substr($fileName, strrpos($fileName, '.'));
                    $res = explode('File', $key);
                    $newFileName = $res[0] . '_' . time() . $ext;
                    $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $AgencyId . "/";

                    $tmpFilePath = $_FILES['copyAddressProofFile2']['tmp_name'];
                    //Make sure we have a filepath

                    $newFileNameR = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);

                    $agencyCorpAddressData = array(
                        'AgencySysId' => $getAgencyData['AgencySysId'],
                        'AddressType' => 2, //corporate address
                        'address' => $corpAddress,
                        'selectCountry' => $corpCountryId,
                        //                    'selectState' => $getData['selectState2'],
                        'selectCity' => $corpCityId,
                        'pinCode' => $getData['pinCode2'],
                        'copyAddressProofFile' => $newFileNameR,
                        'CreateDate' => $currentDate
                    );
                    $objAgency->addAgencyAddressData($agencyCorpAddressData);
                } else {
                    $agencyCorpAddressData = array(
                        'Address' => $corpAddress,
                        'CountrySysId' => $corpCountryId,
                        //                    'selectState' => $getData['selectState2'],
                        'CitySysId' => $corpCityId,
                        'Pincode' => $getData['pinCode2'],
                        //                    'copyAddressProofFile' => $filesArray['copyAddressProofFile2'],
                        'UpdateDate' => $currentDate
                    );
                    $objAgency->updateAgencyAdressDetails($agencyCorpAddressData, $AddressSeqCorp);
                }
            }

            $bankCountryId = $getData['bank_country_id'];
            $bankCityId = $getData['bank_city_id'];
            $objLocation = new Travel_Model_TblLocation();
            // save country to data base if not exists and get country id
            if (trim($bankCountryId) == '') {
                $bankCountryId = $objLocation->addCountry($getData['selectCountry3']);
            }
            // save City to data base if not exists and get city id
            if (trim($bankCityId) == '') {
                $bankCityId = $objLocation->addCity($getData['selectCity3'], $bankCountryId, $getData['selectCountry3'], $currentDate);
            }

            $agencyBankDetailsData = array(
                'AccountName' => $getData['accountHolderName'],
                'AccountNo' => $getData['accountNumber'],
                'IFSCCode' => $getData['ifscCode'],
                'AccountType' => $getData['accountType'],
                'BankName' => $getData['BankName'],
                'Branch' => $getData['branchName'],
                'CountrySysId' => $bankCountryId,
                'CitySysId' => $bankCityId,
                'UpdateDate' => $currentDate
            );
            // echo "<pre>"; print_r($agencyBankDetailsData); die();
            $objAgency->updateAgencyBankDetails($agencyBankDetailsData, $getData['BankId']);
            //$this->redirect('register/verify-contact-email/param/4');
            //            $this->_helper->redirector('verify-contact-email');
            $this->_helper->flashMessenger->addMessage("Company Details updated successfully.");
            $params = array('data' => base64_encode($getData['regEmail']), 'param' => 4);
            $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
        }
        exit;
    }

    public function uploadImageAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //          echo '<pre>';  print_r($getData);
            //            print_r($_FILES); die;
            if (count($_FILES) == 0) {
                $response = array('success' => false, 'msg' => 'Please upload image');
                echo json_encode($response);
                exit;
            }
            if ($_FILES['file']['size'] > 1048576 || $_FILES['file']['error'] == 1) {
                $response = array('success' => false, 'msg' => 'File should be less than 1 mb');
                echo json_encode($response);
                exit;
            }

            $fileName = $_FILES['file']['name'];
            $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $getData['AgencyId'] . "/";
            $tmpFilePath = $_FILES['file']['tmp_name'];
            //Make sure we have a filepath
            //            $newFileName = 'photo_id_' . rand(0, 99);
            // validate extension of file
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            if (!in_array($ext, unserialize(IMAGE_EXTENSIONS)) && $fileName != '') {
                $response = array('success' => false, 'msg' => 'Please upload valid extension. Ex gif,jpg,png,jpeg.');
                echo json_encode($response);
                exit;
            }
            $newNAme = 'companyLogo_' . time() . '.' . $ext;
            //            $newFileName = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);
            $newFileName = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->ResizeAndUpoadImage($tmpFilePath, $folder, $fileName, $newNAme);
            if (!empty($newFileName)) {
                $objAgency = new Travel_Model_TblAgency();
                $saveArr['logo'] = $newFileName;
                $objAgency->editAgencyDetails($saveArr, $getData['AgencyId']);
                $response = array('success' => true, 'msg' => 'Logo is uploaded successfully');
                echo json_encode($response);
                exit;
            } else {
                $response = array('success' => true, 'msg' => 'Error: Please try again.');
                echo json_encode($response);
                exit;
            }
        }
    }

    public function sendSendersEmailAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //          echo '<pre>';  print_r($getData); die;
            $objAgency = new Travel_Model_TblAgency();
            $updateData['EmailIdForCustomer'] = $getData['senderEmailId'];
            $updateData['IsEmailIdForCustVarified'] = 0;
            $updateStatus = $objAgency->updateAgencyData($updateData, $getData['AgencyId']);
            //        print_r($updateStatus);
            $roleTitle = unserialize(AGENCY_USER_ROLE);
            $ownerPersonalDetailsArray = $objAgency->getPersonalDetailsByAgency($getData['AgencyId'], $roleTitle[0]);

            $firstName = $getData['1_firstName'];
            $lastName = $getData['1_lastName'];
            $designation = $getData['1_designation'];
            $contactNo = $getData['1_cCode'] . '-' . $getData['1_contactNo'];
            $mobileNo = $getData['1_mCode'] . '-' . $getData['1_mobileNo'];
            $emailId = $getData['1_emailId'];

            $senderEmailId = $getData['senderEmailId'];
            $AgencyId = $getData['AgencyId'];

//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            //            print_r($ownerPersonalDetailsArray);
            if (empty($ownerPersonalDetailsArray)) {
                //add user role 
                $agencyPrimaryUserRoleData = array(
                    'AgencySysId' => $AgencyId,
                    'RoleTitle' => $roleTitle[0],
                    'IsAdmin' => 1,
                    'IsAbleToManageMember' => 1
                );
                $objAgency = new Travel_Model_TblAgency();
                $userRoleId = $objAgency->addUserRole($agencyPrimaryUserRoleData);

                $oRandStrPass = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->generateRandomString(5);
                $agencyPrimaryUserData = array(
                    'AgencySysId' => $AgencyId,
                    'FirstName' => $firstName,
                    'LastName' => $lastName,
                    'Designation' => $designation,
                    'ContNo' => $contactNo,
                    'mobileNo' => $mobileNo,
                    'EmailId' => $emailId,
                    'EmailIdForCustomer' => $senderEmailId, // to be updated in TblAgency
                    'userRole' => $userRoleId,
                    'Password' => md5($oRandStrPass),
                    'UserAccessLevelType' => 1,
                    'RandStr' => 0,
                    'CreateDate' => $currentDate
                );
                $userId = $objAgency->addAgencyUser($agencyPrimaryUserData, $roleTitle[0]);
            } else {
                $updateagencyPrimaryUserData = array(
                    'FirstName' => $firstName,
                    'LastName' => $lastName,
                    'Designation' => $designation,
                    'ContactNo1' => $contactNo,
                    'ContactNo2' => $mobileNo,
                    //                'EmailId' => $emailId,
                    //                'EmailIdForCustomer' => $senderEmailId, // to be updated in TblAgency
                    //                'userRole' => $userRoleId,
                    'UpdateDate' => $currentDate
                );
                //update agency user in agency user table 
                $objStaff = new Travel_Model_TblAgencyStaff();
                $objStaff->editUserDetails($updateagencyPrimaryUserData, $ownerPersonalDetailsArray['UserSysId']);
            }
            /* Upload Photo ID Proof */
            if (!empty($_FILES)) {
                $folder = USER_FILE_UPLOAD_PATH . 'agency/' . $AgencyId . "/";

                $tmpFilePath = $_FILES['photoIdProofFile']['tmp_name'];
                //Make sure we have a filepath
                $fileName = $_FILES['photoIdProofFile']['name'];

                $newFileName = 'photo_id_' . rand(0, 99);

                $newFileName = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->fileUpload($fileName, $newFileName, $tmpFilePath, $folder);
                //add agency user in agency user table and update primary user in agency table

                if (!empty($newFileName)) {
                    /* Insert into database */
                    $FileType = explode('_', $getData['photoIdProof']);
                    $agencyUploadData = array(
                        'UserSysId' => $userId,
                        'fileName' => $newFileName,
                        'docType' => $FileType[0],
                        'originalFileName' => $FileType[1],
                        'Title' => $FileType[1],
                        'CreateDate' => $currentDate
                    );
                    $objAgency->addAgencyUserDocument($agencyUploadData);
                    //echo "Success";
                }
            }
            $emailData = base64_encode(trim($getData['regEmail']));
            $link = base64_encode('bySendersEmail');
            $verify = base64_encode('sendersEmail');

            $url = $this->siteUrl . "register/verify-contact-email/data/$emailData/link/$link/verify/$verify/param/2";

            $params = array('agent_name' => ucfirst($getData['1_firstName']), 'verification_link' => $url);

            #Set subject
            $subject = 'Verify your Sender\'s email id with ' . SITE_NAME;
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/emails/');
            $html->assign($params);
            $bodyText = $html->render('agent_senders_email_verification.phtml');

            $emailData11 = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => $subject, 'to' => array($getData['senderEmailId']), 'bodyHtml' => $bodyText, 'bodyText' => '');
            try {
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => 0,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencyId,
                    "AgentSysId" => $userId,
                    "Title" => '',
                    "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => date('Y-m-d H:i:s')
                );
                $this->mailSentByElastice($emailData11, $arrEmailStatistics);
                echo 1;
                exit;
            } catch (Exception $err) {
                echo 2;
                exit;
            }

            //                        $mailConfig = array(
            //                            'ssl' => 'ssl',
            //                            'auth' => 'login',
            //                            'port' => $this->smtpPort,
            //                            'username' => $this->smtpUserName,
            //                            'password' => $this->smtpPassword
            //                        );
            //
            //                        $transport = new Zend_Mail_Transport_Smtp($this->smtpHost, $mailConfig);
            //
            //                        $mail = new Zend_Mail("iso-8859-1");
            //                        $mail->addTo($getData['senderEmailId'])
            //                                ->addBcc('pooja@catpl.co.in') // should be removed after testing
            //                                ->setSubject($subject)
            //                                ->setBodyHtml($bodyText)
            //                                ->setFrom($this->fromEmail, $this->fromName);
            //
            //                        try {
            //                            $mail->send($transport);
            ////                            echo '<pre>';print_r($mail);
            //                            echo 1; exit;
            //                        } catch (Exception $err) {
            //                            print_r($err, true);
            //                            echo 2; exit;
            //                        }
        }
    }

    public function approveAgencyAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            $objAgency = new Travel_Model_TblAgency();
            $agencyArray = $objAgency->getAgencyDataById($getData['agencyid']);
//            $date = new Zend_Date();
            $currentDate = date('Y-m-d H:i:s');
            if (empty($getData['userId'])) {
                echo 3;
                exit;
            }
            $usersysid = isset($agencyArray['UserSysId']) ? (int) $agencyArray['UserSysId'] : 0;
            $this->addRMAction($getData['assign_rm_id'], $getData['agencyid']);
            $this->addMarkupAction($getData['agencyid']);
            $this->addAgencyLeadAction($getData['agencyid'], $usersysid);
            $this->addAgencyTermAndCondition($getData['agencyid']);
            $this->addAgencyInsuranceCommissionAction($getData['agencyid'], $agencyArray['TrxCurrency']);
            $this->addAgencyInsuranceCommissionAction($getData['agencyid'], $agencyArray['TrxCurrency']);
            $objAgency->setDefaultCampaign($getData['agencyid']);
            $objAgency->setMarketingWallet($getData['agencyid']);
            $objAgency->addDefaultCampainSix($getData['agencyid']);
            $modelAtofollowup = new Finance_Model_Finance();
            $modelAtofollowup->setDefaultTaxSeeting();
            $walletData = $objAgency->getAgencyWalletDetails($getData['agencyid']);
            if (!empty($walletData)) {
                $agencyWalletData = array(
                    'CurrencyType' => $agencyArray['TrxCurrency'],
                    'Title' => $getData['agencyid'] . '_Wallet',
                    'UpdateDate' => $currentDate
                );
                $addAgencyWallet = $objAgency->updateAgencyWallet($agencyWalletData, $walletData['WalletSysId']);
            } else {
                $agencyWalletData = array(
                    'AgencySysId' => $getData['agencyid'],
                    'CurrencyType' => $agencyArray['TrxCurrency'],
                    'Title' => $getData['agencyid'] . '_Wallet',
                    'CreateDate' => $currentDate,
                    'UpdateDate' => $currentDate
                );
                $addAgencyWallet = $objAgency->addAgencyWallet($agencyWalletData);
            }
            if ($addAgencyWallet) {
                $oRandStrPass = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->generateRandomString(5);
                $objStaff = new Travel_Model_TblAgencyStaff();
                $agencyUserDataForDb = array(
                    'Password' => md5($oRandStrPass),
                );
                $objStaff->editUserDetails($agencyUserDataForDb, $getData['userId']);
                $agencyData = array(
                    'ApprovalDate' => $currentDate,
                    'IsApproved' => 1,
                );
                $objAgency->updateAgencyData($agencyData, $getData['agencyid']);
                $userData = $objStaff->getUserDataByUserId($getData['userId']);
                $url = $this->siteUrl . "login";
                $emailId = trim($userData['EmailId']);
                $params = array('agentName' => ucfirst($userData['FirstName']), 'emailId' => $emailId, 'url' => $url, 'password' => $oRandStrPass);
                $subject = 'Login Details for ' . SITE_NAME;
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/emails/');
                $html->assign($params);
                $bodyText = $html->render('agent_login.phtml');
                $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => $subject, 'to' => array($emailId), 'bodyHtml' => $bodyText, 'bodyText' => '');
                try {
                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $arrEmailStatistics = array(
                        "TPSysId" => 0,
                        "TypeSysId" => 1, // 1 For Email 2 For SMS
                        "AgencySysId" => $getData['agencyid'],
                        "AgentSysId" => $getData['userId'],
                        "Title" => '',
                        "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => date('Y-m-d H:i:s')
                    );
                    $returnArray = $this->mailSentByElastice($emailData, $arrEmailStatistics);
                    //echo "<pre>";print_r($returnArray);exit;
                    $this->_helper->flashMessenger->addMessage("Agency is approved successfully.");
                    echo 1;
                    exit;
                } catch (Exception $err) {
                    echo 4;
                    exit;
                }
            } else {
                echo 2;
                exit;
            }
        }
        exit;
    }

    public function addMarkupAction($agencySysId) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        //                echo 'indexMarkupAction'; die;

        $dateTime = date('Y-m-d H:i:s');
        $this->markupMdl = new Markup_Model_Markup();
        $APIBasedBookingsHotelsMPType = array(1, 1, 1, 2);
        $APIBasedBookingsHotelsItemSourceType = array(1, 1, 0, 0);
        $APIBasedBookingsHotelsAccom = array(1, 2, 1, 1);
        $MyBaseCurrency = '';
        $APIBasedBookingsHotelsMarkupType = array(0, 0, 0, 0);
        $APIBasedBookingsHotelsMarkup = array('', '', 0, 0);
        $APIBasedBookingsHotelsDoubleOccupancy = array(0, 0, '', '');
        $APIBasedBookingsHotelsSingleOccupancy = array(0, 0, '', '');
        $APIBasedBookingsHotelsExtraBed = array(0, 0, '', '');
        $APIBasedBookingsHotelsWithoutExtraBed = array(0, 0, '', '');
        $insertData = array();
        for ($i = 0; $i < count($APIBasedBookingsHotelsMPType); $i++) {

            if (isset($APIBasedBookingsHotelsMarkup[$i]) && $APIBasedBookingsHotelsMarkup[$i] != '') {
                $APIBasedBookingsHotelsMarkup[$i] = $APIBasedBookingsHotelsMarkup[$i];
            } else {
                $APIBasedBookingsHotelsMarkup[$i] = 0;
            }
            if (isset($APIBasedBookingsHotelsDoubleOccupancy[$i]) && $APIBasedBookingsHotelsDoubleOccupancy[$i] != '') {
                $APIBasedBookingsHotelsDoubleOccupancy[$i] = $APIBasedBookingsHotelsDoubleOccupancy[$i];
            } else {
                $APIBasedBookingsHotelsDoubleOccupancy[$i] = 0;
            }
            if (isset($APIBasedBookingsHotelsSingleOccupancy[$i]) && $APIBasedBookingsHotelsSingleOccupancy[$i] != '') {
                $APIBasedBookingsHotelsSingleOccupancy[$i] = $APIBasedBookingsHotelsSingleOccupancy[$i];
            } else {
                $APIBasedBookingsHotelsSingleOccupancy[$i] = 0;
            }
            if (isset($APIBasedBookingsHotelsExtraBed[$i]) && $APIBasedBookingsHotelsExtraBed[$i] != '') {
                $APIBasedBookingsHotelsExtraBed[$i] = $APIBasedBookingsHotelsExtraBed[$i];
            } else {
                $APIBasedBookingsHotelsExtraBed[$i] = 0;
            }
            if (isset($APIBasedBookingsHotelsWithoutExtraBed[$i]) && $APIBasedBookingsHotelsWithoutExtraBed[$i] != '') {
                $APIBasedBookingsHotelsWithoutExtraBed[$i] = $APIBasedBookingsHotelsWithoutExtraBed[$i];
            } else {
                $APIBasedBookingsHotelsWithoutExtraBed[$i] = 0;
            }
            $checkHotelDate = $this->markupMdl->getDetailsForHotel("TB_MP_StdMarkup_Accom", $agencySysId, $APIBasedBookingsHotelsAccom[$i], $APIBasedBookingsHotelsItemSourceType[$i], $APIBasedBookingsHotelsMPType[$i]);

            /* Hotel Data Insert */

            $insertData['AgencySysId'] = $agencySysId;
            $insertData['MPType'] = $APIBasedBookingsHotelsMPType[$i];
            $insertData['ItemSourceType'] = $APIBasedBookingsHotelsItemSourceType[$i];
            $insertData['CustGrSysId'] = 0;
            $insertData['AccomType'] = $APIBasedBookingsHotelsAccom[$i];
            $insertData['Currency'] = $MyBaseCurrency;
            $insertData['MarkUpType'] = $APIBasedBookingsHotelsMarkupType[$i];
            $insertData['IsSameForAll'] = 0;
            $insertData['MarkUp'] = $APIBasedBookingsHotelsMarkup[$i];
            $insertData['DOccupMarkUp'] = $APIBasedBookingsHotelsDoubleOccupancy[$i];
            $insertData['SOccupMarkUp'] = $APIBasedBookingsHotelsSingleOccupancy[$i];
            $insertData['ExtraBedMarkUp'] = $APIBasedBookingsHotelsExtraBed[$i];
            $insertData['ExtraWOBedMarkUp'] = $APIBasedBookingsHotelsWithoutExtraBed[$i];
            $insertData['Tax'] = 0;
            $insertData['PerPaxMarkUp'] = 0;
            $insertData['ValidTill'] = $dateTime;
            $insertData['ApproveDate'] = $dateTime;
            $insertData['CreateDate'] = $dateTime;
            $insertData['UpdateDate'] = $dateTime;
            $insertData['IsApproved'] = 1;
            $insertData['IsMarkForDel'] = 0;
            $insertData['IsActive'] = 1;
            if (!empty($checkHotelDate)) {
                $where = array(
                    "AgencySysId=?" => $agencySysId,
                    "AccomType=?" => $APIBasedBookingsHotelsAccom[$i],
                    "ItemSourceType=?" => $APIBasedBookingsHotelsItemSourceType[$i],
                    "MPType=?" => $APIBasedBookingsHotelsMPType[$i]
                );
                $this->markupMdl->updateTable("TB_MP_StdMarkup_Accom", $insertData, $where);
            } else {
                $this->markupMdl->insertTable("TB_MP_StdMarkup_Accom", $insertData);
            }
        }
        /* Flight Data Insert */



        $APIBasedBookingsFlightAir = array(1, 2, 1, 1);
        $APIBasedBookingsFlightMPType = array(1, 1, 1, 2);
        $APIBasedBookingsFlightItemSourceType = array(1, 1, 0, 0);
        $APIBasedBookingsFlightMarkupType = array(1, 1, 0, 0);
        $APIBasedBookingsFlightMyCommission = array('', '', 0, 0);
        $APIBasedBookingsFlightMarkup = array('', '', '', '');
        $APIBasedBookingsFlightMarkupTypeCommssionType = array(2, 2, 0, 0);


        $insertFlightData = array();
        for ($i = 0; $i < count($APIBasedBookingsFlightMPType); $i++) {


            if (isset($APIBasedBookingsFlightMarkup[$i]) && $APIBasedBookingsFlightMarkup[$i] != '') {
                $APIBasedBookingsFlightMarkup[$i] = $APIBasedBookingsFlightMarkup[$i];
            } else {
                $APIBasedBookingsFlightMarkup[$i] = 0;
            }
            if (isset($APIBasedBookingsFlightMyCommission[$i]) && $APIBasedBookingsFlightMyCommission[$i] != '') {
                $APIBasedBookingsFlightMyCommission[$i] = $APIBasedBookingsFlightMyCommission[$i];
            } else {
                $APIBasedBookingsFlightMyCommission[$i] = 0;
            }
            $checkFlightDate = $this->markupMdl->getDetailsForFlight("TB_MP_StdMarkup_Air", $agencySysId, $APIBasedBookingsFlightAir[$i], $APIBasedBookingsFlightItemSourceType[$i], $APIBasedBookingsFlightMPType[$i]);
            $insertFlightData['AgencySysId'] = $agencySysId;
            $insertFlightData['MPType'] = $APIBasedBookingsFlightMPType[$i];
            $insertFlightData['ItemSourceType'] = $APIBasedBookingsFlightItemSourceType[$i];
            $insertFlightData['AirType'] = $APIBasedBookingsFlightAir[$i];
            $insertFlightData['CustGrSysId'] = 0;
            $insertFlightData['Currency'] = $MyBaseCurrency;
            $insertFlightData['MarkUpType'] = $APIBasedBookingsFlightMarkupType[$i];
            $insertFlightData['IsSameForAll'] = 0;
            $insertFlightData['StdMarkUpPer'] = $APIBasedBookingsFlightMarkup[$i];
            $insertFlightData['TaxPer'] = 0;
            $insertFlightData['DiscAtMarkupPer'] = 0;
            $insertFlightData['DiscAtMarkupVal'] = 0;
            $insertFlightData['CommssionType'] = $APIBasedBookingsFlightMarkupTypeCommssionType[$i];
            $insertFlightData['CommssionVal'] = $APIBasedBookingsFlightMyCommission[$i];
            $insertFlightData['DiscountPer'] = 0;
            $insertFlightData['DiscountVal'] = 0;
            $insertFlightData['DiscountMsg'] = 0;
            $insertFlightData['Details'] = 0;
            $insertFlightData['ValidTill'] = $dateTime;
            $insertFlightData['IsServiceChrgIncludeInTax'] = 0;
            $insertFlightData['ApproveDate'] = $dateTime;
            $insertFlightData['IsApproved'] = 1;
            $insertFlightData['CreateDate'] = $dateTime;
            $insertFlightData['UpdateDate'] = $dateTime;
            $insertFlightData['IsMarkForDel'] = 0;
            $insertFlightData['IsActive'] = 1;
            if (!empty($checkFlightDate)) {
                //echo "<pre>";print_r($insertFlightData);exit;
                $whereFlight = array(
                    "AgencySysId=?" => $agencySysId,
                    "AirType=?" => $APIBasedBookingsFlightAir[$i],
                    "ItemSourceType=?" => $APIBasedBookingsFlightItemSourceType[$i],
                    "MPType=?" => $APIBasedBookingsFlightMPType[$i]
                );
                $this->markupMdl->updateTable("TB_MP_StdMarkup_Air", $insertFlightData, $whereFlight);
            } else {
                $this->markupMdl->insertTable("TB_MP_StdMarkup_Air", $insertFlightData);
            }
        }
    }

    public function addAgencyLeadAction($agencySysId, $usersysid) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $objLeadStage = new Travel_Model_TblLeadStage();
        $objLeadAccount = new Travel_Model_CRM_AgencyLeadAccount();
        $isLeadStageDataExists = $objLeadStage->getLeadStage($agencySysId);
        $isLeadAccountExists = $objLeadAccount->getLeadAccount($agencySysId);
        $LeadStageArray = $objLeadStage->getLeadStageSatus();

        if (!empty($isLeadStageDataExists)) {
            $agencyLeadStageDataDb = array(
                'IsActive' => 0,
                'IsMarkForDel' => 1
            );
            $objLeadStage->updateAgencyLeadStage($agencyLeadStageDataDb, $agencySysId);
        }

        if (!empty($isLeadAccountExists)) {
            $agencyLeadAccountDataDb = array(
                'IsActive' => 0,
                'IsMarkForDel' => 1
            );
            $objLeadAccount->updateAgencyLeadAccount($agencyLeadAccountDataDb, $agencySysId);
        }
        $LeadSourceArray = array('Agency', 'Website', 'Facebook', 'Tripsgateway', 'Website B2B', 'Proposal', 'GTX Network', 'GTX Network Web', 'Instagram');
        foreach ($LeadSourceArray as $LeadSource) {
            if (($LeadSource == 'Website') || ($LeadSource == 'Website B2B')) {
                $agencyLeadSourceArray = array(
                    'IsMappedPlanType' => 1,
                    'AgencySysId' => $agencySysId,
                    'Title' => $LeadSource,
                    'IsEnabledCheckBox' => 1
                );
            } else {
                $agencyLeadSourceArray = array(
                    'AgencySysId' => $agencySysId,
                    'Title' => $LeadSource
                );
            }
            $objLeadAccount->addAgencyLeadSource($agencyLeadSourceArray, $usersysid);
        }
        foreach ($LeadStageArray as $LeadStage) {
            $agencyLeadStageArray = array(
                'AgencySysId' => $agencySysId,
                'Title' => $LeadStage['TPStatus']
            );
            $objLeadStage->addAgencyLeadStage($agencyLeadStageArray);
        }
    }

//    public function createAgencyWholeAction(){
//        $model = new Travel_Model_TblLeadStage();
//        $leadSourceArray = $model->checkLeadSource();
//        foreach ($leadSourceArray as $LeadStage) {
//            $agencyLeadStageArray = array(
//                'AgencySysId' => $LeadStage['AgencySysId'],
//                'Title' => 'Instagram'
//            );
//            
//            $AgencyLead  = new Travel_Model_CRM_AgencyLeadAccount();
//            $AgencyLead->addAgencyLeadSource($agencyLeadStageArray);
//        }
//        echo "<pre>";print_r($leadSourceArray);exit;
//    }
    public function addAgencyInsuranceCommissionAction($agencySysId, $TrxCurrency = 0) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $objInsurance = new Travel_Model_TblInsurance();
        $insuranceCompanyMasterListArr = $objInsurance->getInsuranceCompanyList();
        $agencyInsuranceCompanyArr = $objInsurance->getAgencyInsuranceCompany($agencySysId);


        foreach ($insuranceCompanyMasterListArr as $key => $insuranceCompany) {
            $InsuCompSysId = $insuranceCompany['InsuCompSysId'];
            //             echo '<pre>';   print_r($agencyInsuranceCompanyArr);

            if (!empty($agencyInsuranceCompanyArr[$key]['AgentInsuSysId'])) {
                $updateAgencyInsuData['Commision'] = '30';
                $dbArr[$InsuCompSysId] = $objInsurance->updateAgencyInsuranceCompany($updateAgencyInsuData, $agencyInsuranceCompanyArr[$key]['AgentInsuSysId']);
            } else {
                $addAgencyInsuData = array(
                    'AgencySysId' => $agencySysId,
                    'InsuCompSysId' => $InsuCompSysId,
                    'CurrencyId' => $TrxCurrency,
                    'AllowCredit' => 0,
                    'CreditLimit' => 0,
                    'Balance' => 0,
                    'Commision' => '30',
                );
                $dbArr[$InsuCompSysId] = $objInsurance->addAgencyInsuranceCompany($addAgencyInsuData);
            }
        }

        return $dbArr;
    }

    public function addPermissionControlAction($agencySysId) {
        $currentDate = date("Y-m-d H:i");
        $moduleName = unserialize(MODULENAMEINSERT);
        $permissionModel = new Travel_Model_TblPermission();
        if ((int) $agencySysId > 0) {
            $getActiveAgency = $permissionModel->selectActiveAgency($agencySysId);
            foreach ($getActiveAgency as $agencyDetail) {
                $getAgencySysId = $agencyDetail['AgencySysId'];
                $getAgentSysId = $agencyDetail['UserSysId'];
                if (!empty($moduleName)) {
                    foreach ($moduleName as $moduleKey => $moduleValue) {
                        $checkData = $permissionModel->getModuleData($getAgencySysId, $getAgentSysId, trim($moduleKey));
                        if (empty($checkData)) {
                            $insertData = array(
                                "AgencySysId" => $getAgencySysId,
                                "AgentSysId" => $getAgentSysId,
                                "Parent_Id" => 0,
                                "Title" => $moduleValue['Title'],
                                "ModuleName" => $moduleValue['moduleName'],
                                "ControllerName" => $moduleValue['ControllerName'],
                                "ModuleType" => $moduleValue['Type'],
                                "ParentCode" => $moduleValue['Category'],
                                "val" => $moduleKey,
                                "url" => $moduleValue['url'],
                                "UpdateDate" => $currentDate,
                                "CreateDate" => $currentDate,
                                "IsOrder" => $moduleValue['order'],
                                "IsDisplayLeftNev" => $moduleValue['isDisplay'],
                                "IsActive" => 1,
                                "IsMarkForDelete" => 0
                            );
                            if ($moduleValue['isDisplay'] == 0) {
                                $insertData["IsActive"] = 0;
                            }
                            try {
                                $permissionModel->insertData("TB_Agency_UserRole_Permission", $insertData);
                            } catch (Exception $e) {
                                echo $e->getMessage();
                            }
                        }
                    }
                }
            }
        }
    }

    public function addRMAction($adminUserSysId, $agencySysId) {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $objAdmin = new Travel_Model_TblAdminUser();
        $rmData = $objAdmin->getAgencyRelationshipMgr($agencySysId);
        //        echo '<pre>';        print_r($rmData);
//        $date = new Zend_Date();
        $currentDate = date('Y-m-d H:i:s');
        $rmArrayForDb = array(
            'AgencySysId' => $agencySysId,
            'UserSysId' => $adminUserSysId,
            'IsRegisterUser' => 1,
            'UpdateDate' => $currentDate,
            'ActivationDate' => $currentDate,
            'ApprovalDate' => $currentDate,
            'CreateDate' => $currentDate,
            'IsActive' => 1,
            'IsMarkForDelete' => 0,
            'IsApproved' => 1,
            'Salution' => 0,
            'FirstName' => 0,
            'LastName' => 0,
            'Department' => 0,
            'PrimaryMobile' => 0,
            'LandlineNumbers' => 0,
            'OtherContactInfo' => 0,
            'EmailId' => 0,
            'OtherDetails' => 0,
            'Address' => 0,
            'CitySysId' => 0,
            'StateOrZoneSysId' => 0,
            'CountrySysId' => 0,
            'IsVarified' => 0,
        );
        if (count($rmData) >= 1) {
            $RelationshipMgrSysId = $rmData['RelationshipMgrSysId'];
            $where = array('RelationshipMgrSysId = ? ' => $RelationshipMgrSysId);
            $objAdmin->updateData('TB_Agency_RelationshipMgr', $rmArrayForDb, $where);
        } else {
            $objAdmin->insertData('TB_Agency_RelationshipMgr', $rmArrayForDb);
        }
    }

    public function verifyContactDataAction() {
        //set layout
        $this->_helper->layout->setLayout('layout-register');

        if ($this->getRequest()->getParams()) {
            $objAgency = new Travel_Model_TblAgency();
            $emailId = base64_decode($this->getRequest()->getParam('data'));
            $link = base64_decode($this->getRequest()->getParam('link'));
            $otp = $this->getRequest()->getParam('param');
            $result = $this->getDataByEmail($emailId);
            $getData = $this->getRequest()->getPost();
            if (!empty($getData['mobileotp'])) {
//                $date = new Zend_Date();
                $currentDate = date('Y-m-d H:i:s');
                $RandomCode = $getData["mobileotp"];
                $RandomCodeValidTo = $result['RandomCodeValidTo']->format('Y-m-d H:i:s');
                if ($RandomCode === $result['RandomCode']) {
                    if ($RandomCodeValidTo >= $currentDate) {
                        $agencyData = array('IsMobileVerified' => 1);
                        $objAgency->updateAgencyData($agencyData, $result['AgencySysId']);

                        $params = array('data' => base64_encode($result['PrimaryEmail']), 'param' => 2);
                        $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                        exit;
                    } else {
                        $errorMessage = "Oops! Your OTP is expired. Please try again";
                    }
                } else {
                    $errorMessage = "Oops! Your OTP is wrong. Please try again";
                }
                $this->view->errorMessage = $errorMessage;
            }

            if ($link == 'byEmail' && $result['IsActive'] == 1) {
                $params = array('data' => base64_encode($emailId), 'param' => 6);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }
            if ($link == 'byEmail' && $result['IsMobileVerified'] == 1) {
                $params = array('data' => base64_encode($emailId), 'param' => 2);
                $this->_helper->redirector('verify-contact-email', 'register', 'default', $params);
                exit;
            }
            //            echo '<Pre>'; print_r($result); die;
            if (!empty($result)) {

                $this->view->verifyData = $result;
                //Verify email id of Agency's User
                $agencyData = array('IsVarified' => 1);
                $objAgency->updateAgencyData($agencyData, $result['AgencySysId']);

                $this->view->SENDREGISTERSMSCONFIG = $this->SENDREGISTERSMSCONFIG;
                if ($this->SENDREGISTERSMSCONFIG == 1 && $otp != 'otp' && $result['IsMobileVerified'] == 0) {
                    //                echo 'pppp'; exit;
                    $updateData = new Payment_Model_Checkotp();
                    $mobile_no = $result['ContactInfo'];
                    $countrycode = $result['countrycode'];
                    $login_lastfourdigt_mobile_no = substr($mobile_no, -4);
                    $randomString = $updateData->randomString();
                    //$massage = "OTP for GTX mobile verification is $randomString do not share it with anyone. Team HelloGTX";
//                    $massage = "Hi,\nUse $randomString as OTP (One Time Password) to verify your mobile number. Do not share this OTP with anyone for security reason.\nThanks\nTeam HelloGTX\nTRVCRM";
//                    $this->postFields = "";
//                    $this->postFields .= "&method=$this->SMSMETHOD";
//                    $this->postFields .= "&api_key=$this->SMSAPIKEY";
//                    $this->postFields .= "&to=$mobile_no";
//                    $this->postFields .= "&sender=$this->SMSSENDER";
//                    $this->postFields .= "&message=$massage";
//                    $this->postFields .= "&format=$this->SMSFORMAT";
//                    $postURL = $this->SMSURL;
                    //                        if(Catabatic_Helper::getSENDREGISTERSMSCONFIG() == 0) {
                    //                             $resultVal = array("status"=>'OK');
                    //                        } else {
//                    $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
//                    $arrSMSStatistics = array(
//                        "TPSysId" => 0,
//                        "TypeSysId" => 2, // 1 For Email 2 For SMS
//                        "AgencySysId" => 0,
//                        "AgentSysId" => 0,
//                        "Title" => $massage,
//                        "Source" => $arrSMSStatisticsType[0], // 3 For Misc
//                        "Status" => 0,
//                        "RefSysId" => "",
//                        "RefSysStatus" => "",
//                        "CreateDate" => date('Y-m-d H:i:s')
//                    );
//                    $resultVal = $updateData->sendSmsDetails($postURL, $this->postFields, $arrSMSStatistics);
//                    // 
//                    
//                      
                    $mobileNoCountryCode = trim($countrycode) . '' . trim($mobile_no);
                    $model = new Travel_Model_TblWhatsapp();
                    $resultValJson = $model->sendOptWhatsapp($mobileNoCountryCode, $randomString);
                    $resultValArray = json_decode($resultValJson, true);
                    $errorMessage = '';
                    if (!empty($resultValArray)) {
                        if (isset($resultValArray['messages'][0]['message_status']) && $resultValArray['messages'][0]['message_status'] != 'failed') {
                            $currentDate = date('Y-m-d H:i:s');
                            $dateTime = new DateTime($currentDate);
                            $dateTime->modify('+2 minutes');
                            $RandomCodeValidTo = $dateTime->format('Y-m-d H:i:s');
 
                            $updatedArray = array(
                                "RandomCode" => $randomString,
                                "RandomCodeValidFrom" => $currentDate,
                                "RandomCodeValidTo" => $RandomCodeValidTo
                            );
                            try {
                                $where = array('AgencySysId =?' => $result['AgencySysId']);
                                $updateData->updateTable("TB_Agency", $updatedArray, $where);
                                $errorMessage = "One Time Password(OTP) has been sent your on whatsapp mobile no. ******$login_lastfourdigt_mobile_no, Please enter the same OTP here to continue.";
                                //                                    $this->_helper->redirector('index', 'checkotp');
                            } catch (Zend_Exception $e) {
                                $errorMessage = $e->getMessage();
                            }
                        } else {
                            $errorMessage = "Oops! Please try again";
                        }
                    } else {
                        $errorMessage = "Oops! Please try again";
                    }

                    $this->view->errorMessage = $errorMessage;
                }
            } else {
                $this->_helper->redirector('index', 'register', 'default');
            }
        } else {
            $this->_helper->redirector('index', 'register', 'default');
        }
    }

    public function regenerateRegisterOtpAction() {
        $updateData = new Payment_Model_Checkotp();
        $reGenerateOTP = $this->getRequest()->getParam('reGenerateOTP');
        $mobile_no = $this->getRequest()->getParam('mobileNo');
        $AgencyId = $this->getRequest()->getParam('AgencyId');
        $randomString = $updateData->randomString();
        $login_lastfourdigt_mobile_no = substr($mobile_no, -4);
        $model = new Travel_Model_TblWhatsapp();
        $resultValJson = $model->sendOptWhatsapp($mobile_no, $randomString);
        $resultValArray = json_decode($resultValJson, true);
        $errorMessage = '';
        if (!empty($resultValArray)) {
            if (isset($resultValArray['messages'][0]['message_status']) && $resultValArray['messages'][0]['message_status'] != 'failed') {
                
                $currentDate = date('Y-m-d H:i:s');
                $dateTime = new DateTime($currentDate);
                $dateTime->modify('+2 minutes');
                $RandomCodeValidTo = $dateTime->format('Y-m-d H:i:s');
 
                $updatedArray = array(
                    "RandomCode" => $randomString,
                    "RandomCodeValidFrom" => $currentDate,
                    "RandomCodeValidTo" => $RandomCodeValidTo
                );
                try {
                    $where = array('AgencySysId =?' => $AgencyId);
                    $updateData->updateTable("TB_Agency", $updatedArray, $where);
                    $errorMessage = "One Time Password(OTP) has been sent your on mobile ******$login_lastfourdigt_mobile_no, Please enter the same OTP here to login.";
                } catch (Zend_Exception $e) {
                    $errorMessage = $e->getMessage();
                }
            } else {
                $errorMessage = "Oops! Please try again";
            }
        } else {
            $errorMessage = "Oops! Please try again";
        }
        echo $errorMessage;
        exit;
    }

    public function countrycodeiconAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $arrResponse = array();
        if ($this->getRequest()->getParam("countryname")) {
            $countryname = $this->getRequest()->getParam("countryname");
            $countrycodeicon = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->countrycodeicon(($countryname != '') ? str_replace('+', '', trim($countryname)) : 'India');
            echo json_encode($countrycodeicon);
            exit;
        }
    }

    public function addAgencyTermAndCondition($AgencySysId) {
        $objInsurance = new Travel_Model_TblInsurance();
        $termCondition = $objInsurance->getTermAndConditionList($AgencySysId);
        if (empty($termCondition)) {
            $travelplanterms = $objInsurance->getTermAndConditionList(21);
            foreach ($travelplanterms as $travelplantermsvalue) {
                unset($travelplantermsvalue['TncId']);
                $travelplantermsvalue["AgencySysId"] = $AgencySysId;
                $travelplantermsvalue["IsInclusions"] = 0;
                $travelplantermsvalue["IsExclusions"] = 0;
                $travelplantermsvalue["IsCancellationPolicy"] = 0;
                $travelplantermsvalue["IsTravelBasics"] = 0;
                $travelplantermsvalue["IsBookingTerms"] = 0;
                $travelplantermsvalue["IsWhyUseUs"] = 0;
                $travelplantermsvalue["IsTermsAndConditions"] = 0;
                $travelplantermsvalue["IsPayment"] = 0;
                $travelplantermsvalue["IsCancellationPolicyInternational"] = 0;
                $travelplantermsvalue["IsTermsAndConditionsInternational"] = 0;
                $travelplantermsvalue["IsInclusionsInternational"] = 0;
                $travelplantermsvalue["IsInclusionsDomestic"] = 0;
                $travelplantermsvalue["IsExclusionDomestic"] = 0;
                $travelplantermsvalue["IsExclusionInternational"] = 0;
                $travelplantermsvalue["IsPaymentDetails"] = 0;
                $travelplantermsvalue["IsbookingTermVisa"] = 0;
                $travelplantermsvalue["IstravelBasicsVisa"] = 0;
                $travelplantermsvalue["IstermConditionsVisa"] = 0;
                $travelplantermsvalue["IscancellationPolicyVisa"] = 0;
                $travelplantermsvalue["IsREFUNDPOLICY"] = 0;
                $travelplantermsvalue["IstermConditionsTransfer"] = 0;
                $travelplantermsvalue["IsTermConditionsInvoice"] = 0;

                $objPackage = new Travel_Model_TblPackage();
                $objPackage->insertData('TB_Agency_Terms_Conditions', $travelplantermsvalue);
            }
        }
    }

    public function deleteAgencyImgAction() {
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            $AgencyId = isset($getData['AgencyId']) ? $getData['AgencyId'] : 1;
            $AgencyPhoto = isset($getData['AgencyPhoto']) ? $getData['AgencyPhoto'] : '';
            $originalThumbFolder = $_SERVER["DOCUMENT_ROOT"] . '/public/upload/media/agency/' . $AgencyId . '/photo/' . $AgencyPhoto;
            $objAgency = new Travel_Model_TblAgency();
            $updateData = [
                'AgencyPhoto' => 0,
            ];
            if (file_exists($originalThumbFolder)) {
                unlink($originalThumbFolder);
                $objAgency->updateAgencyData($updateData, $AgencyId);
                $result = array('status' => true, 'msg' => 'Image has been deleted');
                echo json_encode($result);
            } else {
                $result = array('status' => false, 'msg' => 'Image does not exist');
                echo json_encode($result);
            }
        }
    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit