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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

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

/**
 * Copyright 2013 Catabatic Automation Technology Pvt Ltd.
 * All rights reserved
 *
 * @description: Travel_Model_TblLead.php, Leads Model. 2016/06/16 16:30
 * @author: Shakti Rana <shakti@catpl.co.in>
 */
class Admin_LeadController extends Catabatic_ValidateAdmin {

    const CONST_SOURCE_ADMIN = 3;

    protected $intLoggedinUserId;
    protected $InfoSourceSysId = 0;
    protected $intLoggedinUserGroupSysId = 0;
    protected $intLoggedinUserAgencySysId = 0;
    protected $intLoggedinUserTrxCurrency = 0;

    public function init() {
        parent::init();
        $this->model = @$this->modelName ? new $this->modelName() : null;
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $this->baseUrl = $request->getScheme() . '://' . $request->getHttpHost();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionLogin_Details = new Zend_Session_Namespace('AdminUser');
        $this->intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $this->emailIdLoginUser = $sessionLogin_Details->user->EmailId;
        $this->GRID_PER_PAGE_RECORD_COUNT = GRID_PER_PAGE_RECORD_COUNT;
        $this->InfoSourceSysId = self::CONST_SOURCE_ADMIN; // Source - Agent 
    }

    public function indexAction() {
        
    }

    /**
     * Permission Action. Renders the list of permissions.
     */
    public function permissionAction() {
        $permissionModel = new Travel_Model_TblLead();
        $params = $this->getRequest()->getParams();
        $sql = "SELECT TOP 1 TBA.AgencySysId, Title, AgencyType, TBA.Address, TBAU.UserSysId, TBAU.EmailId, TBAU.UserRole, PrimaryContactNo 
                FROM TB_Agency_User AS TBAU
                LEFT JOIN TB_Agency AS TBA 
                ON TBA.AgencySysId = TBAU.AgencySysId
                AND TBA.AgencySysId={$params['AgencySysId']}
                WHERE TBA.AgencySysId > 0 
                ORDER BY TBA.AgencySysId DESC";
        $leadDetail = $permissionModel->getLeadList($sql);
        if ($leadDetail[0]['UserRole'] && $leadDetail[0]['UserSysId']) {
            $leadDetail[0]['role'] = $permissionModel->getRole($leadDetail[0]['UserRole'], $leadDetail[0]['AgencySysId']);
            $this->view->leadDetail = $leadDetail;
            $this->subSystemType = $subSystemType = 2; //B2B System      
            $permissionListArray = $permissionModel->getPermissionList($subSystemType);
            foreach ($permissionListArray as $permissionList) {
                if (!@$permissionList['ParentModule']) {
                    $permissionModulesArray[] = $this->getList($permissionModel, $permissionListArray, $permissionList);
                }
            }
            $this->view->permissionModulesArray = $permissionModulesArray;
            $maxComponent = $permissionModel->getComponents();
            $this->view->maxComponent = count($maxComponent);
            $this->view->permissionModel = $permissionModel;
            $this->view->componentTitles = $permissionModel->getComponentTitle();
            $query = "SELECT ModuleType,ComponentType FROM TB_Agency_UserRole_Permission WHERE AgencySysId =" . $leadDetail[0]['AgencySysId'] . " AND RoleSysId=" . $leadDetail[0]['UserRole'] . " AND SubSystemType=" . $subSystemType;
            $rolePermissionArray = $permissionModel->executeQuery($query);
            $selectedComponents = array();
            foreach ($rolePermissionArray as $rolePermission) {
                $selectedComponents[] = $rolePermission['ModuleType'] . "_" . $rolePermission['ComponentType'];
            }
            $this->view->selectedComponents = $selectedComponents;
        }
    }

    /**
     * getList. Generate the hirerachy of the arrays.
     * 
     * @param array $permissionListArray
     * @param array $permissionList
     * @return array
     */
    public function getList($permissionModel, $permissionListArray, $permissionList) {
        foreach ($permissionListArray as $list) {
            if ($permissionList['ModuleType'] == $list['ParentModule']) {
                //$list['Components'] = $permissionModel->getComponents($list);
                $nodeArray = $this->getList($permissionModel, $permissionListArray, $list);
                $permissionList['ChildModule'][] = $nodeArray;
            }
        }
        return $permissionList;
    }

    /**
     * List of Agency/Partners.
     */
    public function listAction() {
        $leadModel = new Travel_Model_TblLead();
        $searchArr = array();
        $getData = array();
        $Activated = 1;
        $varified = 1;
        $Deleted = 0;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //echo "<pre>"; print_r($getData); 
            if (!empty($getData)) {
                if (isset($getData['NotLoggedIn']) && !empty($getData['NotLoggedIn'])) {
                    $NotLoggedIn = $getData['NotLoggedIn'];
                } else {
                    $NotLoggedIn = array();
                }

                if (@$getData['Title'] != "") {
                    $Title = @trim($getData['Title']);
                } else {
                    $Title = "";
                }
                if (@$getData['IsPaymentGateway'] != "") {
                    $IsPaymentGateway = @trim($getData['IsPaymentGateway']);
                } else {
                    $IsPaymentGateway = "";
                }
                if (isset($getData['Status']) && $getData['Status'] != "") {
                    $Activated = $IsStatus = (int) $getData['Status'];
                } else {
                    $IsStatus = "";
                }
                if (@$getData['IsEmailSetting'] != "") {
                    $IsEmailSetting = @trim($getData['IsEmailSetting']);
                } else {
                    $IsEmailSetting = "";
                }
                if (@$getData['IsB2CSite'] != "") {
                    $IsB2CSite = @trim($getData['IsB2CSite']);
                } else {
                    $IsB2CSite = "";
                }
                if (@$getData['IsB2CUrl'] != "") {
                    $IsB2CUrl = @trim($getData['IsB2CUrl']);
                } else {
                    $IsB2CUrl = "";
                }
                if (@$getData['RelationalManager'] != "") {
                    $RelationalManager = @trim($getData['RelationalManager']);
                } else {
                    $RelationalManager = "";
                }

                $searchArr = array(
                    'Title' => $Title,
                    'IsPaymentGateway' => $IsPaymentGateway,
                    'IsEmailSetting' => $IsEmailSetting,
                    'IsB2CSite' => $IsB2CSite,
                    'IsB2CUrl' => $IsB2CUrl,
                    'IsActive' => $IsStatus,
                    'RelationalManager' => $RelationalManager,
                    'NotLoggedIn' => $NotLoggedIn
                );
            }
        } else {
            $Title = $this->_getParam('Title');
            $IsPaymentGateway = $this->_getParam('IsPaymentGateway');
            $IsEmailSetting = $this->_getParam('IsEmailSetting');
            $IsB2CSite = $this->_getParam('IsB2CSite');
            $IsB2CUrl = $this->_getParam('IsB2CUrl');
            if ($Title != "") {
                $Title = $Title;
            } else {
                $Title = "";
            }
            if ($IsPaymentGateway != "") {
                $IsPaymentGateway = $IsPaymentGateway;
            } else {
                $IsPaymentGateway = "";
            }
            if ($IsEmailSetting != "") {
                $IsEmailSetting = $IsEmailSetting;
            } else {
                $IsEmailSetting = "";
            }
            if ($IsB2CSite != "") {
                $IsB2CSite = $IsB2CSite;
            } else {
                $IsB2CSite = "";
            }
            if ($IsB2CUrl != "") {
                $IsB2CUrl = $IsB2CUrl;
            } else {
                $IsB2CUrl = "";
            }
            $searchArr = array(
                'Title' => $Title,
                'IsPaymentGateway' => $IsPaymentGateway,
                'IsEmailSetting' => $IsEmailSetting,
                'IsB2CSite' => $IsB2CSite,
                'IsB2CUrl' => $IsB2CUrl,
            );
        }
        $uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
        $segments = $uriSegments[4];
        if (isset($segments) && $segments == 'activated') {
            $Activated = 1;
        } else if (isset($segments) && $segments == 'deactivated') {
            $Activated = 0;
        } else if (isset($segments) && $segments == 'new') {
            $Activated = 0;
            $varified = 1;
        }
        if (isset($segments) && $segments == 'deleted') {
            $Deleted = 1;
        }

        if (empty($getData)) {
            $searchArr['IsActive'] = $Activated;
            $searchArr['IsVarified'] = $varified;
        }
        $searchArr['Deleted'] = $Deleted;
        $leadModel->searchArr = $searchArr;
        $this->view->searchArr = $searchArr;
        $leadListArray = $leadModel->getLeadListNew();
        $objAgency = new Travel_Model_TblAdminUser();
        $role = 70;
        $getUserListArray = $objAgency->getAdminUserListByRoleId($role);
        $AgencyList = $leadModel->getAgencyListAll();
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($leadListArray);
        $paginator->setItemCountPerPage(25);
        $paginator->setCurrentPageNumber($page);
        $this->view->leadListArray = $paginator;
        $this->view->agencyList = $AgencyList;
        $this->view->getUserListArray = $getUserListArray;
        $this->view->totalrec = $paginator->getTotalItemCount();
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }

    /**
     * Save Module permission(s) for default agent/partner of the agency.
     */
    public function permissionControlAction() {
        $permissionModel = new Travel_Model_TblPermission();
        if ($this->getRequest()->getParams()) {
            $AgencySysId = $this->getRequest()->getParam('id');
            $PrimaryUserSysId = $this->getRequest()->getParam('UId');
            $checkedData = $permissionModel->getModuleDataForAcl($AgencySysId, $PrimaryUserSysId);
            $this->view->AgencySysId = $AgencySysId;
            $this->view->PrimaryUserSysId = $PrimaryUserSysId;
            $this->view->checkedData = $checkedData;
        }
    }

    public function permissionControlNewAction() {
        $permissionModel = new Travel_Model_TblPermission();
        if ($this->getRequest()->getParams()) {
            $AgencySysId = $this->getRequest()->getParam('id');
            $PrimaryUserSysId = $this->getRequest()->getParam('UId');
            $curl = curl_init();
            // GTXAPIURL . 'agency/get-master-permission-user-wise/?agent_id=' . $PrimaryUserSysId.'&from_gtx_admin=1';
            curl_setopt_array($curl, array(
                CURLOPT_URL => GTXAPIURL . 'agency/get-master-permission-user-wise/?agent_id=' . $PrimaryUserSysId . '&from_gtx_admin=1',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'SECURITYKEY:' . $AgencySysId,
                    'Content-Type: application/json'
                ),
            ));
            $rightshortcuts = curl_exec($curl);
            curl_close($curl);
            $checkedData = json_decode($rightshortcuts, true);
            $this->view->AgencySysId = $AgencySysId;
            $this->view->PrimaryUserSysId = $PrimaryUserSysId;
            $this->view->checkedData = $checkedData;
        }
    }

    public function savemoduleAction() {
        $RWUADMask = 5; //Fix this after understanding the requirement @SHAKTIRANA.
        $postDataArray = $_POST;
        $agencySysId = $_POST['AgencySysId'];
        $subSystemType = $_POST['SubSystemType'];
        $roleSysId = $_POST['RoleSysId'];
        $modules = @$_POST['modulecheckbox'];
        $insertValues = null;

        $modules = array();
        $arrayKeys = array_keys($_POST);
        foreach ($arrayKeys as $key) {
            $keyString = strstr($key, 'componentscheckbox_');
            if ($keyString) {
                $keyId = explode('_', $keyString);
                $modules[] = $keyId[1];
            }
        }

        $permissionModel = new Travel_Model_TblLead();

        foreach ($modules as $moduleId) {
            $permissionData = array_fill(0, 5, 0);

            foreach ($_POST["componentscheckbox_$moduleId"] as $value) {
                $insertValues .= $insertValues ? ', ' : $insertValues;
                $dateTime = date('Y-m-d H:i:s');
                $moduleComponentCondition = @$componentType ? " AND ModuleType=$moduleId AND ComponentType=$value" : "";
                $permissionModel->executeQuery("DELETE FROM TB_Agency_UserRole_Permission WHERE AgencySysId=$agencySysId AND RoleSysId=$roleSysId AND SubSystemType=$subSystemType $moduleComponentCondition");
                /*
                  $insertValues      = array( 'AgencySysId'=>$agencySysId,
                  'RoleSysId' => $roleSysId,
                  'SubSystemType'=>$subSystemType,
                  'ModuleType'=>$moduleId,
                  'ComponentType'=>$value,
                  'RWUADMask'=>10101,
                  'UpdateDate'=>"$dateTime",
                  'CreateDate'=>"$dateTime",
                  'IsActive'=>1);

                  $permissionModel->db->insert('TB_Agency_UserRole_Permission', $insertValues);
                  }
                  }
                 */

                /* Another approach to insert all vlaues into db. Please remove if execute insert query not work. @SHAKTIRANA */
                $insertValues .= "($agencySysId, $roleSysId, $subSystemType, $moduleId, $value, 10101, '$dateTime', '$dateTime', 1)";
            }
        }
        $insertQuery = "INSERT INTO TB_Agency_UserRole_Permission values $insertValues";
        $permissionModel->executeQuery($insertQuery);
        /* Another Approach Ends. */
    }

    /**
     * Delete Action. 
     * 
     * @param string $whereCondition
     * @param string $url
     * @param string $messageKey
     */
    public function saveAdminPermissionAction() {
        $permissionModel = new Travel_Model_TblPermission();
        $getData = $this->getRequest()->getParams();
        $AgencySysId = $getData['id'];
        $selectedmainMenu = $getData['selectedmainMenu'];
        $checkmenulist = explode(',', $selectedmainMenu);
        $PrimaryUserSysId = $getData['PrimaryUserSysId'];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => GTXAPIURL . 'agency/get-master-permission-user-wise/?agent_id=' . $PrimaryUserSysId . '&from_gtx_admin=1',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'SECURITYKEY:' . $AgencySysId,
                'Content-Type: application/json'
            ),
        ));
        $rightshortcuts = curl_exec($curl);
        curl_close($curl);
        $rightshortcutsArray = json_decode($rightshortcuts, true);
        $menuFields = array();
        $agencySysIdArray = $permissionModel->getAgencySysIdFromSecurityKey($AgencySysId);
        if (isset($agencySysIdArray[0]['AgencySysId']) && $agencySysIdArray[0]['AgencySysId'] > 0) {
            $agencySysId = $agencySysIdArray[0]['AgencySysId'];
            foreach ($rightshortcutsArray as $key => $list) {
                if (in_array($list['content_sys_id'], $checkmenulist)) {
                    $menuFields[] = array(
                        "agency_sys_id" => $agencySysId,
                        "agent_sys_id" => $PrimaryUserSysId,
                        "content_sys_id" => $list['content_sys_id'],
                        "is_display_in_dashboard" => "0",
                        "is_order" => $key,
                        "is_mark_for_del" => "0",
                        "is_active" => "1",
                        "is_master" => "0"
                    );
                } else {
                    $menuFields[] = array(
                        "agency_sys_id" => $agencySysId,
                        "agent_sys_id" => $PrimaryUserSysId,
                        "content_sys_id" => $list['content_sys_id'],
                        "is_display_in_dashboard" => "0",
                        "is_order" => "1",
                        "is_mark_for_del" => "0",
                        "is_active" => "0",
                        "is_master" => "0"
                    );
                }
            }
            $menuFieldsJson = json_encode(array("user_permission" => $menuFields));
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => GTXAPIURL . 'agency/get-master-permission-user-wise/',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $menuFieldsJson,
                CURLOPT_HTTPHEADER => array(
                    'SECURITYKEY:' . $AgencySysId,
                    'Content-Type: application/json'
                ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            echo $response;
            exit;
        }
    }

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

        $model = new Travel_Model_TblAgency();
        $agencyId = $this->getRequest()->getParam('AgencySysId');

        $isRecordDeleted = $model->deleteRecord(" AgencySysId = $agencyId", 'TB_Agency');
        $message = @$isRecordDeleted ? "Agency deleted successfully." : "Agency deletion failed.";

        $this->_helper->flashMessenger->addMessage($message);

        if (@$isRecordDeleted) {
            $this->_helper->redirector('list', 'lead');
        }
    }

    /**
     * Deactivate Hotel Action. 
     */
    public function deactivateAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $objHotel = new Travel_Model_TblAgency();
        $agencyId = $this->getRequest()->getParam('id');

        $isDeactive = $objHotel->setActiveDeactive(" AgencySysId=$agencyId", "TB_Agency", 0);
        $message = @$isDeactive ? "Agency deactivated successfully." : "Agency deactivation failed.";

        $this->_helper->flashMessenger->addMessage($message);

        if (@$isDeactive) {
            $this->_redirect('/admin/lead/list');
        }
    }

    /**
     * Activate Hotel Action. 
     */
    public function activateAction() {
        $this->tableName = 'TB_IC_Accomdation';
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $objHotel = new Travel_Model_TblAgency();
        $agencyId = $this->getRequest()->getParam('id');

        $isActive = $objHotel->setActiveDeactive(" AgencySysId=$agencyId", "TB_Agency", 1);
        $message = @$isActive ? "Agency activated successfully." : "Agency activation failed.";

        $this->_helper->flashMessenger->addMessage($message);

        if (@$isActive) {
            $this->_redirect('/admin/lead/list');
        }
    }

    /**
     * List of Agency/Partners.
     */
    public function insuranceSettingsAction() {
        $this->_helper->layout->disableLayout();
        $objInsurance = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $currencyId = $this->getRequest()->getParam('currency');
        $insuranceCompanyListArr = $objInsurance->getInsuranceCompanyList();
        $this->view->insuranceCompanyListArr = $insuranceCompanyListArr;
        $this->view->currencyId = $currencyId;
        $this->view->agencySysId = $agencySysId;

        $agencyInsuranceCompanyArr = $objInsurance->getAgencyInsuranceCompany($agencySysId);
        //        $agencyInsuranceCompanyArray = array();
        foreach ($agencyInsuranceCompanyArr as $agencyInsuranceCompany) {
            $agencyInsuranceCompanyArr[$agencyInsuranceCompany['InsuCompSysId']] = $agencyInsuranceCompany['Commision'];
        }
        $this->view->agencyInsuranceCompanyArr = $agencyInsuranceCompanyArr;
    }

    public function subscriptionSettingsAction() {
        $this->_helper->layout->disableLayout();
        $objSubscription = new Subscription_Model_Subscription();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $currencyId = $this->getRequest()->getParam('currency');
        $getPlanListArr = $objSubscription->getSubscriptionPlanMaster("TB_Master_Subscription_Template_Items", '1');
        $getRazorPlanListArr = $objSubscription->getPlanType("TB_Master_Subscription_Razor_Plan");
        //echo "<pre>"; print_r($getRazorPlanListArr); die;
        //$getPlanTypeListArr = $objSubscription->getPlanType("TB_Master_Subscription_Frequency");
        $this->view->getPlanListArr = $getPlanListArr;
        $this->view->getRazorPlanTypeListArr = $getRazorPlanListArr;
        $this->view->currencyId = $currencyId;
        $this->view->agencySysId = $agencySysId;
    }

    public function saveSubscriptionSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $invoiceFlag = 0;
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $packageArr = unserialize(PACKAGE_TYPE);
            $getPaymentStatus = $getData['paymentStatus'];
            $getPaymentOption = $getData['paymentOption'];
            $objAgency = new Travel_Model_TblAgency();
            //echo "<pre>"; print_r($packageArr);
            //echo "<pre>"; print_r($getData);die;
            $packageType = $getData['packageType'];
            $packageName = $packageArr[$packageType];
            $dateNew = new Zend_Date();
            $currentDate = $dateNew->get('YYYY-MM-dd');
            $PlanName = $getData['PlanName'];
            $currencyId = trim($getData['currencyId']);
            $agencySysId = trim($getData['agencySysId']);
            $objSubscription = new Subscription_Model_Subscription();
            $UserSysId = Travel_Model_AdminAuth::getIdentity()->UserSysId;
            $finalresult = $objSubscription->getDetailsByPlanName("TB_Master_Subscription_Template_Items", '*', 'SubsTemplateItemSysId', $PlanName);
            //echo "<pre>"; print_r($finalresult); die;
            $monthlyOption = 0;
            $asPerUseOption = 0;
            $quarOption = 0;
            $halfYearOption = 0;
            $anualOption = 0;
            if ($packageType == 1) {
                $amount1 = $finalresult['monthlyPerMonthFee'];
                $amount2 = $finalresult['monthlySetupFee'];
                $planFrequentVal = 30;
                $monthlyOption = 1;
            }
            if ($packageType == 2) {
                $amount1 = $finalresult['quarterlyPerMonthFee'];
                $amount2 = $finalresult['quarterlySetupFee'];
                $planFrequentVal = 90;
                $quarOption = 1;
            }
            if ($packageType == 3) {
                $amount1 = $finalresult['halfYrPerMonthFee'];
                $amount2 = $finalresult['halfYrSetupFee'];
                $planFrequentVal = 180;
                $halfYearOption = 1;
            }
            if ($packageType == 4) {
                $amount1 = $finalresult['anualPerMonthFee'];
                $amount2 = $finalresult['anualSetupFee'];
                $planFrequentVal = 365;
                $anualOption = 1;
            }
            if ($packageType == 5) {
                $amount1 = $finalresult['payperusePerMonthFee'];
                $amount2 = $finalresult['payperuseSetupFee'];
                $planFrequentVal = 365;
                $asPerUseOption = 1;
            }

            if ($getPaymentOption == 2) {
                $setupFeePayment = $amount2;
                $recurringPayment = $amount1;
                $gstSetupFeeAmount = ($setupFeePayment * 18) / 100;
                $gstRecurringAmount = ($recurringPayment * 18) / 100;
                $finalSetupFeeAmount = $setupFeePayment + $gstSetupFeeAmount;
                $finalRecurringAmount = $recurringPayment + $gstRecurringAmount;

                $subtotal = $amount1 + $amount2;
                $Credit = ($subtotal * 18) / 100;
                $finalTotal = ($subtotal + $Credit);
            } else {
                $subtotal = $amount1 + $amount2;
                $Credit = ($subtotal * 18) / 100;
                $finalTotal = ($subtotal + $Credit);
            }

            // echo $finalTotal; die;
            $getSubPlanAgencyLog = $objSubscription->getSubPlanAgencyLog("TB_Master_Subscription_TopUps_Log", $agencySysId);
            if (!empty($getSubPlanAgencyLog)) {
                $LastActiveOnLog = $getSubPlanAgencyLog['TopUpAvailTo']->format('Y-m-d');
                $datetime1LOG = new DateTime($LastActiveOnLog);
                //$datetime1LOG->modify("+1 DAYS");
                $TopUpAvailFromLog = $datetime1LOG->format('Y-m-d');
                $logId = $getSubPlanAgencyLog['SubsTopUpsSysId'];
                $addFrequentValLod = (int) trim($planFrequentVal);
                $datetimelod = new DateTime($TopUpAvailFromLog);
                $datetimelod->modify("+$addFrequentValLod DAYS");
                $TopUpAvailToLog = $datetimelod->format('Y-m-d');
                $topupExpryDate = $getSubPlanAgencyLog['TopUpAvailFrom']->format('Y-m-d');
                $dueDate = new DateTime($topupExpryDate);
                //$datetime1LOG->modify("+1 DAYS");
                $DueDate = $dueDate->format('Y-m-d');
            } else {
                $TopUpAvailFromLog = '';
                $TopUpAvailToLog = '';
                $DueDate = '';
                $logId = '';
            }

            $addFrequentVal = (int) trim($planFrequentVal);
            $datetime = new DateTime($currentDate);
            $datetime->modify("+$addFrequentVal DAYS");
            $TopUpAvailTo = $datetime->format('Y-m-d');
            $addAgencyInsuData = array(
                'Title' => 'Topup',
                'Icon' => 0,
                'IsInventoryItem' => 0,
                'SubscriptionPackageType' => $packageType,
                'SubsTopUpType' => $finalresult['planName'],
                'SubsTemplateItemSysId' => $PlanName,
                'BaseQty' => 0,
                'CurrencyType' => $currencyId,
                'BasePrice' => $finalTotal,
                'OwnerSysId' => $agencySysId,
                'TopUpAvailFrom' => !empty($TopUpAvailFromLog) ? $TopUpAvailFromLog : $currentDate,
                'TopUpAvailTo' => !empty($TopUpAvailToLog) ? $TopUpAvailToLog : $TopUpAvailTo,
                'CreateDate' => $currentDate,
                'UpdateDate' => $currentDate,
                'IsApproved' => TRUE,
                'ApprovedBy' => $UserSysId,
                'ApproveDate' => $currentDate,
                'IsActive' => TRUE,
                'PaymentStatus' => $getPaymentStatus,
                'IsMarkForDelete' => False
            );

            $AgencySubAsignData = array(
                'OwnerSysId' => $agencySysId,
                'SubsTempateSysId' => $PlanName,
                'SubsciptionType' => $packageType,
                'invoice' => $finalresult['invoice'],
                'marketing' => $finalresult['marketing'] == 1 ? 1 : 0,
                'fullfillment' => $finalresult['fullfillment'],
                'B2B' => $finalresult['B2B'],
                'B2C' => $finalresult['B2C'],
                'hotelCotracting' => $finalresult['hotelCotracting'],
                'PaymentStatus' => $getPaymentStatus,
                'ExpiryDate' => !empty($TopUpAvailToLog) ? $TopUpAvailToLog : $TopUpAvailTo,
                'freshProposals' => $finalresult['freshProposals'],
                'freeSMS' => $finalresult['freeSMS'],
                'freeEmail' => $finalresult['freeEmail'],
                'autoFollowUps' => $finalresult['autoFollowUps'],
                'offer' => $finalresult['offer'],
                'sourcing' => $finalresult['sourcing'],
                'website' => $finalresult['website'],
                'freshProposalsExtraCost' => $finalresult['freshProposalsExtraCost'],
                'freeSMSExtraCost' => $finalresult['freeSMSExtraCost'],
                'freeEmailExtraCost' => $finalresult['freeEmailExtraCost'],
                'autoFollowUpsExtraCost' => $finalresult['autoFollowUpsExtraCost'],
                'noOfPackages' => $finalresult['noOfPackages'],
                'noOfPackagesExtraCost' => $finalresult['noOfPackagesExtraCost'],
                'marketingEmail' => $finalresult['marketingEmail'],
                'marketingEmailExtraCost' => $finalresult['marketingEmailExtraCost'],
                'noOfHotels' => $finalresult['noOfHotels'],
                'webOnlyPackage' => $finalresult['webOnlyPackage'],
                'webWithFixDep' => $finalresult['webWithFixDep'],
                'webWithActSight' => $finalresult['webWithActSight'],
                'webWithPackage' => $finalresult['webWithPackage'],
                'webSelfPackage' => $finalresult['webSelfPackage'],
                'webSelfNoOfPack' => $finalresult['webSelfNoOfPack'],
                'webflight' => $finalresult['webflight'],
                'webhotel' => $finalresult['webhotel'],
                'monthlyOption' => $monthlyOption,
                'monthlySetupFee' => $finalresult['monthlySetupFee'],
                'monthlyPerMonthFee' => $finalresult['monthlyPerMonthFee'],
                'quarterlyOption' => $quarOption,
                'quarterlySetupFee' => $finalresult['quarterlySetupFee'],
                'quarterlyPerMonthFee' => $finalresult['quarterlyPerMonthFee'],
                'halfYrOption' => $halfYearOption,
                'halfYrSetupFee' => $finalresult['halfYrSetupFee'],
                'halfYrPerMonthFee' => $finalresult['halfYrPerMonthFee'],
                'anualOption' => $anualOption,
                'anualSetupFee' => $finalresult['anualSetupFee'],
                'anualPerMonthFee' => $finalresult['anualPerMonthFee'],
                'monthlyInvoice' => $finalresult['monthlyInvoice'],
                'subscriptionType' => $finalresult['subscriptionType'],
                'marketoffer' => $finalresult['marketoffer'],
                'payperuseOption' => $asPerUseOption,
                'payperuseSetupFee' => $finalresult['payperuseSetupFee'],
                'payperusePerMonthFee' => $finalresult['payperusePerMonthFee'],
                'noOfQuery' => $finalresult['noOfQuery'],
                'noOfQueryExtraCost' => $finalresult['noOfQueryExtraCost'],
                'razorpaySubscriptionPlanId' => $finalresult['razorpaySubscriptionPlanId'],
                'planName' => $getData['razorpayplan'],
                'IsMarkForDelete' => False
            );
            //echo "<pre>"; print_r($addAgencyInsuData); die;
            try {
                $objSubscription->insertTable("TB_Master_Subscription_TopUps_Log", $addAgencyInsuData);
                $lastAsignId = $objSubscription->insertTable("TB_Agency_Subscription_Asign", $AgencySubAsignData);
                $getSubscriptionPlanAgency = $objSubscription->getSubscriptionPlanAgency("TB_Master_Subscription_TopUps", $agencySysId);

                $updateDataOfAgency = array(
                    'AgencySubsAsignId' => $lastAsignId,
                    'IsActiveSubscription' => 0
                );
                $whrAgencyCon = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency", $updateDataOfAgency, $whrAgencyCon);
                // echo $lastAsignId; die;
                if (!empty($getSubscriptionPlanAgency)) {
                    $topupLastId = $getSubscriptionPlanAgency['SubsTopUpsSysId'];
                    $LastActiveOn = $getSubscriptionPlanAgency['TopUpAvailTo']->format('Y-m-d');
                    $datetime1 = new DateTime($LastActiveOn);
                    $datetime1->modify("+$addFrequentVal DAYS");
                    $TopUpAvailToUpdate = $datetime1->format('Y-m-d');
                    $updateData = array(
                        'IsInventoryItem' => 0,
                        'SubsTopUpType' => $finalresult['planName'],
                        'CurrencyType' => $currencyId,
                        'TopUpAvailTo' => $TopUpAvailToUpdate,
                        'UpdateDate' => $currentDate,
                        'IsApproved' => TRUE,
                        'ApprovedBy' => $UserSysId,
                        'IsActive' => TRUE,
                        'PaymentStatus' => $getPaymentStatus,
                        'IsMarkForDelete' => False
                    );
                    $whereCon = array("OwnerSysId =?" => $agencySysId);

                    try {
                        $objSubscription->updateTable("TB_Master_Subscription_TopUps", $updateData, $whereCon);
                        //$json = array('result' => 1);
                        // echo json_encode($json);
                        // exit;
                    } catch (Zend_Exception $e) {
                        echo $e->getMessage();
                        exit;
                    }
                } else {
                    try {
                        $topupLastId = $objSubscription->insertTable("TB_Master_Subscription_TopUps", $addAgencyInsuData);
                    } catch (Zend_Exception $e) {
                        echo $e->getMessage();
                        exit;
                    }
                }
                // echo $getPaymentStatus; die;
                //email invoice code start
                if ($getPaymentStatus == 1 || $finalTotal == 0) {

                    $currentDate = date("Y-m-d H:i");
                    $moduleName = unserialize(MODULENAME);
                    $permissionModel = new Travel_Model_TblPermission();
                    $isActive = $objAgency->setActiveDeactive(" AgencySysId=$agencySysId", "TB_Agency", 1);
                    $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
                                    );
                                    try {
                                        $permissionModel->insertData("TB_Agency_UserRole_Permission", $insertData);
                                        $isActive = $objAgency->setActiveDeactive(" AgencySysId=$agencySysId", "TB_Agency", 1);
                                        $agencyData = array('IsVarified' => 1, 'IsActiveSubscription' => 1);
                                        $objAgency->updateAgencyData($agencyData, $agencySysId);


                                        //                                  code for general and marketing email data                                   
                                        $finalEmail = $finalresult['freeEmail'] + $finalresult['marketingEmail'];
                                        $extraCost = $finalresult['freeEmailExtraCost'];
                                        $marketWalletArr = array('finalEmail' => $finalEmail, 'extracost' => $extraCost);
                                        $objSubscription->addupdatewalletdata($marketWalletArr, 'TB_Agency_Marketing_Wallet', $agencySysId);

                                        //code for fresh praposal wallet data
                                        $finalPraposal = $finalresult['freshProposals'];
                                        $extraCostPraposal = $finalresult['freshProposalsExtraCost'];
                                        $freshPraposalWalletArr = array('finalEmail' => $finalPraposal, 'extracost' => $extraCostPraposal);
                                        $objSubscription->addupdatewalletdata($freshPraposalWalletArr, 'TB_Agency_FreshProposal_Wallet', $agencySysId);
                                        //code for fresh sms wallet data

                                        $finalSms = $finalresult['freeSMS'];
                                        $extraCostSMS = $finalresult['freeSMSExtraCost'];
                                        $SMSWalletArr = array('finalEmail' => $finalSms, 'extracost' => $extraCostSMS);
                                        $objSubscription->addupdatewalletdata($SMSWalletArr, 'TB_Agency_SMS_Wallet', $agencySysId);

                                        //code for fresh autofollowup wallet data
                                        $finalAutoFollowup = $finalresult['autoFollowUps'];
                                        $extraCostAutoFollowup = $finalresult['autoFollowUpsExtraCost'];
                                        $autofollowupWalletArr = array('finalEmail' => $finalAutoFollowup, 'extracost' => $extraCostAutoFollowup);
                                        $objSubscription->addupdatewalletdata($autofollowupWalletArr, 'TB_Agency_AutoFollowUP_Wallet', $agencySysId);
                                    } catch (Exception $e) {
                                        echo $e->getMessage();
                                        exit;
                                    }
                                }
                            }
                        }
                    }
                    //$objAgency->updateAgencyData($agencyData, $agencySysId);
                    $json = array('result' => 1);
                    echo json_encode($json);
                    exit;
                } else {
                    //$AgentName = $this->intLoggedinUserFirstName;
                    //$strInvoiceNo=date('Y')."-".date('m')."-".$logId;
                    if (!empty($logId)) {
                        $strInvoiceNo = "00" . $logId;
                    } else {
                        $strInvoiceNo = "00" . $topupLastId;
                    }
                    // echo $strInvoiceNo; die;

                    $topupSysId = $topupLastId;
                    $strInvoiceNumber = $strInvoiceNo;
                    $AgencyData = $objAgency->getUserDataByAgency($agencySysId);
                    $AddressAgency = $objAgency->getAddressByAgency($agencySysId);
                    $BankDetailsAgency = $objAgency->getBankDetailsByAgency($agencySysId);
                    $duedate = new DateTime($DueDate);
                    $duedate->modify("+5 DAYS");
                    $invoiceDueDate = $duedate->format('Y-m-d');
                    $paymentTypeReccorOne = $getPaymentOption == 2 ? 'automatic' : 'manual';
                    $arrpost = array(
                        'finalresult' => $finalresult,
                        'AgencyData' => $AgencyData,
                        'SetupFee' => $amount2,
                        'RecurringFee' => $amount1,
                        'paymentTypeOption' => $paymentTypeReccorOne,
                        'SubscriptionType' => $packageName,
                        'InvoiceNo' => $strInvoiceNumber,
                        'InvoiceDueDate' => $invoiceDueDate,
                        'topupSysId' => $topupSysId,
                        'adminEmailId' => $this->emailIdLoginUser,
                    );
                    //                  echo "<pre>"; print_r($AgencyData);  die;
                    if ($getPaymentOption == 2) {
                        $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendSubscriptionAutoInvoice($arrpost);
                    } else {
                        $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendSubscriptionInvoice($arrpost);
                    }
                    if ($emailStatus == '1') {
                        $invoiceFlag = 1;
                    } else {
                        $invoiceFlag = 0;
                    }
                    $json = array('result' => 1);
                    echo json_encode($json);
                    exit;
                }
                //          email invoice code end
            } catch (Zend_Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
    }

    public function subscriptiondeleteAction() {
        $agencySysId = (int) $this->getRequest()->getParam('id');
        $topupId = $this->getRequest()->getParam('topupId');
        $gUID = $this->getRequest()->getParam('guid');
        $objSubscription = new Subscription_Model_Subscription();
        //die('deug');
        //      echo ADMIN_ID; die;
        if (!empty($agencySysId) && $agencySysId > 0) {
            $mxId = $agencySysId . "" . $topupId;
            $checkguID = hash('ripemd160', $mxId);
            //          echo $checkguID."==".$gUID; die;
            if ($checkguID != $gUID) {
                $this->_redirect('/admin/lead/list');
            }
            //$getSubscriptionPlanAgency = $objSubscription->getSubscriptionPlanAgency("TB_Master_Subscription_TopUps", $agencySysId);
            //echo "<pre>"; print_r($getSubscriptionPlanAgency); die;
            //$finalresult = $objSubscription->getDetailsByPlanName("TB_Master_Subscription_Template_Items", '*', 'SubsTemplateItemSysId', $PlanName);            
            $updateAgencyData = array('IsActiveSubscription' => 0);
            $whereConAgency = array("AgencySysId =?" => $agencySysId);
            $objSubscription->updateTable("TB_Agency", $updateAgencyData, $whereConAgency);
            $this->_redirect('/admin/lead/list');
        } else {
            $this->_redirect('/admin/lead/list');
        }
    }

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

        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            //echo "<pre>"; print_r($getData); die;
            $paymentStatus = $getData['subpaymentStatus'];
            $objAgency = new Travel_Model_TblAgency();
            $agencySysId = $getData['agencyId'];
            $topupSysId = $getData['topupId'];
            $objSubscription = new Subscription_Model_Subscription();
            if ($paymentStatus == 'complete') {

                $updateAgencyData = array('IsActiveSubscription' => 1);
                $whereConAgency = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency", $updateAgencyData, $whereConAgency);

                $currentDate = date("Y-m-d H:i");
                $moduleName = unserialize(MODULENAME);
                $permissionModel = new Travel_Model_TblPermission();
                $isActive = $objAgency->setActiveDeactive(" AgencySysId=$agencySysId", "TB_Agency", 1);
                $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
                                );
                                try {
                                    $permissionModel->insertData("TB_Agency_UserRole_Permission", $insertData);
                                    $isActive = $objAgency->setActiveDeactive(" AgencySysId=$agencySysId", "TB_Agency", 1);
                                    $agencyData = array('IsVarified' => 1, 'IsActiveSubscription' => 1);
                                    $objAgency->updateAgencyData($agencyData, $agencySysId);
                                    $updateData = array(
                                        'PaymentStatus' => 1,
                                    );
                                    $whereCon = array("OwnerSysId =?" => $agencySysId);
                                    $objSubscription->updateTable("TB_Master_Subscription_TopUps", $updateData, $whereCon);

                                    $updateDataTopUpsLog = array(
                                        'PaymentStatus' => 1,
                                        'paymentRemark' => $getData['remark']
                                    );
                                    $whereConTopupLog = array("SubsTopUpsSysId =?" => $topupSysId);
                                    $objSubscription->updateTable("TB_Master_Subscription_TopUps_Log", $updateDataTopUpsLog, $whereConTopupLog);
                                    $finalresult = $objSubscription->getDetailsByAgencyAsignId("TB_Agency_Subscription_Asign", '*', 'OwnerSysId', $agencySysId);
                                    $AgencyData = $objAgency->getUserDataByAgency($agencySysId);
                                    $arrpost = array(
                                        'finalresult' => $finalresult,
                                        'AgencyData' => $AgencyData,
                                        'adminEmailId' => $this->emailIdLoginUser,
                                    );

                                    // $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendSubscriptionAutoInvoice($arrpost);

                                    $json = array('result' => 1);
                                    echo json_encode($json);
                                    exit;
                                } catch (Exception $e) {
                                    echo $e->getMessage();
                                    exit;
                                }
                            }
                        }
                    }
                }
            } else {
                $updateAgencyData = array('IsActiveSubscription' => 0);
                $whereConAgency = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency", $updateAgencyData, $whereConAgency);
                $updateData = array(
                    'PaymentStatus' => 2,
                );
                $whereCon = array("OwnerSysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Master_Subscription_TopUps", $updateData, $whereCon);
                $json = array('result' => 1);
                echo json_encode($json);
                exit;
            }
        }
    }

    public function saveInsuranceSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = trim($getData['agencySysId']);
            $objInsurance = new Travel_Model_TblInsurance();
            $agencyInsuranceCompanyArr = $objInsurance->getAgencyInsuranceCompany($agencySysId);
            $agencyInsuranceCompanyNewArray = array();
            foreach ($agencyInsuranceCompanyArr as $agencyInsuranceCompany) {
                $agencyInsuranceCompanyNewArray[$agencyInsuranceCompany['InsuCompSysId']] = $agencyInsuranceCompany;
            }
            foreach ($getData['comission'] as $InsuCompSysId => $commision) {
                if (!empty($agencyInsuranceCompanyNewArray[$InsuCompSysId])) {
                    $updateAgencyInsuData['AllowCredit'] = !empty($getData['allowCredit']) ? $getData['allowCredit'] : 0;
                    $updateAgencyInsuData['CreditLimit'] = !empty($getData['creditLimit']) ? $getData['creditLimit'] : 0;
                    $updateAgencyInsuData['Balance'] = !empty($getData['balance']) ? $getData['balance'] : 0;
                    $updateAgencyInsuData['Commision'] = !empty($commision) ? $commision : 0;
                    $updateAgencyInsuData['InsuCompSysId'] = $InsuCompSysId;
                    $dbArr[$InsuCompSysId] = $objInsurance->updateAgencyInsuranceCompany($updateAgencyInsuData, $agencyInsuranceCompanyNewArray[$InsuCompSysId]['AgentInsuSysId']);
                } else {
                    $addAgencyInsuData = array(
                        'AgencySysId' => $agencySysId,
                        'InsuCompSysId' => $InsuCompSysId,
                        'CurrencyId' => !empty($getData['currencyId']) ? $getData['currencyId'] : 0,
                        'AllowCredit' => !empty($getData['allowCredit']) ? $getData['allowCredit'] : 0,
                        'CreditLimit' => !empty($getData['creditLimit']) ? $getData['creditLimit'] : 0,
                        'Commision' => !empty($commision) ? $commision : 0,
                        'Balance' => !empty($getData['balance']) ? $getData['balance'] : 0
                    );
                    $dbArr[$InsuCompSysId] = $objInsurance->addAgencyInsuranceCompany($addAgencyInsuData);
                }
            }
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    /* Added by Piyush Tiwari Start */

    public function paymentSettingsAction() {
        $this->_helper->layout->disableLayout();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $obPayment = new Travel_Model_TblInsurance();
        $paymentSettingListArr = $obPayment->getPaymentSettingList($agencySysId);
        $masterPaymentGatewayType = $obPayment->getMasterPaymentGatewayType();
        $this->view->masterPaymentGatewayType = $masterPaymentGatewayType;
        //echo "<pre>";print_r($masterPaymentGatewayType);die;
        $this->view->paymentSettingListArr = $paymentSettingListArr;
        $this->view->agencySysId = $agencySysId;
    }

    public function planlistAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $objSubscription = new Subscription_Model_Subscription();
            $type = $getData['planType'];
            $getPlanListArr = $objSubscription->getSubscriptionPlanMaster("TB_Master_Subscription_Template_Items", $type);
            $this->view->getPlanListArr = $getPlanListArr;
            //echo "<pre>"; print_r($getData); die;
        }
    }

    public function packagelistAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $objSubscription = new Subscription_Model_Subscription();
            $type = $getData['packageId'];
            $getPlanListArr = $objSubscription->getSubscriptionPackageOptionByPlanId("TB_Master_Subscription_Template_Items", $type);
            $this->view->getPlanListArr = $getPlanListArr;
            //echo "<pre>"; print_r($getPlanListArr); die;
        }
    }

    public function subpackagelistAction() {
        $this->_helper->layout->disableLayout();
        $AsignId = '';
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $objSubscription = new Subscription_Model_Subscription();
            $type = $getData['packageId'];
            $AsignId = $getData['aisgnId'];
            if (empty($AsignId)) {
                $getPlanListArr = $objSubscription->getSubscriptionPackageOptionByPlanId("TB_Master_Subscription_Template_Items", $type);
            } else {
                $getPlanListArr = $objSubscription->getDetailsAsignSubscriptionByAgency("TB_Agency_Subscription_Asign", $AsignId, '');
            }

            $this->view->getPlanListArr = $getPlanListArr;
            //            echo "<pre>"; print_r($getPlanListArr); die;
        }
    }

    public function templatedetailsAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $objSubscription = new Subscription_Model_Subscription();
            $type = $getData['packageId'];
            $option = $getData['option'];
            if ($option == 1) {
                $optionType = 1;
            }
            if ($option == 3) {
                $monthly = 1;
            }
            if ($option == 6) {
                $monthly = 1;
            }
            if ($option == 12) {
                $monthly = 1;
            }
            $getPlanListArr = $objSubscription->getSubscriptionPackageOptionByPlanName("TB_Master_Subscription_Template_Items", $type);
            echo json_encode($getPlanListArr[0]);
            //            echo "<pre>"; print_r($getPlanListArr[0]); die;
            exit;
            //            echo "<pre>"; print_r($getPlanListArr); die;
        }
    }

    public function emailSettingsAction() {
        $this->_helper->layout->disableLayout();
        $obEmail = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $emailSettingListArr = $obEmail->getEmailSettingList($agencySysId);
        $this->view->emailSettingListArr = $emailSettingListArr;
        $this->view->agencySysId = $agencySysId;
    }

    public function otherSettingsAction() {
        $this->_helper->layout->disableLayout();
        $obEmail = new Travel_Model_TblInsurance();
        $subscriptionMdl = new Subscription_Model_Subscription();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $this->view->cencelprotection = $subscriptionMdl->checkCencelattionData($agencySysId);
        $this->view->leadAllocation = $subscriptionMdl->checkLeadAllocationData($agencySysId);
        $emailSettingListArr = $obEmail->getOtherSettingList($agencySysId);
        $getAgencyDistribution = $obEmail->getAgencyDistribution($agencySysId);
        $getAgencyDestinationExpertArr = $obEmail->getAgencyDestinationExpert($agencySysId);
        $getAgencySslUrl = $obEmail->sslWebsite($agencySysId);
        // echo "<pre>"; print_r($getAgencySslUrl); die("ssl and url");
        $getAgencySslUrlarr = array();
        foreach ($getAgencySslUrl as $key => $wval) {
            $getAgencySslUrlarr['IsHotelInventory'] = $wval['IsHotelInventory'];
            $getAgencySslUrlarr['IsHotelOnlyRates'] = $wval['IsHotelOnlyRates'];
            $getAgencySslUrlarr['TotalOnlyRatesHotels'] = $wval['TotalOnlyRatesHotels'];
            $getAgencySslUrlarr['TotalInventoryHotels'] = $wval['TotalInventoryHotels'];
            $getAgencySslUrlarr['IsAPIProd'] = $wval['IsAPIProd'];
            $getAgencySslUrlarr['IsB2bSSL'] = $wval['IsB2bSSL'];
            $getAgencySslUrlarr['IsB2bSite'] = $wval['IsB2bSite'];
            $getAgencySslUrlarr['IsB2bSiteURL'] = $wval['IsB2bSiteURL'];
            $getAgencySslUrlarr['IsCheckWallet'] = $wval['IsCheckWallet'];
            $getAgencySslUrlarr['IsCreditLimitActivate'] = $wval['IsCreditLimitActivate'];
            $getAgencySslUrlarr['IsAutoProposalOnFBLead'] = $wval['IsAutoProposalOnFBLead'];
            $getAgencySslUrlarr['IsPANVerified'] = $wval['IsPANVerified'];
            $getAgencySslUrlarr['IsSanKash'] = $wval['IsSanKash'];
            $getAgencySslUrlarr['IsGSTVerified'] = $wval['IsGSTVerified'];
            $getAgencySslUrlarr['IsAadharVerified'] = $wval['IsAadharVerified'];
            $getAgencySslUrlarr['IsWhatsApp'] = $wval['IsWhatsApp'];
            $getAgencySslUrlarr['IsCallCenter'] = $wval['IsCallCenter'];
            $getAgencySslUrlarr['IsEnabledB2BOtpLogin'] = $wval['IsEnabledB2BOtpLogin'];
            $getAgencySslUrlarr['IsEnabledB2CWallet'] = $wval['IsEnabledB2CWallet'];
            $getAgencySslUrlarr['IsEnabledFlexiPay'] = $wval['IsEnabledFlexiPay'];
            $getAgencySslUrlarr['WhatsappUser'] = $wval['WhatsappUser'];
            $getAgencySslUrlarr['IsB2BRewardsPoints'] = $wval['IsB2BRewardsPoints'];
        }
        //  echo "<pre>"; print_r($getAgencySslUrlarr);  die();

        $agencyDistributionArr = $getAgencyDestinationExpert = array();

        foreach ($getAgencyDistribution as $key => $val) {
            $agencyDistributionArr['RefSysId'][] = $val['RefSysId'];
            $agencyDistributionArr['PerLeadCharge'][$val['RefSysId']] = $val['PerLeadCharge'];
        }
        foreach ($getAgencyDestinationExpertArr as $dkey => $dval) {
            $getAgencyDestinationExpert[] = $dval['DestinationSysId'];
        }
        //        echo "<pre>"; print_r($getAgencyDestinationExpert); die;
        $this->view->getAgencyDestinationExpert = $getAgencyDestinationExpert;
        $this->view->agencyDistributionArr = $agencyDistributionArr;
        $this->view->emailSettingListArr = $emailSettingListArr;
        $this->view->agencySysId = $agencySysId;
        $masterData = new Webservice_Model_Master();
        $getRegionList = $masterData->getRegionData();
        $this->view->getRegionList = $getRegionList;
        $gtxNetworkWebArr = unserialize(GTX_NETWORK_WEB);
        $this->view->gtxNetworkWebArr = $gtxNetworkWebArr;
        $gtxNetworkWebPriceArr = unserialize(GTX_NETWORK_WEB_PRICE);
        $this->view->gtxNetworkWebPriceArr = $gtxNetworkWebPriceArr;
        $this->view->getAgencySslUrlarr = $getAgencySslUrlarr;
    }

    public function requirementtypeSettingsAction() {
        $this->_helper->layout->disableLayout();
        $obEmail = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $getService = $obEmail->getService($agencySysId);
        $this->view->getService = $getService;
        $this->view->agencySysId = $agencySysId;
    }

    
    public function saveRequirementTypeSettingsAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $TblAgency = new Travel_Model_TblAgency();
            $agencySysId = $getData['agencySysId'];
            $RequirementType = $getData['RequirementType'];

            $TblAgency->updateData('Tb_Agency_Services', array('IsActive'=> 0,'UpdateDate'=> date('Y-m-d')), array('AgencySysId =?' => $agencySysId));

            foreach($RequirementType as $key => $type){
                $checkservice = $TblAgency->checkService($agencySysId,$type);
                if(!empty($checkservice)){
                    $TblAgency->updateData('Tb_Agency_Services', array('IsActive'=> 1,'UpdateDate'=> date('Y-m-d')), array('AgencySysId =?' => $agencySysId,'plan_type =?'=>$type)); 
                } else {
                    $insertArr = array(
                        'plan_type'=> $type,
                        'CreateDate'=> date('Y-m-d'),
                        'UpdateDate'=> date('Y-m-d'),
                        'IsActive'=> 1,
                        'IsMarkForDelete'=> 0,
                        'AgencySysId'=> $agencySysId,
                    );
                  $TblAgency->insertData('Tb_Agency_Services', $insertArr);
                }
            }
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function apiSettingsAction() {
        $this->_helper->layout->disableLayout();
        $obEmail = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $apiSettingListArr = $obEmail->getMasterAPISource();
        $this->view->apiSettingListArr = $apiSettingListArr;
        $agencyAPISourceArr = $obEmail->getAgencyAPISource($agencySysId);
        $this->view->agencyAPISourceArr = $agencyAPISourceArr;
        $this->view->agencySysId = $agencySysId;
    }

    public function gtxPaymentSettingsAction() {
        $this->_helper->layout->disableLayout();
        $obEmail = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $emailSettingListArr = $obEmail->getGTXPaymentSettingList($agencySysId);

        $this->view->emailSettingListArr = $emailSettingListArr;
        $this->view->agencySysId = $agencySysId;
    }

    public function isB2cUrlSettingsAction() {
        $this->_helper->layout->disableLayout();
        $objIsB2CUrl = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $agencySysId = base64_decode($agencySysId);
        $IsB2CUrlSetting = $objIsB2CUrl->getIsB2CUrlSetting($agencySysId);
        $this->view->IsB2CUrlSetting = $IsB2CUrlSetting;
        $this->view->agencySysId = $agencySysId;
    }

    public function isB2cSiteAction() {
        $this->_helper->layout->disableLayout();
        $objIsB2CSite = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $agencySysId = base64_decode($agencySysId);
        $IsB2CSite = $objIsB2CSite->getIsB2CSite($agencySysId);
        $agencyMappingData = $objIsB2CSite->getAgencyMappingData('TB_Agency_WebSite_Mapping', ['*'], ['AgencySysId' => $agencySysId, 'IsActive' => 1, 'IsMarkForDel' => '0']);
        $this->view->agencyMappingData = $agencyMappingData;
        $this->view->IsB2CSite = $IsB2CSite;
        $this->view->agencySysId = $agencySysId;
    }

    public function isB2bSiteAction() {
        $this->_helper->layout->disableLayout();
        $objIsB2BSite = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $agencySysId = base64_decode($agencySysId);
        $IsB2BSite = $objIsB2BSite->getIsB2BSite($agencySysId);
        $this->view->IsB2BSite = $IsB2BSite;
        $this->view->agencySysId = $agencySysId;
    }

    public function getSecurityKeyAction() {
        $this->_helper->layout->disableLayout();
        $objIsB2BSite = new Travel_Model_TblInsurance();
        $agencySysId = $this->getRequest()->getParam('agencyId');
        $agencySysId = base64_decode($agencySysId);
        $IsB2BSite = $objIsB2BSite->getSecurityCheck($agencySysId);
        $this->view->IsB2BSite = $IsB2BSite;
    }

    public function savePaymentSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();

            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $obPayment = new Travel_Model_TblInsurance();
            $agencyPaymentSettingArray = array();
            $agencyPaymentSettingArray1 = array();
            $agencyPaymentSettingArray1['IsPaymentGateway'] = !empty($getData['IsPaymentGateway']) ? $getData['IsPaymentGateway'] : 0;
            $agencyPaymentSettingArray['AgencySysId'] = !empty($getData['agencySysId']) ? $getData['agencySysId'] : 0;
            $agencyPaymentSettingArray['PaymentUrl'] = !empty($getData['paymentUrl']) ? $getData['paymentUrl'] : 0;
            $agencyPaymentSettingArray['PaymentMerchantId'] = !empty($getData['paymentMerchantId']) ? $getData['paymentMerchantId'] : 0;
            $agencyPaymentSettingArray['PaymentGatewayMode'] = !empty($getData['mode']) ? $getData['mode'] : 0;
            $agencyPaymentSettingArray['PaymentSecretPwd'] = !empty($getData['paymentSecretPassword']) ? $getData['paymentSecretPassword'] : 0;
            $agencyPaymentSettingArray['AccountNumber'] = !empty($getData['accountNumber']) ? $getData['accountNumber'] : 0;
            $agencyPaymentSettingArray['BankName'] = !empty($getData['bankName']) ? $getData['bankName'] : 0;
            $agencyPaymentSettingArray['BranchName'] = !empty($getData['branchName']) ? $getData['branchName'] : 0;
            $agencyPaymentSettingArray['IFSC'] = !empty($getData['ifscCode']) ? $getData['ifscCode'] : 0;
            $agencyPaymentSettingArray['RespHashKey'] = !empty($getData['respHashKey']) ? $getData['respHashKey'] : 0;
            $agencyPaymentSettingArray['ReqHashKey'] = !empty($getData['reqHashKey']) ? $getData['reqHashKey'] : 0;

            $agencyPaymentSettingArray['ReqAESKey'] = !empty($getData['reqAESKey']) ? $getData['reqAESKey'] : '';
            $agencyPaymentSettingArray['ReqAESSaltKey'] = !empty($getData['reqAESSaltKey']) ? $getData['reqAESSaltKey'] : '';
            $agencyPaymentSettingArray['ResAESKey'] = !empty($getData['resAESKey']) ? $getData['resAESKey'] : '';
            $agencyPaymentSettingArray['ResAESSaltKey'] = !empty($getData['resAESSaltKey']) ? $getData['resAESSaltKey'] : '';

            $agencyPaymentSettingArray['CreateDate'] = !empty($createDate) ? $createDate : 0;
            $agencyPaymentSettingArray['PaymentOption'] = !empty($getData['role']) ? $getData['role'] : 0;
            $agencyPaymentSettingArray['ProdId'] = !empty($getData['productionId']) ? $getData['productionId'] : 0;
            $dbArr = $obPayment->alreadyExistsPaymentSetting($agencySysId);

            if (isset($dbArr) && !empty($dbArr) && $dbArr['AgencySysId'] === $agencySysId) {
                $updateDate = $date->get('yyyy-MM-dd HH:mm:ss');
                $agencyPaymentSettingArray['UpdateDate'] = $updateDate;
                $agencyPaymentSettingArray['CreateDate'] = $dbArr['CreateDate'];
                $obPayment->addEmailSetting('TB_Payment_Gateway_Setting', $agencyPaymentSettingArray, ['AgencySysId =?' => $agencySysId]);
                $obPayment->addEmailSetting('TB_Agency', $agencyPaymentSettingArray1, ['AgencySysId =?' => $agencySysId]);
            } else {
                $obPayment->addPaymentSetting($agencyPaymentSettingArray);
                $obPayment->addEmailSetting('TB_Agency', $agencyPaymentSettingArray1, ['AgencySysId =?' => $agencySysId]);
            }
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function saveEmailSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $obEmail = new Travel_Model_TblInsurance();
            $agencyEmailSettingArray = array();
            $agencyEmailSettingArray['IsEmailSetting'] = !empty($getData['is-email-setting']) ? $getData['is-email-setting'] : 0;
            $agencyEmailSettingArray['EmailKey'] = !empty($getData['emailKey']) ? $getData['emailKey'] : "";
            $dbArr = $obEmail->addEmailSetting('TB_Agency', $agencyEmailSettingArray, ['AgencySysId =?' => $agencySysId]);
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function saveOtherSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            // echo "<pre>";print_r($getData); exit;
            $agencySysId = trim($getData['agencySysId']);
            $obEmail = new Travel_Model_TblInsurance();
            $TblAgency = new Travel_Model_TblAgency();
            $objSubscription = new Subscription_Model_Subscription();
            $agencyEmailSettingArray = array();
            $depositBalance = isset($getData['depositBalance']) ? $getData['depositBalance'] : 0;
            $cancellationProtection = isset($getData['cancellationProtection']) ? $getData['cancellationProtection'] : 0;
            $objSubscription->updateCancelattionProtectionData($agencySysId, $depositBalance, $cancellationProtection);

            $IsSourceWise = isset($getData['IsSourceWise']) ? $getData['IsSourceWise'] : 0;
            $IsDestinationWise = isset($getData['IsDestinationWise']) ? $getData['IsDestinationWise'] : 0;
            $objSubscription->updateLeadAllocationData($agencySysId, $IsSourceWise, $IsDestinationWise);

            $agencyEmailSettingArray['IsDisplayHelloGTX'] = isset($getData['IsHelloGtxLogo']) ? $getData['IsHelloGtxLogo'] : 0;
            $agencyEmailSettingArray['IsTG'] = isset($getData['IsTG']) ? $getData['IsTG'] : 0;
            $agencyEmailSettingArray['IsGTXNetwork'] = isset($getData['IsGTXNetwork']) ? $getData['IsGTXNetwork'] : 0;
            $agencyEmailSettingArray['IsGTXPaymentGateway'] = isset($getData['IsGTXPaymentGateway']) ? $getData['IsGTXPaymentGateway'] : 0;
            $agencyEmailSettingArray['IsB2bSite'] = isset($getData['IsB2bSite']) ? $getData['IsB2bSite'] : 0;
            $agencyEmailSettingArray['IsSMSApi'] = isset($getData['IsSMSApi']) ? $getData['IsSMSApi'] : 0;
            $agencyEmailSettingArray['IsActiveSubscription'] = isset($getData['IsActiveSubscription']) ? $getData['IsActiveSubscription'] : 0;
            $agencyEmailSettingArray['IsGTXNetworkWeb'] = isset($getData['IsGTXNetworkWeb']) ? $getData['IsGTXNetworkWeb'] : 0;
            $agencyEmailSettingArray['IsGTXLite'] = isset($getData['IsGTXLite']) ? $getData['IsGTXLite'] : 0;

            $agencyEmailSettingArray['IsB2bSSL'] = isset($getData['IsB2bSSL']) ? $getData['IsB2bSSL'] : 0;
            $agencyEmailSettingArray['IsHotelInventory'] = isset($getData['IsHotelInventory']) ? $getData['IsHotelInventory'] : 0;
            $agencyEmailSettingArray['IsAPIProd'] = isset($getData['IsAPIProd']) ? $getData['IsAPIProd'] : 0;
            $agencyEmailSettingArray['IsB2bSiteURL'] = isset($getData['IsB2bSiteURL']) ? $getData['IsB2bSiteURL'] : 0;
            $agencyEmailSettingArray['IsCheckWallet'] = isset($getData['IsCheckWallet']) ? $getData['IsCheckWallet'] : 0;
            $agencyEmailSettingArray['IsCreditLimitActivate'] = isset($getData['IsCreditLimitActivate']) ? $getData['IsCreditLimitActivate'] : 0;
            $agencyEmailSettingArray['IsAutoProposalOnFBLead'] = isset($getData['IsAutoProposalOnFBLead']) ? $getData['IsAutoProposalOnFBLead'] : 0;
            $agencyEmailSettingArray['IsEnabledB2BOtpLogin'] = isset($getData['IsEnabledB2BOtpLogin']) ? $getData['IsEnabledB2BOtpLogin'] : 0;
            $obEmail->addEmailSetting('TB_Agency', $agencyEmailSettingArray, ['AgencySysId =?' => $agencySysId]);
            $agencyMappingArray['IsGSTVerified'] = isset($getData['IsGSTVerified']) ? $getData['IsGSTVerified'] : 0;
            $agencyMappingArray['IsPANVerified'] = isset($getData['IsPANVerified']) ? $getData['IsPANVerified'] : 0;
            $agencyMappingArray['IsAadharVerified'] = isset($getData['IsAadharVerified']) ? $getData['IsAadharVerified'] : 0;
            $agencyMappingArray['IsSanKash'] = isset($getData['IsSanKash']) ? $getData['IsSanKash'] : null;
            $agencyMappingArray['IsWhatsApp'] = isset($getData['IsWhatsApp']) ? $getData['IsWhatsApp'] : null;
            $agencyMappingArray['WhatsappUser'] = isset($getData['IsWhatsApp']) ? $getData['WhatsappUser'] : 0;
            $agencyMappingArray['IsCallCenter'] = isset($getData['IsCallCenter']) ? $getData['IsCallCenter'] : null;
            $agencyMappingArray['IsEnabledB2CWallet'] = isset($getData['IsEnabledB2CWallet']) ? $getData['IsEnabledB2CWallet'] : 0;
            $agencyMappingArray['IsEnabledFlexiPay'] = isset($getData['IsEnabledFlexiPay']) ? $getData['IsEnabledFlexiPay'] : 0;
            $agencyMappingArray['IsB2BRewardsPoints'] = isset($getData['IsB2BRewardsPoints']) ? $getData['IsB2BRewardsPoints'] : 0;
            $agencyMappingArray['TotalInventoryHotels'] = isset($getData['IsHotelInventory']) ? $getData['TotalInventoryHotels'] : 0;
            $agencyMappingArray['IsHotelOnlyRates'] = isset($getData['IsHotelOnlyRates']) ? $getData['IsHotelOnlyRates'] : 0;
            $agencyMappingArray['TotalOnlyRatesHotels'] = isset($getData['IsOnlyRates']) ? $getData['TotalOnlyRatesHotels'] : 0;

            $getAgencyMappingData = $TblAgency->getAgencyMappingData($agencySysId);
            $IsGTXNetworkWeb = isset($getData['IsGTXNetworkWeb']) ? $getData['IsGTXNetworkWeb'] : 0;
            if ($IsGTXNetworkWeb == 0) {
                $networkArray = array(
                    "IsWeb" => 0,
                    "IsActive" => 0,
                    "IsMarkForDel" => 1
                );
                $tpsysIdArray = array(
                    "IsGTXNetworkWeb" => 0
                );
                $TblAgency->updateData('TB_TravelPlan_Mapping_Network_Web', $networkArray, array('AgencySysId =?' => $agencySysId));
                $TblAgency->updateData('TB_TravelPlan', $tpsysIdArray, array('AgencySysId =?' => $agencySysId));
            }
            try {
                if ($getAgencyMappingData) {
                    $TblAgency->updateData('TB_Agency_Mapping', $agencyMappingArray, ['AgencySysId =?' => $agencySysId]);
                } else {
                    $agencyMappingArray['AgencySysId'] = $agencySysId;
                    $agencyMappingArray['IsSourceWise'] = 0;
                    $agencyMappingArray['IsDestinationWise'] = 0;
                    $agencyMappingArray['B2BGreetingMessage'] = ' ';
                    $agencyMappingArray['IsB2CGreetingMessage'] = 0;
                    $agencyMappingArray['IsB2BGreetingMessage'] = 0;
                    $agencyMappingArray['IsAadharVerified'] = 0;
                    $agencyMappingArray['IsEnabledB2CWallet'] = 0;
                    $agencyMappingArray['IsPANVerified'] = 0;
                    $agencyMappingArray['IsGSTVerified'] = 0;
                    $TblAgency->insertData('TB_Agency_Mapping', $agencyMappingArray);
                }
            } catch (Zend_Exception $e) {
                echo $message = $e->getMessage();
                die;
            }
            if (isset($getData['IsGTXNetworkWeb']) && $getData['IsGTXNetworkWeb'] == 1) {
                $totalIsGTXNetworkWeb = (isset($getData['totalIsGTXNetworkWeb']) && !empty($getData['totalIsGTXNetworkWeb'])) ? $getData['totalIsGTXNetworkWeb'] : 0;
                for ($i = 1; $i <= $totalIsGTXNetworkWeb; $i++) {
                    $AgencyDistributionData = $obEmail->checkAgencyDistributionData($agencySysId, $i);
                    if (!empty($AgencyDistributionData)) {
                        $updateAgencyData = [
                            'PerLeadCharge' => (isset($getData['gtxNetworkWebData' . $i]) && isset($getData['gtxNetworkWebDataValue'][$i - 1]) && !empty($getData['gtxNetworkWebDataValue'][$i - 1])) ? (int) $getData['gtxNetworkWebDataValue'][$i - 1] : 0,
                            'IsActive' => 1,
                            'IsMarkForDel' => isset($getData['gtxNetworkWebData' . $i]) ? 0 : 1,
                        ];
                        $whereConAgency = array("AgencySysId =?" => $agencySysId, "DisSysId =?" => $AgencyDistributionData['DisSysId']);
                        $objSubscription->updateTable("TB_Agency_Distribution", $updateAgencyData, $whereConAgency);
                    } else {
                        if (isset($getData['gtxNetworkWebData' . $i]) && $getData['gtxNetworkWebData' . $i] == 1) {
                            $insertAgencyData = [
                                'AgencySysId' => $agencySysId,
                                'RefSysId' => isset($getData['gtxNetworkWebData' . $i]) ? $i : 0,
                                'PerLeadCharge' => (isset($getData['gtxNetworkWebDataValue'][$i - 1]) && !empty($getData['gtxNetworkWebDataValue'][$i - 1])) ? (int) $getData['gtxNetworkWebDataValue'][$i - 1] : 0,
                                'IsActive' => 1,
                                'IsMarkForDel' => isset($getData['gtxNetworkWebData' . $i]) ? 0 : 1,
                            ];
                            $objSubscription->insertTable("TB_Agency_Distribution", $insertAgencyData);
                        }
                    }
                }
            } else {
                $updateAgencyData = ['IsMarkForDel' => 1, 'PerLeadCharge' => 0];
                $whereConAgency = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency_Distribution", $updateAgencyData, $whereConAgency);
            }
            if (isset($getData['expertiseDestinationsValue']) && !empty($getData['expertiseDestinationsValue'])) {
                $updateExpertData = ['IsMarkForDel' => 1];
                $whereExpert = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency_Destination_Expert", $updateExpertData, $whereExpert);

                foreach ($getData['expertiseDestinationsValue'] as $dKey => $dVal) {

                    $insertDesData = [
                        'AgencySysId' => $agencySysId,
                        'DestinationSysId' => isset($dVal) ? (int) $dVal : 0,
                        'IsActive' => 1,
                        'IsMarkForDel' => 0,
                    ];
                    $objSubscription->insertTable("TB_Agency_Destination_Expert", $insertDesData);
                }
            }


            /* Added By Mangal For Add Suplier 04-09-2020 Start */

            $objSupplier = new Travel_Model_TblSupplier();
            $UserDataByAgency = $TblAgency->getAgencyDataById($agencySysId);

            $checkemail = $objSupplier->checkSupplierEmailExists($agencySysId, trim($UserDataByAgency['EmailId']));
            //   echo "<pre>";print_r($UserDataByAgency);die;
            $SupplierTypeArrDB = $objSupplier->getSupplierTypes();
            $SupplierServicesArrDB = $objSupplier->getSupplierServices();
            if (isset($getData['IsGTXNetworkWeb']) && $getData['IsGTXNetworkWeb'] == 1) {
                $supplierTypeMasking = $objSupplier->setMasking(['2'], $SupplierTypeArrDB, 'SupplierTypeSysId');
                $servicesMasking = $objSupplier->setMasking(['10'], $SupplierServicesArrDB, 'SupplierSerSysId');
                $suppliertypemp = 'B2B';
                $supplierservicesomp = '10';
                $currentDate = date('Y-m-d');
                $gstApplicable = 0;
                $gstScheme = NULL;
                $gstNumber = NULL;
                if ($checkemail) {
                    $SupplierSysId = isset($checkemail['SupplierSysId']) ? $checkemail['SupplierSysId'] : '';
                    $dataForDb = array(
                        'IsDelete' => 0,
                        'IsActive' => 1
                    );
                    $intLastInsertId = $objSupplier->updateSupplier($dataForDb, $SupplierSysId);
                } else {
                    $dataForDb = array(
                        'SupplierName' => $this->sanitize_data($UserDataByAgency['Title']),
                        'Salution' => isset($UserDataByAgency['Salution']) ? $UserDataByAgency['Salution'] : 1,
                        'FirstName' => $this->sanitize_data($UserDataByAgency['FirstName']),
                        'LastName' => $this->sanitize_data($UserDataByAgency['LastName']),
                        'IsCompany' => ($UserDataByAgency['Title']) ? '1' : '0',
                        'CompanyName' => $this->sanitize_data($UserDataByAgency['Title']),
                        'Services' => $servicesMasking,
                        'GstApplicable' => $gstApplicable,
                        'RegisrationScheme' => $gstScheme,
                        'GSTNo' => $gstNumber,
                        'Type' => $supplierTypeMasking,
                        'ContactPerson' => $this->sanitize_data(trim($UserDataByAgency['FirstName']) . ' ' . trim($UserDataByAgency['LastName'])),
                        'Designation' => $this->sanitize_data($UserDataByAgency['Designation']),
                        'ContactNo' => isset($UserDataByAgency['ContactNo1']) ? $UserDataByAgency['ContactNo1'] : '',
                        'EmailId' => trim($UserDataByAgency['EmailId']),
                        'CitySysId' => (int) $UserDataByAgency['CitySysId'],
                        'ContId' => (int) $UserDataByAgency['CountrySysId'],
                        'StateId' => (int) $UserDataByAgency['StateOrZoneSysId'],
                        'Expertisecountriesid' => '',
                        'OldExpertiseCountriesId' => '',
                        'Expertisedestinationsid' => '',
                        'ExpertiseStateId' => '',
                        'ExpertiseRegionId' => $UserDataByAgency['ExpertiseDestinationsId'],
                        'otherlocationcity' => 0,
                        'CategoryType' => $suppliertypemp,
                        'ServicesType' => $supplierservicesomp,
                        'address1' => $UserDataByAgency['Address'],
                        'address2' => $UserDataByAgency['SecondaryAddress'],
                        'comments' => '',
                        'Regions' => 0,
                        'UpdatedDate' => $currentDate,
                        'SupplierTypeSysId' => '0',
                        'FacilityMask' => '0',
                        'PrefCurrencyType' => '0',
                        'Address' => '0',
                        'PlaceSysId' => '0',
                        'IsCreatedByAgent' => '1',
                        'AgentSysId' => isset($UserDataByAgency['UserSysId']) ? $UserDataByAgency['UserSysId'] : '',
                        'XRefAgencySysId' => 1903, //Tripsgateway agencySysId if(1903) is master supplier
                        'CreateDate' => $currentDate,
                        'ApproveDate' => $currentDate,
                        'IsApproved' => 0,
                        'IsDelete' => 0,
                        'IsActive' => 1,
                        'countrycode' => isset($UserDataByAgency['countrycode']) ? $UserDataByAgency['countrycode'] : '+91',
                        'code_icons' => isset($UserDataByAgency['code_icons']) ? $UserDataByAgency['code_icons'] : 'in',
                        'IscheckForAllCountry' => '0',
                        'SearchString' => '',
                        'CountryNameString' => '',
                        'CityNameString' => '',
                        'IsExpertisecountriesAll' => '',
                        'SupplierAgencySysId' => $UserDataByAgency['AgencySysId']
                    );
                    // echo "<pre>";print_r($dataForDb);exit;
                    $intLastInsertId = $objSupplier->addSupplier($dataForDb);

                    $dataForDb = array(
                        'SupplierSysId' => $intLastInsertId,
                        'ProfileTitle' => $this->sanitize_data($UserDataByAgency['Designation']),
                        'Salution' => isset($UserDataByAgency['salution']) ? $UserDataByAgency['salution'] : 1,
                        'FirstName' => $this->sanitize_data($UserDataByAgency['FirstName']),
                        'LastName' => $this->sanitize_data($UserDataByAgency['LastName']),
                        'CompanyName' => $this->sanitize_data($UserDataByAgency['Title']),
                        'Services' => '', //$servicesMasking, removed as per discussion with KJ Mam
                        'ContactPerson' => $this->sanitize_data(trim($UserDataByAgency['FirstName']) . ' ' . trim($UserDataByAgency['LastName'])),
                        'Department' => 'NA',
                        'PrimaryMobile' => $UserDataByAgency['ContactNo1'],
                        'EmailId' => trim($UserDataByAgency['EmailId']),
                        'CitySysId' => (int) $UserDataByAgency['CitySysId'],
                        'CountrySysId' => (int) $UserDataByAgency['CountrySysId'],
                        'UpdateDate' => $currentDate,
                        'OtherDetails' => '',
                        'ContactType' => '0',
                        'ProfileId' => '0',
                        'LandlineNumbers' => '0',
                        'OtherContactInfo' => '0',
                        'CreateDate' => $currentDate,
                        'IsRegisterUser' => '0',
                        'Address' => '0',
                        'StateOrZoneSysId' => (int) $UserDataByAgency['StateOrZoneSysId'],
                        'ActivationDate' => $currentDate,
                        'ApprovalDate' => $currentDate,
                        'IsVarified' => '0',
                        'IsActive' => '1',
                        'IsMarkForDelete' => '0',
                        'IsApproved' => '0',
                        'IsPrimary' => 1,
                        'code_icons' => isset($UserDataByAgency['code_icons']) ? $UserDataByAgency['code_icons'] : 'in',
                        'countrycode' => isset($UserDataByAgency['countrycode']) ? $UserDataByAgency['countrycode'] : '+91',
                        'SearchString' => '',
                        'CountryNameString' => '',
                        'CityNameString' => ''
                    );
                    $SupplierContactId = $objSupplier->addSupplierContact($dataForDb);
                    $geographyRegionId = !empty($UserDataByAgency['ExpertiseDestinationsId']) ? explode(',', geographyRegionId) : array();
                    if (!empty($geographyRegionId)) {
                        $objLocation->addSupplierDestinationMappingData($geographyRegionId, $intLastInsertId, $SupplierContactId);
                    }
                    $datacontactcity = array(
                        'SupplierContactId' => $SupplierContactId,
                        'SupplierSysId' => $intLastInsertId,
                        'CitySysId' => (int) $UserDataByAgency['CitySysId'],
                        'CountrySysId' => (int) $UserDataByAgency['CountrySysId'],
                        'UpdateDate' => $currentDate,
                        'CreateDate' => $currentDate,
                        'IsActive' => '1',
                        'IsMarkForDelete' => '0'
                    );
                    $objSupplier->addSupplierContactCity($datacontactcity);
                    // $json = array('success' => true, 'msg' => 'Add supplier successfully.', 'id' => $intLastInsertId);
                    // echo json_encode($json);
                    // exit;
                }
            } else {
                if ($checkemail) {
                    $SupplierSysId = isset($checkemail['SupplierSysId']) ? $checkemail['SupplierSysId'] : '';
                    $dataForDb = array(
                        'IsDelete' => 1,
                        'IsActive' => 0,
                    );
                    $intLastInsertId = $objSupplier->updateSupplier($dataForDb, $SupplierSysId);
                }
            }
            /* Added By Mangal For Add Suplier 04-09-2020 End */



            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function saveGtxpgSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $obEmail = new Travel_Model_TblInsurance();
            $agencyEmailSettingArray = array();
            $agencyEmailSettingArray['IsGTXPaymentGateway'] = !empty($getData['is-email-setting']) ? $getData['is-email-setting'] : 0;
            $dbArr = $obEmail->addEmailSetting('TB_Agency', $agencyEmailSettingArray, ['AgencySysId =?' => $agencySysId]);
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function saveB2cUrlSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $objB2CUrlSetting = new Travel_Model_TblInsurance();
            $agencyB2CUrlSettingArray = array();
            $agencyB2CUrlSettingArray['IsB2CUrl'] = !empty($getData['is-b2c-setting']) ? $getData['is-b2c-setting'] : 0;
            $agencyB2CUrlSettingArray['B2CUrl'] = !empty($getData['b2cUrl']) ? $getData['b2cUrl'] : "";
            $dbArr = $objB2CUrlSetting->addEmailSetting('TB_Agency', $agencyB2CUrlSettingArray, ['AgencySysId =?' => $agencySysId]);
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function saveB2cSiteAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            // echo "<pre>";print_r($getData);die("");
            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $objB2CUrlSetting = new Travel_Model_TblInsurance();
            $permissionModel = new Travel_Model_TblPermission();
            $agencyB2CUrlSettingArray = array();
            $agencyMappingData = $objB2CUrlSetting->getAgencyMappingData('TB_Agency_WebSite_Mapping', ['*'], ['AgencySysId' => $agencySysId]);

            if (isset($agencyMappingData) && !empty($agencyMappingData)) {

                $permissionModel->deleteData("TB_Agency_WebSite_Mapping", ['AgencySysId =? ' => $agencySysId]);
            }
            if (isset($getData['IsGTXNetwork']) && $getData['IsGTXNetwork'] == 1) {

                for ($m = 0; $m < $getData['noofWebsite']; $m++) {
                    $mn = $m + 1;
                    $insertData = [
                        'AgencySysId' => (int) $agencySysId,
                        'IsSSL' => !empty($getData['is-b2c-site'][$m]) ? $getData['is-b2c-site'][$m] : 0,
                        'URL' => !empty($getData['Url'][$m]) ? $getData['Url'][$m] : "",
                        'IsSiteType' => !empty($getData['siteType'][$m]) ? $getData['siteType'][$m] : 0,
                        'IsMaster' => (isset($getData['masterUrlIndex']) && $getData['masterUrlIndex'] == $mn) ? 1 : 0,
                        'IsActive' => 1,
                        'IsMarkForDel' => 0,
                    ];
                    // echo print_r($insertData); die;
                    $permissionModel->insertData("TB_Agency_WebSite_Mapping", $insertData);

                    if (isset($getData['masterUrlIndex']) && $getData['masterUrlIndex'] == $mn) {
                        $agencyB2CUrlSettingArray['IsSSL'] = !empty($getData['is-b2c-site'][$m]) ? $getData['is-b2c-site'][$m] : 0;
                        $agencyB2CUrlSettingArray['Url'] = !empty($getData['Url'][$m]) ? $getData['Url'][$m] : "";
                        $agencyB2CUrlSettingArray['IsSiteType'] = !empty($getData['siteType'][$m]) ? $getData['siteType'][$m] : 0;
                        $agencyB2CUrlSettingArray['IsB2CSite'] = !empty($getData['IsGTXNetwork']) ? $getData['IsGTXNetwork'] : 0;
                        $dbArr = $objB2CUrlSetting->addEmailSetting('TB_Agency', $agencyB2CUrlSettingArray, ['AgencySysId =?' => $agencySysId]);
                    }
                }
            } else if (isset($getData['IsGTXNetwork']) && $getData['IsGTXNetwork'] == 2) {
                $agencyB2CUrlSettingArray['IsSSL'] = 0;
                $agencyB2CUrlSettingArray['Url'] = !empty($getData['Url'][0]) ? $getData['Url'][0] : "";
                $agencyB2CUrlSettingArray['IsB2bSSL'] = 0;
                $agencyB2CUrlSettingArray['IsB2bSiteURL'] = !empty($getData['Url'][0]) ? $getData['Url'][0] : "";
                $agencyB2CUrlSettingArray['IsSiteType'] = !empty($getData['IsSiteType'][0]) ? $getData['IsSiteType'][0] : 0;
                $agencyB2CUrlSettingArray['IsB2CSite'] = !empty($getData['IsGTXNetwork']) ? $getData['IsGTXNetwork'] : 0;
                $dbArr = $objB2CUrlSetting->addEmailSetting('TB_Agency', $agencyB2CUrlSettingArray, ['AgencySysId =?' => $agencySysId]);
            } else {
                $agencyB2CUrlSettingArray['IsSSL'] = 0;
                $agencyB2CUrlSettingArray['Url'] = '';
                $agencyB2CUrlSettingArray['IsSiteType'] = 0;
                $agencyB2CUrlSettingArray['IsB2CSite'] = !empty($getData['IsGTXNetwork']) ? $getData['IsGTXNetwork'] : 0;
                $dbArr = $objB2CUrlSetting->addEmailSetting('TB_Agency', $agencyB2CUrlSettingArray, ['AgencySysId =?' => $agencySysId]);
            }




            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    // ADDED BY SNDEEP NEGI 17-03-2021//
    public function updateTotalNoemailAction() {
        $this->_helper->layout->disableLayout();
        $leadupdate = new Travel_Model_TblLead();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $param = $this->getRequest()->getParams();
            $finalTotalEmail = $param['finalTotalEmail'];
            if (!empty($param['AgencySysId'])) {
                $where = array("AgencySysId=?" => $param['AgencySysId']);
                $saveArr = ['TotalEmail' => $finalTotalEmail];
                $result = $leadupdate->updateTable("TB_Agency_Marketing_Wallet", $saveArr, $where);
                //    echo "<pre>"; print_r($result); die;
                if ($result == 0) {
                    $getDataByAgency = $leadupdate->getDetaByAgencysysid("TB_Agency_Marketing_Wallet", $param['AgencySysId']);
                    if ($getDataByAgency == 0) {
                        $data = [
                            'AgencySysId' => $param['AgencySysId'],
                            'TotalEmail' => $param['finalTotalEmail'],
                            'PerEmailPrice' => '0.06',
                            'CreateDate' => date("Y-m-d"),
                            'UpdateDate' => date("Y-m-d"),
                            'IsMarkForDel' => 0,
                            'IsActive' => 1,
                        ];
                        $result = $leadupdate->insertTable("TB_Agency_Marketing_Wallet", $data);
                        //  echo "<pre>"; print_r($result); die("insert");
                    }
                    //   echo "<pre>"; print_r($countrows_Agency); die("null ");
                }
            }
            echo json_encode(array('status' => true, 'TotalEmail' => $finalTotalEmail, 'AgencySysId' => $param['AgencySysId']));
        }

        exit;
    }

    // ADDED BY SNDEEP NEGI 17-03-2021 END//

    public function saveB2bSiteAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = trim($getData['agencySysId']);
            $date = new Zend_Date();
            $createDate = $date->get('yyyy-MM-dd HH:mm:ss');
            $objB2BUrlSetting = new Travel_Model_TblInsurance();
            $agencyB2BUrlSettingArray = array();
            $agencyB2BUrlSettingArray['IsB2bSSL'] = !empty($getData['is-b2b-site']) ? $getData['is-b2b-site'] : 0;
            $agencyB2BUrlSettingArray['IsB2bSiteURL'] = !empty($getData['Url']) ? $getData['Url'] : "";
            $agencyB2BUrlSettingArray['IsB2bSite'] = !empty($getData['is-b2b-site-status']) ? $getData['is-b2b-site-status'] : 0;
            $dbArr = $objB2BUrlSetting->addEmailSetting('TB_Agency', $agencyB2BUrlSettingArray, ['AgencySysId =?' => $agencySysId]);
            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    /* Added by Piyush Tiwari End */

    public function queryAgencyWiseAction() {
        $queryagencyModel = new Travel_Model_TblLead();
        $queryAgencyWiseListArray = $queryagencyModel->getQueryAgencyWiseList();
        //echo "<pre>";print_r($queryAgencyWiseListArray);die;
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($queryAgencyWiseListArray);
        $paginator->setItemCountPerPage($this->GRID_PER_PAGE_RECORD_COUNT);
        $paginator->setCurrentPageNumber($page);

        $this->view->paginator = $paginator;
        $this->view->GRID_PER_PAGE_RECORD_COUNT = $this->GRID_PER_PAGE_RECORD_COUNT;
        $this->view->page = $page;

        //        $this->view->queryAgencyWiseListArray = $paginator;
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
        //$this->view->controller    = $this;        
    }

    public function proposalQueryAction() {
        $proposalQueryModel = new Travel_Model_TblLead();
        $proposalQueryListArray = $proposalQueryModel->getProposalQueryList();
        //echo "<pre>";print_r($proposalQueryListArray);die;
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($proposalQueryListArray);
        $paginator->setItemCountPerPage($this->GRID_PER_PAGE_RECORD_COUNT);
        $paginator->setCurrentPageNumber($page);

        $this->view->paginator = $paginator;
        $this->view->GRID_PER_PAGE_RECORD_COUNT = $this->GRID_PER_PAGE_RECORD_COUNT;
        $this->view->page = $page;

        //        $this->view->proposalQueryListArray = $paginator;
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
        //$this->view->controller    = $this;        
    }

    public function exportExcelQueryAgencyWiseAction() {
        $queryagencyModel = new Travel_Model_TblLead();
        $queryAgencyWiseListArray = $queryagencyModel->getQueryAgencyWiseList();

        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($queryAgencyWiseListArray);
        $paginator->setItemCountPerPage(5000);
        $paginator->setCurrentPageNumber($page);
        $arrFieldValue = array();
        $sheetTitle = "Query Agency Wise Data";
        $arrFieldLabel = array('Agency Name ', 'Total', '');
        $counter = 0;
        if ($paginator) {
            foreach ($paginator as $key => $queryAgencyWiseList) {

                $arrFieldValue[$counter]['DisplayName'] = $queryAgencyWiseList['DisplayName'];
                $arrFieldValue[$counter]['Totalcount'] = $queryAgencyWiseList['Totalcount'] . ' ';
                //              echo "<pre>";print_r($queryAgencyWiseList);
                $counter++;
            }
        }

        Zend_Controller_Action_HelperBroker::getStaticHelper("CreateExcel")->exportToExcel($sheetTitle, $arrFieldLabel, $arrFieldValue);
        exit;
    }

    public function exportProposalQueryAction() {
        $proposalQueryModel = new Travel_Model_TblLead();
        $proposalQueryListArray = $proposalQueryModel->getProposalQueryList();

        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($proposalQueryListArray);
        $paginator->setItemCountPerPage(5000);
        $paginator->setCurrentPageNumber($page);
        $arrFieldValue = array();
        $sheetTitle = "Proposal Query Data";
        $arrFieldLabel = array('Agency Name ', 'Total', '');
        $counter = 0;
        if ($paginator) {
            foreach ($paginator as $key => $proposalQueryList) {

                $arrFieldValue[$counter]['DisplayName'] = $proposalQueryList['DisplayName'];
                $arrFieldValue[$counter]['Totalcount'] = $proposalQueryList['Totalcount'] . ' ';
                $counter++;
            }
        }
        //            echo "<pre>";print_r($arrFieldValue);die;
        Zend_Controller_Action_HelperBroker::getStaticHelper("CreateExcel")->exportToExcel($sheetTitle, $arrFieldLabel, $arrFieldValue);
        exit;
    }

    public function saveApiSettingsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            // echo "<pre>";print_r($getData);die;
            $APISourceSysId = $getData['APISourceSysId'];
            $agencySysId = trim($getData['agencySysId']);
            $obEmail = new Travel_Model_TblInsurance();
            $objSubscription = new Subscription_Model_Subscription();
            $agencyEmailSettingArray = $APISysId = $masterAPISourceArr = array();
            $masterAPISource = $obEmail->getMasterAPISource();
            // echo "<pre>"; print_r($masterAPISource); die;
            foreach ($masterAPISource as $mKey => $mVal) {
                $masterAPISourceArr[] = $mVal['APISourceSysId'];
                $result = $obEmail->checkAgencyAPISource($agencySysId, $mVal['APISourceSysId']);
                //    echo "<pre>";print_r($result);die;

                if (!empty($result)) {
                    if (in_array($result['APISourceSysId'], $APISourceSysId)) {
                        $updateAgencyData = array('IsMarkForDel' => 0);
                        $whereConAgency = array("AgencySysId =?" => $agencySysId, "APISysId =?" => $result['APISysId'], "APISourceSysId =?" => $result['APISourceSysId']);
                        $objSubscription->updateTable("TB_Agency_API", $updateAgencyData, $whereConAgency);
                    } else {
                        $updateAgencyData = array('IsMarkForDel' => 1);
                        $whereConAgency = array("AgencySysId =?" => $agencySysId, "APISourceSysId =?" => $result['APISourceSysId']);
                        $objSubscription->updateTable("TB_Agency_API", $updateAgencyData, $whereConAgency);
                    }
                } else {
                    if (in_array($mVal['APISourceSysId'], $APISourceSysId)) {
                        $insertAgencyData = [
                            'AgencySysId' => $agencySysId,
                            'APISourceSysId' => $mVal['APISourceSysId'],
                            'IsActive' => 1,
                            'IsMarkForDel' => 0,
                        ];
                        $objSubscription->insertTable("TB_Agency_API", $insertAgencyData);
                    }
                }
            }
            //            if(!empty($APISourceSysId)){
            //                foreach($APISourceSysId as $key => $val){
            //                    $updateAgencyData = [
            //                        'IsActive'=>1,
            //                        'IsMarkForDel'=>0,
            //                    ];
            //                    $whereConAgency = array("AgencySysId =?" => $agencySysId,"APISourceSysId =?" => $val);
            //                    $objSubscription->updateTable("TB_Agency_API", $updateAgencyData, $whereConAgency);
            //                    
            //                }
            //            }


            $json = array('result' => 1);
            echo json_encode($json);
            exit;
        }
    }

    public function refreshAdminDashboardAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $proMdl = new Gtxwebservices_Model_Procedures();
            $proMdl->getSuperAdminBIData();
        }
        $json = array('result' => 1);
        echo json_encode($json);
        exit;
    }

    public function exportExcelAgenciesListAction() {
        $leadModel = new Travel_Model_TblLead();
        $searchArr = array();
        $getData = array();
        if ($this->getRequest()->isPost()) {
            $proMdl = new Gtxwebservices_Model_Procedures();
            $proMdl->getSuperAdminBIData();
            $getData = $this->getRequest()->getPost();
            $searchArr = array(
                "IsActive" => 1
            );
            $leadModel->searchArr = $searchArr;
            $this->view->searchArr = $searchArr;
            $leadListArray = $leadModel->getLeadListNew(1);
            $sheetTitle = "Agency Data";
            $arrFieldValue = array();
            $proposalArray = $loggedInArray = array();
            for ($i = 0; $i < 7; $i++) {
                $loggedInArray[$i] = "LoggenIN-" . strtoupper(date('D', strtotime("-$i days")));
                $proposalArray[$i] = "Proposal-" . strtoupper(date('D', strtotime("-$i days")));
            }
            $hhh = array_merge($loggedInArray, $proposalArray);
            $arrFieldLabel1 = array(
                'Agency Id', 'Company Name', 'Location', 'Name', 'Email Id', 'Phone Number', 'Total Email', 'Balance', 'RM', 'Date Of Registration', 'Status'
            );
            $arrFieldLabel = array_merge($arrFieldLabel1, $hhh);
            foreach ($leadListArray as $key => $val) {
                $BalanceAmount = Zend_Controller_Action_HelperBroker::getStaticHelper('General')->number_format_indian($val['BalanceAmount']);
                $address = ucfirst(trim($val['CityName'])) . ', ' . ucfirst(trim($val['Country']));
                $arrFieldValue[$key]['AgencySysId'] = $val['AgencySysId'];
                $arrFieldValue[$key]['Title'] = trim($val['Title']);
                $arrFieldValue[$key]['CityName'] = !empty($val['CityName']) ? trim($address) : 'NA';
                $arrFieldValue[$key]['PrimaryContactName'] = trim($val['PrimaryContactName']);
                $arrFieldValue[$key]['EmailId'] = trim($val['EmailId']);
                $arrFieldValue[$key]['PrimaryContactNo'] = trim($val['PrimaryContactNo']);
                $arrFieldValue[$key]['TotalEmail'] = ($val['TotalEmail'] > 0) ? $val['TotalEmail'] : 0;
                $arrFieldValue[$key]['BalanceAmount'] = ($val['BalanceAmount'] > 0) ? trim($val['Symbol']) . ' ' . $BalanceAmount : (int) $BalanceAmount;
                $arrFieldValue[$key]['UserName'] = !empty($val['UserName']) ? ucfirst(trim($val['UserName'])) : 'NA';
                $arrFieldValue[$key]['CreateDate'] = $val['CreateDate']->format('d-m-Y');
                $arrFieldValue[$key]['IsApproved'] = $val['IsApproved'] == 1 ? 'Approved' : 'Not Approved';
                $arrFieldValue[$key]['LDayOne'] = $val['LDayOne'];
                $arrFieldValue[$key]['LDayTwo'] = $val['LDayTwo'];
                $arrFieldValue[$key]['LDayThree'] = $val['LDayThree'];
                $arrFieldValue[$key]['LDayFour'] = $val['LDayFour'];
                $arrFieldValue[$key]['LDayFive'] = $val['LDayFive'];
                $arrFieldValue[$key]['LDaySix'] = $val['LDaySix'];
                $arrFieldValue[$key]['LDaySeven'] = $val['LDaySeven'];
                $arrFieldValue[$key]['PDayOne'] = $val['PDayOne'];
                $arrFieldValue[$key]['PDayTwo'] = $val['PDayTwo'];
                $arrFieldValue[$key]['PDayThree'] = $val['PDayThree'];
                $arrFieldValue[$key]['PDayFour'] = $val['PDayFour'];
                $arrFieldValue[$key]['PDayFive'] = $val['PDayFive'];
                $arrFieldValue[$key]['PDaySix'] = $val['PDaySix'];
                $arrFieldValue[$key]['PDaySeven'] = $val['PDaySeven'];
            }
            //echo "<pre>";print_r($arrFieldValue); exit;
            Zend_Controller_Action_HelperBroker::getStaticHelper("CreateExcel")->exportToExcel($sheetTitle, $arrFieldLabel, $arrFieldValue);
            exit;
        }
    }

    public function ismarkfordeleteAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $objSubscription = new Subscription_Model_Subscription();
        $agencySysId = (int) $this->getRequest()->getParam('id');
        if (!empty($agencySysId) && ($agencySysId > 0)) {
            $updateDataOfAgency = array(
                'IsMarkForDelete' => 1,
                'IsApproved' => 0,
            );
            $whrAgencyCon = array("AgencySysId =?" => $agencySysId);
            $objSubscription->updateTable("TB_Agency", $updateDataOfAgency, $whrAgencyCon);
            $message = "Agency deleted successfully";
            $this->_helper->flashMessenger->addMessage($message);
            $this->_helper->redirector('list', 'lead');
        }
    }

    public function updateRmAction() {
        $leadModel = new Travel_Model_TblLead();
        $objSubscription = new Subscription_Model_Subscription();
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getParams();
            $agencySysId = (int) $getData['AgencySysId'];
            $RM = (int) $getData['RM'];
            $getRm = $leadModel->getRelationshipMgr($agencySysId);
            if (!empty($getRm)) {
                $updateDataOfAgency = array(
                    'RelationalManager' => $RM,
                );
                $whrAgencyCon = array("AgencySysId =?" => $agencySysId);
                $objSubscription->updateTable("TB_Agency_RelationshipMgr", $updateDataOfAgency, $whrAgencyCon);
                $json = array('status' => true);
                echo json_encode($json);
                exit;
            } else {
                $json = array('status' => false);
                echo json_encode($json);
                exit;
            }
        }
    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit