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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

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

/**
 * Class PackageController
 *
 * @name		PackageController
 * @author		Prashant Kr Gupta
 * @version 	1.0
 * @copyright 	Catabatic India Pvt Ltd
 * Handle Package Related function
 *
 */
class PublicPackageController extends Catabatic_ValidateCustomer {

    const ADMIN_ID = 1;
    const CONST_SOURCE_ADMIN = 3;

    private $intLoggedinUserId = '';
    private $intLoggedinUserGroupSysId = '';
    private $intLoggedinUserAgencySysId = '';
    private $intLoggedinUserTrxCurrency = '';
    public $baseUrl;
    public $smtpUserName;
    public $smtpPassword;
    public $smtpPort;
    public $smtpHost;
    private $fromEmail;
    private $fromName;
    private $SMSURL;
    private $SMSMETHOD;
    private $SMSAPIKEY;
    private $SMSSENDER;
    private $SMSFORMAT;
    private $BITLYLOGIN;
    private $BITLYAPIKEY;
    public $_crmcusttravelplan;

    public function init() {
        // error_reporting('E_ALL');
        $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
        $this->smtpUserName = $aConfig['smtpUserName'];
        $this->smtpPassword = $aConfig['smtpPassword'];
        $this->smtpPort = $aConfig['smtpPort'];
        $this->smtpHost = $aConfig['smtpHost'];
        $this->fromEmail = $aConfig['fromEmail'];
        $this->fromName = $aConfig['fromName'];
        $this->SMSURL = Catabatic_Helper::getSMSURL();
        $this->SMSMETHOD = Catabatic_Helper::getSMSMETHOD();
        $this->SMSAPIKEY = Catabatic_Helper::getSMSAPIKEY();
        $this->SMSSENDER = Catabatic_Helper::getSMSSENDER();
        $this->SMSFORMAT = Catabatic_Helper::getSMSFORMAT();
        $this->BITLYLOGIN = 'gpurwar';
        $this->BITLYAPIKEY = 'R_c1c94b5c789249d5a59d585bc0e7ef80';
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $this->baseUrl = $request->getScheme() . '://' . $request->getHttpHost();
    }

    public function getPackageRateAction() {
        //$intLoggedinUserAgencySysId     = 	$this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $packid = @$_REQUEST['packid'];
        $travelers = @$_REQUEST['travelers'];
        $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripdate'])));
        $packRate = $objPackage->getPackMPRate($packid, $travelers, $tripdate);
        $CostPPSO = @$packRate[0]['CostPPSO'];
        $CostPPDO = (@$packRate[0]['CostPPDO'] * 2);
        $CostPPTO = (@$packRate[0]['CostPPTO'] * 3);
        $CostExtraBed = @$packRate[0]['CostExtraBed'];
        $CostChildWithoutBed = @$packRate[0]['CostChildWithoutBed'];
        if (@$packRate[0]['Tax'] == 'Excluded') {
            $ExcludedPercent = @$packRate[0]['ExcludedPercent'];
        }
        $adultcost = '0';
        $childcost = '0';
        for ($d = 1; $d <= @$_REQUEST['roomlp']; $d++) {
            $rmadlt = '';
            $rmchld = '';
            $rmadlt = @$_REQUEST['adult_' . @$d];
            $rmchld = @$_REQUEST['child_' . @$d];
            $extrabed = @$_REQUEST['extrabed_' . @$d];
            if ($rmadlt == '3') {
                $adultcost = $adultcost + $CostPPTO;
            } elseif ($rmadlt == '2') {
                $adultcost = $adultcost + $CostPPDO;
            } else {
                $adultcost = $adultcost + $CostPPSO;
            }
            if ($extrabed == 'extrabed') {
                $extrabedcost = @$extrabedcost + @$CostExtraBed;
            }
            if ($extrabed == 'withoutbed') {
                $withoutbedcost = @$withoutbedcost + @$CostChildWithoutBed;
            }
        }
        $totalcost = @$adultcost + @$extrabedcost + @$withoutbedcost;
        if (@$ExcludedPercent > 0) {
            $totalcost = @$totalcost + round((@$totalcost * @$ExcludedPercent) / 100);
        }
        echo $totalcost;
        exit;
    }

    public function customerviewAction() {

        $this->_helper->layout->disableLayout();
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $tpID = base64_decode($this->getRequest()->getParam('id'));
        $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
        $this->view->flexiPackageItenList = $flexiPackageItenList;
        $termscond = $objPackage->getTermCond($tpID);
        $agencyTncList = $objPackage->getCustomerTnCDetails($tpID);
        $this->view->agencyTncList = $agencyTncList;
        $this->view->termc = $termscond;
        //echo $this->getRequest()->getParam('id');		
        if ($tpID > 0) {
            $getitenryID = $objPackage->GetTravelPlanItenaryID($tpID);
            $itenararray = array();
            for ($i = 0; $i < count($getitenryID); $i++) {
                $itenararray[] = "'" . $getitenryID[$i]['TPIntSysId'] . "'";
            }

            $implodeitenary = implode(",", $itenararray);

            $gettotalhotelcount = $objPackage->GetAllTotalHotelCount($implodeitenary);
            $getselectedHotel = $objPackage->GetAllSelectedHotelCount($implodeitenary);
            $this->view->totalhotelcount = count($gettotalhotelcount);

            $getflightcount = $objPackage->GetFlightCount($implodeitenary);
            $this->view->totalflightcount = $getflightcount;

            $getactivitycount = $objPackage->GetActivityCount($implodeitenary);

            $this->view->totalactivitycount = count($getactivitycount);

            $getactivitycount = $objPackage->GetActivityCount($implodeitenary);
            $gettransportoption = $objPackage->GetTransPortOption($tpID);
            //echo count($gettransportoption);
            $totaltransport = count($gettransportoption);
            $this->view->totaltransport = $totaltransport;
            $this->view->totalactivitycount = count($getactivitycount);

            $this->view->implodeitenary = $implodeitenary;
            $getsightseeincount = $objPackage->GetSightSeeingByItenaryCount($implodeitenary);
            $this->view->totalsightseeingcount = count($getsightseeincount);
            //$this->view->hotelCount = count($getselectedHotel);
            $flightitenarydata = $objPackage->GetFlightItenaryWise($implodeitenary);
            //  $hotelcount = $objPackage->GetAllSelectedHotel($implodeitenary);
            $this->view->itenarydata = $itenararray;
            $this->view->flightitenarydata = $flightitenarydata;
            $flexiPackageList = $objPackage->getCustPackageList($tpID);
            $this->view->flexiPackageList = $flexiPackageList;

            ###$flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
            ###$this->view->flexiPackageItenList = $flexiPackageItenList;
            //Get Package Places 
            ###$flexiPackagePlaces = $objPackage->getCustomerPackagePlacesListBYO($implodeitenary);
            ###$this->view->flexiPackagePlaces = $flexiPackagePlaces;
            //Get Package Activity
            ####$flexiPackageActivityList = $objPackage->getCustTravelPackageActivityList($implodeitenary);
            ####$this->view->flexiPackageActivityList = $flexiPackageActivityList;
            //Get Package Sightseen
            ####$flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
            ####$this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            // echo count($flexiPackageSightseenList);
            //Get Package Hotels
            $flexiPackageHotelsList = $objPackage->getCustPackageHotelsListBYO($implodeitenary);

            $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;

            //Get Package Flight
            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            $this->view->flexiPackageFlight = $flexiPackageFlight;

            ########## Code Added By Shobhit ##################

            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->view->tpID = $tpID;
            $getcustomerDetail = $this->_crmcusttravelplan->GetTravelPlanDetailsofCustomer($tpID);
            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
            $checkCustomerChatExist = $getcustomerDetail[0]['CustomerSysId'] > 0 ? $objAgencyUser->CheckCustomerMsgCount($getcustomerDetail[0]['CustomerSysId'], $tpID) : array();
            $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            $getcustomerDetail['userChatExist'] = count($checkCustomerChatExist);

            //query for get customer chat history
            $chatSenderDetails = array();
            if ($getcustomerDetail['userChatExist'] > 0) {
                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                    $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'DESC');
                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
                    $chatSenderDetails['TPSysId'] = $tpID;
                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
                    $chatSenderDetails['EmailId'] = $getcustomerDetail[0]['EmailId'];
                }
            }
            $this->view->chatSenderDetails = $chatSenderDetails;
            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $getversiondetails;
        }
    }

    public function viewCustomerProposalAction() {
        $this->_helper->layout->disableLayout();
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $tpID = base64_decode($this->getRequest()->getParam('id'));
        //echo $this->getRequest()->getParam('id');		
        if ($tpID > 0) {

            $flexiPackageList = $objPackage->getCustPackageList($tpID);
            $packageTncList = $objPackage->getCustPackageTncList($tpID);
            $flexiPackageList['tncDetails'] = $packageTncList;

            //for agency details
            $crmcustomerObj = new Travel_Model_CRM_Customer();

            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
            $agencyObj = new Travel_Model_TblAgency();
            $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
            $flexiPackageList['agencyDetails'] = $getAgencyDetail;
            $inclusionMastArray = $objPackage->getPackageInclusionList();
            //						echo "<pre>";print_r($getAgentDetail['FirstName']);die;
            $inclusionArr = $objPackage->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
            $flexiPackageList['inclusionDetails'] = $inclusionArr;
            $this->view->flexiPackageList = $flexiPackageList;

            $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotels($flexiPackageList['TPSysId']); // for only hotel overview
            $this->view->hotelarr = $hotelarr;
            //echo "<pre>";print_r($flexiPackageList);die;

            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;

            $objCity = new Travel_Model_TblCity();
            $this->view->cityMainDetail = $objCity->getCityImagesDetailsById($flexiPackageItenList[0]['PlaceSysId'], 1, 1);

            //Get Package Activity
            if ($flexiPackageList['PackSpecType'] == 2) {
                $resflexiPackageActivityOnlyHotel = $objPackage->getCustPackageActivityListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageActivityList = $resflexiPackageActivityOnlyHotel;
                $resflexiPackageSSOnlyHotel = $objPackage->getCustPackageSightseenListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageSightseenList = $resflexiPackageSSOnlyHotel;
            } else {
                $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
                $this->view->flexiPackageActivityList = $flexiPackageActivityList;
                //Get Package Sightseen
                $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
                $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            }

            //Get Package Hotels
            $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID);
            $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;

            //Get Package Flight
            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            $this->view->flexiPackageFlight = $flexiPackageFlight;

            $termscond = $objPackage->getTermCond($tpID);
            $this->view->termc = $termscond;

            $objAgency = new Travel_Model_TblAgency();
            $agencyData = $objAgency->getAgencyDataById($flexiPackageList['AgencySysId']);
            $this->view->getAgencyData = $agencyData;

            ########## Code Added By Shobhit ##################
            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->view->tpID = $tpID;
            $getcustomerDetail = $this->_crmcusttravelplan->GetTravelPlanDetailsofCustomer($tpID);
            $getcustomerDetail[0]['AgentName'] = $getAgentDetail['FirstName'] . ' ' . $getAgentDetail['LastName'];
            $getcustomerDetail[0]['AgentNo'] = $getAgentDetail['ContactNo1'];
            //                        echo '<pre>'; print_r($getcustomerDetail);echo '</pre>';
            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
            $checkCustomerChatExist = (@$getcustomerDetail[0]['CustomerSysId'] > 0) ? $objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID) : array();

            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            if ($flexiPackageList['MasterTPSysId'] == '0') {
                $childpackarr = $objCusttravelplan->GetVersionInfo($tpID);
            } else {
                $childpackarr = $objCusttravelplan->GetVersionInfo($flexiPackageList['MasterTPSysId']);
            }
            //                       $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            $getcustomerDetail['userChatExist'] = count($checkCustomerChatExist);
            //  $this-view->getCustomerDetails = $getcustomerDetail;
            //query for get customer chat history
            $chatSenderDetails = array();
            if ($getcustomerDetail['userChatExist'] > 0) {
                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                    $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'DESC');
                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
                    $chatSenderDetails['TPSysId'] = $tpID;
                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
                    //$chatSenderDetails['EmailId']=$getcustomerDetail[0]['EmailId'];
                    $objAgencyStaff = new Travel_Model_TblAgencyStaff();
                    $agentDetail = $objAgencyStaff->getUserDetailsById($flexiPackageList['AgentSysId']);
                    $chatSenderDetails['EmailId'] = $agentDetail['EmailId'];
                    //print_r($agentDetail);
                }
            }
            //end of customer chat history
            //echo "<pre>";print_r($getcustomerDetail);die;
            //  $this-view->getCustomerDetails = $getcustomerDetail;

            $this->view->chatSenderDetails = $chatSenderDetails;

            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $childpackarr;
        }
    }

    public function getCustomerPackageRateAction() {
        //$intLoggedinUserAgencySysId     = 	$this->intLoggedinUserAgencySysId;
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $objPackage = new Travel_Model_TblPackage();
        $type = $this->getRequest()->getParam('type');
        $packid = @$_REQUEST['packid'];
        $travelers = @$_REQUEST['travelers'];
        $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripdate'])));
        //        $packMPRate = $objPackage->getCustPackRate($packid, $travelers, $tripdate);
        //        $packRate = $objCust->getCustTravelPackRate($packid, $tripdate);
        $flexiPackageList = $objPackage->getCustPackageList($packid);

        $objCust = new Travel_Model_CRM_CustomerTravelPlan();
        //        $travelPlanDetails = $objCust->GetTravelPlanDetailsofCustomer($packid);
        $IsB2BCustomer = isset($flexiPackageList['IsB2BProposal']) ? $flexiPackageList['IsB2BProposal'] : 0;
        $IsGTXNetwork = isset($flexiPackageList['IsGTXNetwork']) ? $flexiPackageList['IsGTXNetwork'] : 0;
        if ($IsB2BCustomer == 1 || $IsGTXNetwork == 1) {
            $MarketPlaceId = 2;
        } else {
            $MarketPlaceId = 1;
        }
        $packRate = $objCust->getCustTravelPackRate($packid, $tripdate, $MarketPlaceId);
        //        print_r($_REQUEST);;
        // echo "<pre>";print_r($flexiPackageList);exit;

        $rominfojson = json_decode($flexiPackageList['RoomInfoJson'], 1);

        $paxCount = array_sum((array_column($rominfojson, 'Adult')));
        //echo "<pre>";print_r($flexiPackageList);exit;
        if ($flexiPackageList['PackSpecType'] == '1' || $flexiPackageList['PackSpecType'] == '2') {
            $packRate = $objCust->getCustTravelPackRateRowWise($packid, $tripdate, $MarketPlaceId, $paxCount);
            $packMPRate = $objCust->getCustPackRateRowWise($packid, $tripdate, $MarketPlaceId, $paxCount);
            // echo "<pre>";print_r($packRate);exit('here');
        } else {
            $packRate = $objCust->getCustTravelPackRate($packid, $tripdate, $MarketPlaceId);
            $packMPRate = $objCust->getCustPackRate($packid, $tripdate, $MarketPlaceId);
        }



        if (count($packMPRate) == 0) {
            echo json_encode('notexists');
            exit;
            //$packRate = $objPackage->getMinPackRate($packid);
        }

        if (($flexiPackageList['StatusType'] == 16 && count($packMPRate) > 0) || @$_REQUEST['optionalSightInclude'] != '') {
            $roomjson = array();
            $totaladult = 0;
            $totalchild = 0;
            $roomlp = $this->_request->getParam('roomlp') ? $this->_request->getParam('roomlp') : '';
            for ($k = 1; $k <= $roomlp; $k++) {
                $roomjson[$k]['Adult'] = $this->_request->getParam('adult_' . $k);
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $this->_request->getParam('child_' . $k);
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['bedtype'] = $this->_request->getParam('extrabed_' . $k);
            }
            $travelers = $totaladult + $totalchild;
            $arrPkg['DiscountType'] = $_REQUEST['DiscountType'];
            $arrPkg['DiscountVal'] = $_REQUEST['DiscountVal'];
            $arrPkg['AdvBookingPercent'] = $_REQUEST['AdvBookingPercent'];
            $arrPkg['ShareCurrency'] = $_REQUEST['ShareCurrency'];
            if ($flexiPackageList['EconomyMask'] != 1) {
                // $_REQUEST['ExtraMarkup'] = 0;
            }
            $strRoomInfoJson = $flexiPackageList['RoomInfoJson']; //json_encode($roomjson);
            //
            $optionalSightInclude = implode(', ', json_decode(base64_decode($_REQUEST['optionalSightInclude'])));
            $totalactcost = $totalactmarkup = 0;
            if (!empty($optionalSightInclude)) {
                $ssdaywisearr = $objCust->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $tripdate, $optionalSightInclude);

                $objActivities = new Travel_Model_TblActivities();
                $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($flexiPackageList['AgencySysId'], $MarketPlaceId);

                if (!empty($ssdaywisearr)) {
                    foreach ($ssdaywisearr as $sightDetailsArr) {
                        $TotalCostArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getReadymadeOptionalSightseeingRatesnMarkup($sightDetailsArr, $arrStandardMarkups);
                        //             echo '<pre>'; print_r($TotalCostArr);echo '</pre>';
                        $totalactcost += ($totalchild * $TotalCostArr['ChildCost']) + ($totaladult * $TotalCostArr['AdultCost']);
                        $totalactmarkup += ($totalchild * $TotalCostArr['ChildCostMarkup']) + ($totaladult * $TotalCostArr['AdultCostMarkup']);
                    }
                }
            }

            //                 Package Cost.....                
            $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetAgencyCustomerTravelPlanCost($packid, $strRoomInfoJson, $arrPkg, $packMPRate[0], $packRate[0], $_REQUEST['ExchangeRate'], $type, $totalactcost, $totalactmarkup);
            //echo "<pre>";print_r($arrPkgCost);exit;
            $finalPackageCostWithDiscount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageCostwithDiscount($arrPkg, $arrPkgCost['FinalCost']);
            if ($MarketPlaceId == 2) {
                $B2BAgencyMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->addB2BAgencyMarkupForCustomer($arrPkgCost['FinalCost'], (int) base64_decode($_REQUEST['selectedCustomerId']), (float) $arrPkgCost['FinalMarkUp']);
                $arrPkgCost['FinalMarkUp'] = $B2BAgencyMarkUp;
                $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
            } else {
                $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
            }


            //calculate GST added by Er Amit Kumar Dubey on 19 august 2017 at 12:34 PM
            $objPackage = new Travel_Model_TblPackage();
            //						$flexiPackageList =	$objPackage->getCustPackageList($packid);
            $gsttype = ($flexiPackageList['GSTSharedMode'] == 0) ? 1 : $flexiPackageList['GSTSharedMode'];
            $GSTApplicableOn = $gsttype;
            $packageCost = $finalPackageCostWithMarkupnTax;
            $AgencyMarkUp = $arrPkgCost['FinalMarkUp'];
            $AgencyExtraMarkUp = $_REQUEST['ExtraMarkup'];
            $AgencyDiscount = $_REQUEST['ExtraDiscount'];
            $intProductType = 9;
            $intProductGeoType = 1; // 1 For Domestic, 2 For International


            $arrInputData = array(
                "GSTApplicableOn" => $GSTApplicableOn,
                "intProductType" => $intProductType,
                "intProductGeoType" => $intProductGeoType,
                "Cost" => $packageCost,
                "AgencyMarkUp" => $AgencyMarkUp + $arrPkgCost['optSightMarkupPrice'],
                "AgencyExtraMarkUp" => $AgencyExtraMarkUp,
                "AgencyDiscount" => $AgencyDiscount
            );

            $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
            $serviceTax = ($flexiPackageList['StatusType'] != 16) ? trim($arrGSTCalculations['GSTAmount']) : 0;
            $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWithMarkupnTax + $_REQUEST['ExtraMarkup'] + $serviceTax - $_REQUEST['ExtraDiscount'];
            $myCost = ($finalPackageCostWith_extramarkupNdiscount + $arrPkgCost['FinalDiscount'] + $_REQUEST['ExtraDiscount']);
            //#end calculate GST
//                        echo "<pre>";print_r($finalPackageCostWithMarkupnTax); 
//            echo "<pre>";print_r($_REQUEST['ExtraMarkup']); 
//            echo "<pre>";print_r($finalPackageCostWith_extramarkupNdiscount);exit;
            $advanceBookingAmount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getAdvanceBookingDetails($arrPkg['AdvBookingPercent'], $finalPackageCostWith_extramarkupNdiscount);
            if (isset($arrGSTCalculations['TaxType']) && $arrGSTCalculations['TaxType'] == 2) {
                $fMarkup = $arrPkgCost['FinalMarkUp'] + $arrPkgCost['optSightMarkupPrice'];
                $AgencyMarkupArrayServiceTax = $serviceTax - ($flexiPackageList['AgentsCustomServiceTaxAmount'] - $flexiPackageList['ServiceTaxOnCustomDiscount']); //Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($fMarkup, $arrGSTCalculations['TaxRate']);
            }
            if (isset($arrGSTCalculations['TaxType']) && $arrGSTCalculations['TaxType'] == 1) {
                $netPriceArrayServiceTax = $serviceTax - ($flexiPackageList['AgentsCustomServiceTaxAmount'] - $flexiPackageList['ServiceTaxOnCustomDiscount']); //Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($myCost, $arrGSTCalculations['TaxRate']);
            }
            $FinalMarkUp = (float) $arrPkgCost['FinalMarkUp'];
            //  if ($flexiPackageList['ShareCombinedFlightPricing'] == 1) { //Share Combined Flight Pricing
            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $GetPackageFLightData = $objCusttravelplan->GetPackageFLightData($packid);
            $encodedata = json_decode($GetPackageFLightData[0]['encodedata'], 1);
            $myCost = $myCost + $encodedata['totalcost_wom'] + $encodedata['total_markup'] + $encodedata['total_gst'];
            $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWith_extramarkupNdiscount + $encodedata['totalflightcost'];
            $FinalMarkUp = (float) $arrPkgCost['FinalMarkUp'] + (float) $package_flightdetails['total_markup'];
            // }
            $responseArray = array();
            $responseArray['AdvBookingPercent'] = $arrPkg['AdvBookingPercent'];
            $responseArray['bookingAmount'] = $advanceBookingAmount;
            $responseArray['TotalPrice'] = round($myCost + $flexiPackageList['TotalCostGen']);
            $responseArray['GrandTotal'] = round($finalPackageCostWith_extramarkupNdiscount + $flexiPackageList['TotalCostGen']);
            $responseArray['PricePerPax'] = round($responseArray['GrandTotal'] / $travelers);
            $responseArray['DiscountedPrice'] = $arrPkgCost['FinalDiscount'];
            $responseArray['ExtraDiscountedPrice'] = round($_REQUEST['ExtraDiscount']);
            $responseArray['SourcingCurrency'] = $arrPkgCost['SourcingCurrency'];
            $responseArray['ExchangeRate'] = $arrPkgCost['ExchangeRate'];
            $responseArray['SourcingNetCost'] = $arrPkgCost['SourcingNetCost'];
            $responseArray['SourcingMarkUp'] = $arrPkgCost['SourcingMarkUp'];
            $responseArray['SourcingNetPrice'] = $arrPkgCost['SourcingNetPrice'];
            $responseArray['ToCurrencySymbol'] = $arrPkgCost['ToCurrencySymbol'];
            $responseArray['FinalMarkUp'] = $FinalMarkUp;
            $responseArray['baseCurrExchange'] = $arrPkgCost['baseCurrExchange'];
            $responseArray['FinalCost'] = $arrPkgCost['FinalCost'];
            $responseArray['ShareCurrency'] = $arrPkgCost['ShareCurrency'];
            $responseArray['SourcingCurrencyId'] = $arrPkgCost['SourcingCurrencyId'];
            $responseArray['AgencyMarkupArrayServiceTax'] = isset($AgencyMarkupArrayServiceTax) ? $AgencyMarkupArrayServiceTax : 0;
            $responseArray['netPriceArrayServiceTax'] = isset($netPriceArrayServiceTax) ? $netPriceArrayServiceTax : 0;

            echo json_encode($responseArray);
            exit;
        }
    }

    function moneyFormatIndia($num) {
        $num = round($num);
        $explrestunits = "";
        if (strlen($num) > 3) {
            $lastthree = substr($num, strlen($num) - 3, strlen($num));
            $restunits = substr($num, 0, strlen($num) - 3); // extracts the last three digits
            $restunits = (strlen($restunits) % 2 == 1) ? "0" . $restunits : $restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
            $expunit = str_split($restunits, 2);
            for ($i = 0; $i < sizeof($expunit); $i++) {
                // creates each of the 2's group and adds a comma to the end
                if ($i == 0) {
                    $explrestunits .= (int) $expunit[$i] . ","; // if is first value , convert into integer
                } else {
                    $explrestunits .= $expunit[$i] . ",";
                }
            }
            $thecash = $explrestunits . $lastthree;
        } else {
            $thecash = $num;
        }
        return $thecash; // writes the final format where $currency is the currency symbol.
    }

    public function updateCustomerPackageHotelApiAction() {
        $objPackage = new Travel_Model_TblPackage();
        $packageId = @$_REQUEST['packageId'];
        $apibook = @$_REQUEST['apibook'];

        $currentDate = Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss');
        $data = array(
            'IsHotelFromAPI' => @$apibook
        );
        $where = array('TPSysId = ? ' => @$packageId);
        $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan', $data, $where);
        exit;
    }

    public function deletePackRateAction() {
        //$intLoggedinUserAgencySysId     = 	$this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $packid = @$_REQUEST['packid'];
        $fromdt = date("Y-m-d", @$_REQUEST['fromdate']);
        $todt = date("Y-m-d", @$_REQUEST['todate']);
        $currentDate = Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss');
        $data = array(
            'IsMarkForDel' => '1',
            'UpdateDate' => @$currentDate
        );
        $where = array(
            'TPIntSysId = ? ' => @$packid,
            'FromDate = ? ' => @$fromdt,
            'ToDate = ? ' => @$todt
        );
        $updateId = $objPackage->updateData('TB_TravelPlan_MarketWise_Rate', $data, $where);

        $where1 = array(
            'TPSysId = ? ' => @$packid,
            'StartDate = ? ' => @$fromdt,
            'ValidTill = ? ' => @$todt
        );
        $updateId1 = $objPackage->updateData('TB_TravelPlan_Rate', $data, $where1);
        //echo '<pre>';
        //print_r($exchangerate);
        exit;
    }

    public function currencyExchangeRateAction() {
        //$intLoggedinUserAgencySysId     = 	$this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $fromcurrency = @$_REQUEST['fromcurrency'];
        $tocurrency = @$_REQUEST['tocurrency'];
        $exchangerate = $objPackage->currencyExchangeRate($fromcurrency, $tocurrency);
        //echo '<pre>';
        //print_r($exchangerate);			
    }

    public function changePrevHotelAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
    }

    public function getHotelDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
    }

    public function getActivityDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $this->view->tourID = $this->_request->getParam('tourID');
    }

    public function getSightDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $this->view->tourID = $this->_request->getParam('tourID');
    }

    public function changePackageHotelAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
    }

    public function getFinalCityHotelAction() {
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
    }

    public function getAgentCityHotelAction() {
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
    }

    public function getAgentActivityAction() {
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
    }

    public function getAgentSightseenAction() {
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
    }

    public function updatePackRateAction() { //TPSysId
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
        //$intLoggedinUserAgencySysId         = 	$this->intLoggedinUserAgencySysId;			
        $currentDate = Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss');
        $data = array(
            'UpdateDate' => @$currentDate,
            $_REQUEST['type'] => @$_REQUEST['packrate']
        );
        $where = array('TPSysId = ? ' => @$_REQUEST['packid']);
        $updateId = $objPackage->updateData('TB_TravelPlan', $data, $where);
        exit;
    }

    /*     * ***************************************************Flight**************************************** */

    public function getAgentFlightAction() {
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
        //$intLoggedinAgencyId	=	@$_SESSION['sessionLogin_user']['intLoggedinUserAgencySysId'];
        //$intLoggedinUserAgencySysId         = 	$this->intLoggedinUserAgencySysId;
        if (@$_REQUEST['packageId'] > 0) {
            $flexiPackageList = $objPackage->getCustPackageList(@$_REQUEST['packageId']);
            $this->view->flexiPackageList = $flexiPackageList;
        }
    }

    /*     * ***************************************************\Flight**************************************** */

    public function viewFlexiFinalPackageReadymadeAction() {
        $this->_helper->layout->disableLayout();
        //$intLoggedinUserAgencySysId         = 	$this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        //echo $this->getRequest()->getParam('id');		
        if ($this->getRequest()->getParam('id') > 0) {
            $flexiPackageList = $objPackage->getFlexiPackageList($this->getRequest()->getParam('id'));
            $this->view->flexiPackageList = $flexiPackageList;
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getPackagePlacesList($this->getRequest()->getParam('id'));
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;
            $this->view->baseUrl = $this->baseUrl;
            //Get Package Itenary
            $flexiPackageItenList = $objPackage->getFlexiPackageItenList($this->getRequest()->getParam('id'));
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            //Get Package Activity
            /* $flexiPackageActivityList				=	$objPackage->getFlexiPackageActivityList($this->getRequest()->getParam('id'));
              $this->view->flexiPackageActivityList 	= 	$flexiPackageActivityList;
              //Get Package Sightseen
              $flexiPackageSightseenList				=	$objPackage->getFlexiPackageSightseenList($this->getRequest()->getParam('id'));
              $this->view->flexiPackageSightseenList 	= 	$flexiPackageSightseenList;
              //Get Package Hotels
              $flexiPackageHotelsList				=	$objPackage->getFlexiPackageHotelsList($this->getRequest()->getParam('id'));
              $this->view->flexiPackageHotelsList = 	$flexiPackageHotelsList; */

            //Get Package FInal Hotels
            $flexiPackageFinalHotel = $objPackage->getFlexiPackageFinalHotels($this->getRequest()->getParam('id'));
            $this->view->flexiPackageFinalHotel = $flexiPackageFinalHotel;

            /* echo "<pre>";
              print_r($flexiPackageItenList); //PackTypeMask	InclMask
              print_r($arrTransportInventoryList); //PackTypeMask	InclMask
              die(); */
        }
    }

    public function viewCustomerFinalPackageRedirectAction() {
        $tpID = base64_decode($this->getRequest()->getParam('id'));
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $TPSysId = $this->_HtmlPurifier->filter($tpID);
        if ($TPSysId > 0) {
            $secureCode = Catabatic_ValidateCustomer::secureCode($tpID, 1);
            $link = $this->view->baseUrl("/publicpackage/view-customer-final-package/id/" . base64_encode($TPSysId) . '/code/' . $secureCode);
            $this->_redirect($link);
        }
        exit;
    }

    public function viewCustomerFinalPackageAction() {
        $this->_helper->layout->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;
        $intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $objPackage = new Travel_Model_TblPackage();
        $tpID = $this->getRequest()->getParam('id') ? base64_decode($this->getRequest()->getParam('id')) : 0;
        $CustomerSysId = (NULL != $this->getRequest()->getParam('cid')) ? base64_decode($this->getRequest()->getParam('cid')) : '';
        $this->view->cid = $CustomerSysId;
        $queryTPSysId = (NULL != $this->getRequest()->getParam('qId')) ? base64_decode($this->getRequest()->getParam('qId')) : '';
        $this->view->qId = $queryTPSysId;
        $code = $this->getRequest()->getParam('code');
        $this->view->token = $token = $this->getRequest()->getParam('token', null);
        $this->view->code = $code;
        $source = $this->getRequest()->getParam('source');
        $this->view->source = isset($source) ? $source : '';
        $secureCode = Catabatic_ValidateCustomer::secureCode(trim($this->getRequest()->getParam('id')), 1);
        $otherlocationcity = array();
        if ($secureCode != $code) {
            echo "Please check your request parameters";
            exit;
        }
        // Added By Pardeep Panchal for Show T & C If Shared From GTX Network..............
        $strUrlData = ($this->getRequest()->getParam('data') != '') ? $this->getRequest()->getParam('data') : '';
        if ($strUrlData != '') {
            $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);
            $packid = $arrUrlData['packid'];
            $this->view->isfromgtxnetwork = $isfromgtxnetwork = $arrUrlData['isfromgtxnetwork'];
            $intLoggedinUserAgencySysId = $arrUrlData['intLoggedinUserAgencySysId'];
            $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
            $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($intLoggedinUserAgencySysId, $packid);
        }
        if ($tpID > 0) {
            $flexiPackageList = $objPackage->getCustPackageList($tpID);
//            echo "<pre>";print_r($flexiPackageList);die;
            //$QueryData = $this->_crmcusttravelplan->GetVersionAndOptionsByTpSysId($flexiPackageList['MasterTPSysId']);
            //echo "<pre>";print_r($QueryData);die;
            if (isset($flexiPackageList['IsGTXNetwork']) && !empty($flexiPackageList['IsGTXNetwork'])) {
                $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
                $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($flexiPackageList['AgencySysId'], $flexiPackageList['TPId']);
            }

            $objSupplier = new Travel_Model_TblSupplier();
            //$PkgSupplierDetails = $objSupplier->getSupplierList($flexiPackageList['SupplierSysId']);
            //echo "<pre>";print_r($flexiPackageList);die;
            $objSupplier->SupplierSysId = $flexiPackageList['SupplierSysId'];
            $packageSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $flexiPackageList['SupplierSysId']);

            if (isset($flexiPackageList['DestinationCovered']) && !empty($flexiPackageList['DestinationCovered'])) {
                $cityobj = new Travel_Model_TblCity();
                $cityIds = trim($flexiPackageList['DestinationCovered']);
                $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                $this->view->otherlocationcity = $otherlocationcity;
            }
            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $getcustomerDetail = $objCusttravelplan->GetTravelPlanDetailsofCustomer($tpID);

            $this->view->GetPackageFLightData = $objCusttravelplan->GetPackageFLightData($tpID);
            if ($getcustomerDetail[0]['CustomerSysId'] == '' && $CustomerSysId != '') {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $fetchRecord = $this->_crmcustomerObj->GetAgencyCustomerById(trim($CustomerSysId));
                $getcustomerDetail[0]['CustomerSysId'] = $fetchRecord['CustomerSysId'];
                $getcustomerDetail[0]['EmailId'] = $fetchRecord['EmailId'];
                $getcustomerDetail[0]['Contacts'] = $fetchRecord['Contacts'];
                $getcustomerDetail[0]['FirstName'] = $fetchRecord['FirstName'];
                $getcustomerDetail[0]['Salutation'] = $fetchRecord['Title'];
                $getcustomerDetail[0]['LastName'] = $fetchRecord['LastName'];
                $getcustomerDetail[0]['IsB2BAgent'] = $fetchRecord['IsB2BAgent'];
                $getcustomerDetail[0]['countrycode'] = $fetchRecord['countrycode'];
            }

            $IsB2BProposal = isset($flexiPackageList['IsB2BProposal']) ? $flexiPackageList['IsB2BProposal'] : 0;
            if ($IsB2BProposal == 1) {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }
            if ($flexiPackageList['MasterTPSysId'] == '0') {
                $childpackarr = $objCusttravelplan->GetVersionInfo($tpID);
            } else {
                $childpackarr = $objCusttravelplan->GetVersionInfo($flexiPackageList['MasterTPSysId']);
            }
            //echo '<pre>';print_r();die;
            $packRates = array();
            $tppackRate = array();
            if ($flexiPackageList['PackSpecType'] != '3' && $flexiPackageList['PackSpecType'] != '12') {
                foreach ($childpackarr as $key => $proposal) {
                    $StartDateTime = (array) $proposal['StartDate'];
                    $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));
                    $objCust = new Travel_Model_CRM_CustomerTravelPlan();
                    $strRoomInfoJson = $proposal['RoomInfoJson'];
                    $rominfojson = json_decode($strRoomInfoJson, 1);
                    $paxCount = array_sum((array_column($rominfojson, 'Adult')));
                    if ($flexiPackageList['PackSpecType'] == '1' || $flexiPackageList['PackSpecType'] == '2') {
                        $packRates = $objPackage->getCustPackRateRowWise($proposal['TPSysId'], $paxCount, $TripDate);
                        $tppackRate = $objCust->getCustTravelPackRateRowWise($proposal['TPSysId'], $TripDate, '', $paxCount);
                    } else {
                        $packRates = $objPackage->getCustPackRate($proposal['TPSysId'], '', $TripDate);
                        $tppackRate = $objCust->getCustTravelPackRate($proposal['TPSysId'], $TripDate);
                    }
                    //echo "<pre>";print_r($tppackRate);die;
                    $tppackRates = @$tppackRate[0];
                    $this->view->marketwiserate = $packRate = @$packRates[0];
                    $arrPkg['DiscountType'] = $proposal['DiscountType'];
                    $arrPkg['DiscountVal'] = $proposal['DiscountVal'];
                    $arrPkg['AdvBookingPercent'] = $proposal['AdvBookingPercent'];
                    if (!empty($packRates)) {
                        $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetAgencyCustomerTravelPlanCost($proposal['TPSysId'], $strRoomInfoJson, $arrPkg, $packRate, $tppackRates);
                        $finalPackageCostWithDiscount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageCostwithDiscount($arrPkg, $arrPkgCost['FinalCost']);
                        $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
                        $taxdetailforagency = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax('', "P", 0);
                        $tax = (trim($taxdetailforagency['ServiceTaxPercentage']) > 0) ? trim(floatval($taxdetailforagency['ServiceTaxPercentage'])) : 0;
                        $gsttype = ($proposal['GSTSharedMode'] == 0) ? 1 : $proposal['GSTSharedMode'];
                        $GSTApplicableOn = $gsttype;
                        $packageCost = $finalPackageCostWithMarkupnTax;
                        $AgencyMarkUp = $arrPkgCost['FinalMarkUp'];
                        $AgencyExtraMarkUp = $proposal['MarkUp'];
                        $AgencyDiscount = $proposal['CustomDiscount'];
                        $intProductType = 9;
                        $intProductGeoType = 1; // 1 For Domestic, 2 For International
                        $arrInputData = array(
                            "GSTApplicableOn" => $GSTApplicableOn,
                            "intProductType" => $intProductType,
                            "intProductGeoType" => $intProductGeoType,
                            "Cost" => $packageCost,
                            "AgencyMarkUp" => $AgencyMarkUp,
                            "AgencyExtraMarkUp" => $AgencyExtraMarkUp,
                            "AgencyDiscount" => $AgencyDiscount
                        );
                        $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
                        $serviceTax = trim($arrGSTCalculations['GSTAmount']);
                        $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWithMarkupnTax + round($proposal['MarkUp']) + $serviceTax - round($proposal['CustomDiscount']);
                        $childpackarr[$key]['GrandTotal'] = $finalPackageCostWith_extramarkupNdiscount;
                        $childpackarr[$key]['arrPkgCost'] = $arrPkgCost;
                    }
                }
            }

            $this->view->proposalList = $childpackarr;
            $this->view->arrGSTCalculations = $arrGSTCalculations;
            $packageTncList = $objPackage->getCustPackageTncList($tpID);
            $flexiPackageList['tncDetails'] = $packageTncList;
            //$flexiPackageList['QueryData'] = $QueryData;
            //for agency details
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
            $agencyObj = new Travel_Model_TblAgency();
            $agentDetail = $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
            //            echo "<pre>";print_r($arrGSTCalculations);die;
            $flexiPackageList['agencyDetails'] = $getAgencyDetail;
            $flexiPackageList['agentDetails'] = $getAgentDetail;
            $inclusionMastArray = $objPackage->getPackageInclusionList();
            //print_r($flexiPackageList['InclMask']);
            $inclusionArr = $objPackage->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
            $flexiPackageList['inclusionDetails'] = $inclusionArr;
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->PkgSupplierDetails = $PkgSupplierDetails;
            $this->view->packageSupplierDetails = $packageSupplierDetails;
            if ($flexiPackageList['PackSpecType'] == '12') {
                $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotelsForB2BOptinal($flexiPackageList['TPSysId']);

                //echo "<pre>";print_r($gettransportoption);exit;
            } else {
                $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotels($flexiPackageList['TPSysId']); // for only hotel overview
            }
            //echo "<pre>";print_r($hotelarr);exit;
            $this->view->hotelarr = $hotelarr;

            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
            $flexiPackageAllDetailsList = $objPackage->getCustPackageAllDetailsList($tpID);
            //echo "<pre>";print_r($flexiPackageAllDetailsList);die;
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            $this->view->flexiPackageAllDetailsList = $flexiPackageAllDetailsList;
            $objCity = new Travel_Model_TblCity();
            if (!empty($flexiPackageItenList)) {
                $this->view->cityMainDetail = $objCity->getCityImagesDetailsById($flexiPackageItenList[0]['PlaceSysId'], 1, 1);
            }
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID, $intLoggedinUserAgencySysId);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;

            $tourID = $this->getRequest()->getParam('tID');
            $this->view->tourID = $tourID = !empty($tourID) ? $tourID : $flexiPackageList['TourType'];
            //Get Package Hotels

            $packType = $flexiPackageList['PackSpecType'];

            if ($flexiPackageList['PackSpecType'] == '3') { // only for dynamic proposal
                $gettransportoption = $objPackage->GetTransPortOption($tpID);
                $totaltransport = array_sum(array_column($gettransportoption, 'total'));
                $this->view->totaltransportCount = $totaltransport;

                $catID = $this->getRequest()->getParam('cID');
                $mealID = $this->getRequest()->getParam('mID');
                $this->view->catID = $catID = !empty($catID) ? $catID : $flexiPackageList['EconomyMask']; // only for dynamic
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID, @$catID, $packType);

                $getotherservices = $this->_crmcusttravelplan->GetOtherServices($tpID);
                $gettransportdata = $this->_crmcusttravelplan->GetAllTransportOption($tpID);
                $this->view->getotherservices = $getotherservices;
                $this->view->gettransportdata = $gettransportdata;
                $flexiPackageHotelListArr1 = $flexiPackageHotelMealPlanWiseListArr = array();
                for ($h = 0; $h < count(@$flexiPackageHotelsList); $h++) {
                    if ($flexiPackageHotelsList[$h]['IsSelectedOnPkg'] == '1') {
                        $flexiPackageHotelListArr1[] = $flexiPackageHotelsList[$h];
                        $flexiPackageHotelMealPlanWiseListArr[$flexiPackageHotelsList[$h]['MealPlanType']][] = $flexiPackageHotelsList[$h];
                    }
                }

                $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList);
                $totalNight = $totalDaysNightsArr['totalnights'];
                $PackageCostCalType = $flexiPackageList['PackageCostCalType'];
                if ($PackageCostCalType) {
                    $PossibleCombinationsOfMealPlanArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPossibleCombinationsOfMealPlan($flexiPackageHotelListArr1, $totalNight, $catID);
                    $this->view->possibleCombinationsOfMealPlanArr = $PossibleCombinationsOfMealPlanArr;
                }

                //                echo '<pre>';print_r($PossibleCombinationsOfMealPlanArr); print_r($flexiPackageHotelsList); die;
                //                $mIDArr = array_keys($PossibleCombinationsOfMealPlanArr); // need a column for this in database
                $this->view->mID = $mID = !empty($mealID) ? $mealID : $flexiPackageList['SharedMealPlanType'];
                $this->view->flexiPackageHotelsList = !empty($PackageCostCalType) ? $flexiPackageHotelMealPlanWiseListArr[$mID] : $flexiPackageHotelsList;

                $marketwiseratebyo = $this->_crmcusttravelplan->GetMarketWiseRateBYOReadyMade($tpID, @$catID, $tourID, $mID, $MarketPlaceId);

                $this->view->marketwiseratebyo = $marketwiseratebyo;
            } else { // condition for readymade package
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsListReadymade($tpID);
                $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;
                $sequenceCount = 2;
                if (count($flexiPackageItenList) == 1) {
                    $sequenceCount = 1;
                }



                $itenArray = $this->_crmcusttravelplan->getPackItenId($tpID, $sequenceCount);
                //             echo "<pre>"; print_r($itenArray);die;
                $StartDateTime = (array) $flexiPackageList['StartDate'];
                $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));

                $ssdaywisearr = $this->_crmcusttravelplan->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $TripDate);
                $this->view->ssdaywisearr = $ssdaywisearr;

//                $objActivities = new Travel_Model_TblActivities();
//                $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($getAgencyDetail['AgencySysId'], $MarketPlaceId);
                //                echo "<pre>"; print_r($itenArray);die;
                $this->view->arrStandardNativesMarkups = $arrStandardMarkups;
            }
            $this->view->OtherServiceData = $OtherServiceData = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServicesDisplay($flexiPackageList['TPSysId']);
            $addOnItemsCurrencyArray = array_column($OtherServiceData, 'CurrencyType');
            $exchangerateAll = array();
            if (!empty($addOnItemsCurrencyArray)) {
                $AllCurrenciesIds = (!empty($addOnItemsCurrencyArray)) ? implode(',', array_unique($addOnItemsCurrencyArray)) : '';
                $exchangerateArray = $objPackage->multipleCurrencyExchangeRate($AllCurrenciesIds, $OtherServiceData[0]['SharedCurrencyType']);
                $MarkUpPersentage = $exchangerateArray['MarkUpPersentage'];
                foreach ($exchangerateArray['conversion'] as $exKey => $exVal) {
                    if ($MarkUpPersentage > 0) {
                        $Rate = isset($exVal['Rate']) ? ((float) $exVal['Rate'] + ((float) ($exVal['Rate']) * $MarkUpPersentage) / 100) : 1;
                    } else {
                        $Rate = isset($exVal['Rate']) ? (float) $exVal['Rate'] : 1;
                    }
                    $exchangerateAll[$exVal['FCurrencyType'] . '-' . $exVal['TCurrencyType']] = $Rate;
                }
            }
            $this->view->exchangerateAll = $exchangerateAll;
            //echo "<pre>";print_r($exchangerateAll);die;
            if ($flexiPackageList['PackSpecType'] == 2) {
                //                $resflexiPackageActivityOnlyHotel = $objPackage->getCustPackageActivityListBySeq(@$flexiPackageList['TPSysId'], 2);
                //                $this->view->flexiPackageActivityList = $resflexiPackageActivityOnlyHotel;
                $resflexiPackageSSOnlyHotel = $objPackage->getCustPackageSightseenListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageSightseenList = $resflexiPackageSSOnlyHotel;
            } else {
                //Get Package Activity
                //                $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
                //                $this->view->flexiPackageActivityList = $flexiPackageActivityList;
                //Get Package Sightseen
                $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
                $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            }
            $this->view->gettransportdata = $gettransportdata = $this->_crmcusttravelplan->GetAllQuickTransportOption($flexiPackageList['TPSysId']);
            $this->view->getitinerarytransportdata = $getitinerarytransportdata = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryTransportByTPSysId($flexiPackageList['TPSysId']);
            //          echo "<pre>"; print_r(getitinerarytransportdata);die;
            $RoadTypeList = $objPackage->getMasterRoadType();
            $this->view->RoadTypeList = $RoadTypeList;
//            $getpacktypemask = $objPackage->GetMasterPackageList();
//            $this->view->packtypemask = $getpacktypemask;
            //Get Package Flight
            //            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            //            $this->view->flexiPackageFlight = $flexiPackageFlight;
            ########## Code Added By Shobhit ##################
            $this->view->tpID = $tpID;
            $getcustomerDetail[0]['AgentName'] = trim($getAgentDetail['FirstName']) . ' ' . trim($getAgentDetail['LastName']);
            $getcustomerDetail[0]['AgentNo'] = $getAgentDetail['ContactNo1'];
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            $objAgency = new Travel_Model_TblAgency();
            $agencyData = $objAgency->getAgencyDataById($flexiPackageList['AgencySysId']);
            $this->view->getAgencyData = $agencyData;

            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
            $getChatHistoryDetail = array();
            $checkCustomerChatExist = (@$getcustomerDetail[0]['CustomerSysId'] > 0) ? $objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID, trim($flexiPackageList['AgentSysId'])) : array();
            // $checkCustomerChatExist = (count($checkCustomerChatExist)==0)?$objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID):$checkCustomerChatExist;
            if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'ASC');
            }
            $getcustomerDetail['userChatExist'] = (is_array($checkCustomerChatExist) && count($checkCustomerChatExist) > 0) ? count($checkCustomerChatExist) : count($getChatHistoryDetail);
            //  $this-view->getCustomerDetails = $getcustomerDetail;
            //query for get customer chat history
            $chatSenderDetails = array();
            $objAgencyStaff = new Travel_Model_TblAgencyStaff();
            //$agentDetail = $objAgencyStaff->getUserDetailsById($flexiPackageList['AgentSysId']);
            if ($getcustomerDetail['userChatExist'] > 0) {
                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
                    $chatSenderDetails['TPSysId'] = $tpID;
                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
                    $chatSenderDetails['EmailId'] = $agentDetail['EmailId'];
                    //print_r($agentDetail);
                }
            }
            //end of customer chat history
            $getcustomerDetail['AgencyDetails'] = $agencyData;
            $chatSenderDetails['AgencyDetails'] = $agencyData;
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $getversiondetails;
            $this->view->chatSenderDetails = $chatSenderDetails;

//            $termscond = $objPackage->getTermCond($tpID);
//            $this->view->termc = $termscond;

            $rateList = array('arrPkgCost' => array('AdultPax' => $flexiPackageList['MinPax'], 'ChildPax' => 0, 'FinalCost' => $flexiPackageList['NetPrice'], 'FinalDiscount' => $flexiPackageList['DiscountVal'], 'FinalMarkUp' => 0));
            $popupArray = array();
            $popupArray['rateList'] = json_encode($rateList);

            $this->view->popupArray = $popupArray;
            //print_r($agentDetail);
            //send email to agent when customer open proposal
            //$isPlanViewed = $this->_crmcusttravelplan->GetTravelPlanType($tpID);

            if ($flexiPackageList['PackSpecType'] != '12' && $flexiPackageList['IsPlanViewed'] == 0 && $flexiPackageList['IsShared'] == 1 && $isAgentLoggedIn == 0) {
                $objAgentStaff = new Travel_Model_TblAgencyStaff();
                $fieldName = array('SMSOpenAlert', 'EmailOpenAlert');
                $manageNotifications = $objAgentStaff->getAgencyWiseQueryAcknowledgement($flexiPackageList['AgencySysId'], $fieldName);
                $emailSendId = trim($agencyData['PrimaryEmail']);
                $fromName = (isset($agencyData['DisplayName']) && !empty($agencyData['DisplayName'])) ? trim($agencyData['DisplayName']) : trim(trim($agencyData['Title']));
                $emailId = trim($agentDetail['EmailId']);
                //$emailId = trim('amit.k@catpl.co.in');
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
                $html->assign('type', 'proposalViewPackageSendEmailToAgent');
                $html->assign('customerDetails', $getcustomerDetail);
                $html->assign('agentDetails', $agentDetail);
                $html->assign('agencyDetails', $agencyData);
                $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpID), 1);
                $link = $this->view->baseUrl("/publicpackage/view-customer-final-package/id/" . base64_encode($tpID) . "/code/" . $secureCode);
                $html->assign('link', $link);
                $html->assign('data', $flexiPackageList);
                //$html->assign('data', $hotelValues);
                $bodyText = $html->render('email-template.phtml');
                //$bodyText='Customer open your proposal' .$this->view->baseUrl("/proposal/preview-hotel-result/mid/".base64_encode($mid)."/pid/".base64_encode($pid)."/uid/".base64_encode($uid)."/type/".base64_encode($type));
                //$bodyText='Customer open your proposal' .$this->view->baseUrl("/proposal/preview-hotel-result/mid/".base64_encode($mid)."/pid/".base64_encode($pid)."/uid/".base64_encode($uid)."/type/".base64_encode($type));
                $subject = 'HelloGTX - Proposal Open Alert !';
                if ($agencyData['IsDisplayHelloGTX'] == 1) {
                    $subject = $fromName . ' - Proposal Open Alert !';
                }
                $emailData = array('fromEmail' => trim($emailSendId), 'fromName' => trim($fromName), 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $params['arrEmailStatisticsType'] = $arrEmailStatisticsType[2];
                $arrEmailStatistics = array(
                    "TPSysId" => $flexiPackageList['TPSysId'],
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $flexiPackageList['AgencySysId'],
                    "AgentSysId" => $flexiPackageList['AgentSysId'],
                    "Title" => $bodyText,
                    "Source" => isset($params['arrEmailStatisticsType']) ? $params['arrEmailStatisticsType'] : '', // 1 For Fresh Proposals
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                if (in_array('EmailOpenAlert', $manageNotifications)) {
                    $mailsend = $this->mailSentByElastice($emailData, $arrEmailStatistics, 0, 0);
                    //echo "<pre>";print_r($mailsend);
                }

                // Proposal Open Alert Mobile Notification
                $getAgentDetails = $this->_crmcusttravelplan->getAgentDetails($flexiPackageList['AgentSysId']);

                $countrycode = (strpos($getCustomerDetail[0]['countrycode'], '+') !== false) ? $getCustomerDetail[0]['countrycode'] : "+" . $getCustomerDetail[0]['countrycode'];

                $CustomerMobileNumber = trim($countrycode) . '' . trim($getCustomerDetail[0]['Contacts']);
                $customerFirstName = trim($getCustomerDetail[0]['FirstName']);
                $destination = (isset($flexiPackageList['DestinationPlaces']) && !empty($flexiPackageList['DestinationPlaces'])) ? trim($flexiPackageList['DestinationPlaces']) : '';

                $postData = array(
                    "UserSysId" => trim($flexiPackageList['AgentSysId']),
                    // "IsSchedule" => False,
                    "schedule_time" => "",
                    "title" => "Proposal Open Alert",
                    "body" => "Boom! Proposal Unlocked! $customerFirstName just opened the $destination proposal.",
                    //"IsButton" => True,
                    "URL" => "",
                    "IsCall" => true,
                    "mobileNo" => trim($CustomerMobileNumber)
                );

                if (isset($getAgentDetails['SecurityKey'])) {
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://globaltravelexchange.com/gtxwebservices/agency/create-fire-base-message',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS => $postData,
                        CURLOPT_HTTPHEADER => array(
                            'securitykey:' . trim($getAgentDetails['SecurityKey']),
                        //'Content-Type: application/json'
                        ),
                    ));
                    $response = curl_exec($curl);
                    curl_close($curl);
                }

                // Proposal Open Alert Mobile Notification
                //send sms
                $mobile_no = trim($agentDetail['ContactNo1']);
                $updateData = new Payment_Model_Checkotp();
                //$massage = "Your Customer(".trim($getcustomerDetail[0]['Contacts']).") has just opened the proposal. Team HelloGTX";
                $params['TPSysId'] = $tpID;
                $params['shared_url'] = $link;
                $params['AgencySysId'] = $flexiPackageList['AgencySysId'];
                $params['AgentSysId'] = $flexiPackageList['AgentSysId'];
                $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
                $params['arrSMSStatisticsType'] = $arrSMSStatisticsType[0];
                $shorturl_response = Zend_Controller_Action_HelperBroker::getStaticHelper('ShortUrl')->url_get($params);
                if (isset($shorturl_response['status_code']) && $shorturl_response['status_code'] == 200) {
                    $link = $shorturl_response['data']['short_url'];
                }

                $RoomInfoJson = json_decode($flexiPackageList['RoomInfoJson'], true);
                $departuredate = isset($RoomInfoJson[1]['departuredate']) ? $RoomInfoJson[1]['departuredate'] : '';
                $AgentFirstName = trim($agentDetail['FirstName']) . ' ' . trim($agentDetail['LastName']);
                $custPhone = trim($getcustomerDetail[0]['Contacts']);
                $massage = "Dear " . trim($AgentFirstName) . ",\n" . trim($getcustomerDetail[0]['FirstName']) . " " . trim($getcustomerDetail[0]['LastName']) . " has just opened the proposal for " . trim(stripslashes($flexiPackageList['DestinationPlaces'])) . " using link " . $link . ". Call at " . $custPhone . " to help in trip planning.\nHappy Selling\nTRVCRM";

                $this->postFields = "";
                $this->postFields .= "&method=$this->SMSMETHOD";
                $this->postFields .= "&api_key=$this->SMSAPIKEY";
                $this->postFields .= "&to=$mobile_no";
                $this->postFields .= "&sender=$this->SMSSENDER";
                $this->postFields .= "&message=$massage";
                $this->postFields .= "&format=$this->SMSFORMAT";
                $postURL = $this->SMSURL;
                // Added By Amit For SMS Count...
                $arrSMSStatistics = array(
                    "TPSysId" => isset($params['TPSysId']) ? $params['TPSysId'] : 0,
                    "TypeSysId" => 2, // 1 For Email 2 For SMS
                    "AgencySysId" => isset($params['AgencySysId']) ? $params['AgencySysId'] : 0,
                    "AgentSysId" => isset($params['AgentSysId']) ? $params['AgentSysId'] : 0,
                    "Title" => $massage,
                    "Source" => isset($params['arrSMSStatisticsType']) ? $params['arrSMSStatisticsType'] : 1, // 2 Resend Proposals (Bulk)
                    "Status" => '',
                    "RefSysId" => '',
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                if (in_array('SMSOpenAlert', $manageNotifications)) {
                    //$resultVal = $updateData->sendSmsDetails($postURL, $this->postFields, $arrSMSStatistics);
                    $resultVal['status'] = 'OK';
                    if (isset($resultVal['status']) && $resultVal['status'] == 'OK') {
                        $errorMessage = "";
                    } else {
                        $errorMessage = "Oops! Please try again";
                    }
                }
                $data = array(
                    'IsPlanViewed' => 1,
                    'UpdateDate' => date('Y-m-d H:i:s'),
                );
                $where = "TPSysId = " . $tpID;
                $updatetravelplanrecord = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($data, $where);
            }

            $objHotel = new Travel_Model_TblHotel();
            $objHotel->orderByField = " TB_Master_Accom_AccomAminity.AminityId";
            $objHotel->orderBy = "";
            $arrAmenites = $objHotel->getMasterAccomAminities();
            $this->view->arrAmenites = $arrAmenites;
            $this->view->queryTPSysId = $queryTPSysId;
            //   $encydataForTnc = $this->getEnc($flexiPackageList['TPSysId'] . ":" . $flexiPackageList['AgencySysId'] . ":" . $flexiPackageList['CustomerSysId']);
            // $this->view->encid = $encydataForTnc;
            $this->view->encid = '';
            $getServiceFeeAmount = $this->_crmcusttravelplan->getTcsAmount($tpID, 21, 0);
            $this->view->getServiceFeeAmount = $getServiceFeeAmount;
        }
        $this->view->intLoggedinUserAgencySysId = $intLoggedinUserAgencySysId;
        $this->view->intLoggedinUserId = $intLoggedinUserId;
    }

    public function convertToUtf8($str) {
        if (!mb_detect_encoding($str, 'UTF-8', true)) {
            return utf8_encode($str);
        }
        return $str;
    }

    public function viewCustomerFinalPackagePreviewAction() {
        $this->_helper->layout->disableLayout();
        $type = $this->getRequest()->getParam('type') ? ($this->getRequest()->getParam('type')) : 0;
        $tpID = $this->getRequest()->getParam('id') ? base64_decode($this->getRequest()->getParam('id')) : 0;
        $CustomerSysId = (NULL != $this->getRequest()->getParam('cid')) ? base64_decode($this->getRequest()->getParam('cid')) : '';
        $this->view->cid = $CustomerSysId;
        $queryTPSysId = (NULL != $this->getRequest()->getParam('qId')) ? base64_decode($this->getRequest()->getParam('qId')) : '';
        $this->view->qId = $queryTPSysId;
        $code = $this->getRequest()->getParam('code');
        $this->view->token = $token = $this->getRequest()->getParam('token', null);
        $this->view->code = $code;
        $source = $this->getRequest()->getParam('source');
        $this->view->source = isset($source) ? $source : '';
        $secureCode = Catabatic_ValidateCustomer::secureCode(trim($this->getRequest()->getParam('id')), 1);
        if ($secureCode != $code) {
            echo "Please check your request parameters";
            exit;
        }
        $objPackage = new Travel_Model_TblPackage();
        $strUrlData = ($this->getRequest()->getParam('data') != '') ? $this->getRequest()->getParam('data') : '';
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;
        $intLoggedinUserAgencySysId = isset($sessionLogin_user->intLoggedinUserAgencySysId) ? $sessionLogin_user->intLoggedinUserAgencySysId : NULL;
        $intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $mdl = new Crm_Model_CrmProcedure();
        $resultSet = $mdl->getCustomerProposal($tpID, $intLoggedinUserAgencySysId);
        $jsonStringUtf8 = $this->convertToUtf8($resultSet);
        $resultSetArr = json_decode($jsonStringUtf8, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_last_error_msg();
            exit; // Print any JSON error
        }
        if ($type == 1) {
            echo "<pre>";
            print_r($resultSetArr);
            die;
        }

        $getitinerarytransportdata = isset($resultSetArr['CustomerTransfer']) ? $resultSetArr['CustomerTransfer'] : [];
        $GetPackageFLightData = $resultSetArr['FlightDetail'];
        $itinaryData = $resultSetArr['Itinerary'];
        $flexiPackageItenList = [];
        $flexiPackageHotelsList = [];
        $flexiPackageSightseenList = [];
        $CruiseData = $hotelarr = $getTransportDetail = [];
        foreach ($itinaryData as $itiKey => $itiVal) {
            $placeData = $itiVal['Places'];
            $sightseeingData = $itiVal['SightSeeing'];
            $CruiseDataArray = $itiVal['CruiseData'];
            $hotelData = $itiVal['Accommodation'];
            $TransferData = isset($itiVal['Transfer']) ? $itiVal['Transfer'] : array();
            foreach ($placeData as $placeVal) {
                $placeSysId = $placeVal['PLACESYSID'];
            }
            $flexiPackageItenList[] = array(
                'TPIntSysId' => $itiVal['ItineraryID'],
                'TPSysId' => $resultSetArr['TPSysId'],
                'Sequence' => $itiVal['Sequence'],
                'Title' => $itiVal['ItineraryTitle'],
                'Details' => $itiVal['ItineraryDetails'],
                'InclMask' => $itiVal['InclMask'],
                'CitySysId' => $itiVal['CitySysId'],
                'Cities' => $itiVal['Cities'],
                'MealPlanInclude' => $itiVal['MealPlanInclude'],
                'TotalMinDays' => $itiVal['TotalMinDays'],
                'TotalMaxDays' => $itiVal['TotalMaxDays'],
                'PlaceSysId' => $placeSysId,
            );
            foreach ($sightseeingData as $sightKy => $sightVal) {
                $flexiPackageSightseenList[] = array(
                    'InvnItemSysId' => $itiVal['ItineraryID'],
                    'SeqId' => $itiVal['Sequence'],
                    'CITYNAME' => $itiVal['Cities'],
                    'Title' => $sightVal['ActivityTitle'],
                    'synonyms' => $sightVal['ActivityTitle'],
                    'WriteUp' => $sightVal['ActivityDetails'],
                    'Icon' => $sightVal['DetailImg'],
                    'ThumnailImg' => $sightVal['DetailImg'],
                    'DetailImg' => $sightVal['DetailImg'],
                    'PriceType' => isset($sightVal['PriceType']) ? $sightVal['PriceType'] : '',
                    'Type' => $sightVal['Type'],
                    'TotalCost' => $sightVal['TotalCost'],
                    'Symbol' => $sightVal['Symbol'],
                );
            }
            foreach ($CruiseDataArray as $cruiseKy => $cruiseVal) {
                $CruiseData[] = $cruiseVal;
            }
            foreach ($hotelData as $hotelVal) {
                $hotelarr[] = array(
                    'TPSysId' => $resultSetArr['TPSysId'],
                    'CitySysId' => $itiVal['CitySysId'],
                    'TPIntSysId' => $itiVal['ItineraryID'],
                    'SeqId' => $itiVal['Sequence'],
                    'Sequence' => $itiVal['Sequence'],
                    'CityName' => $itiVal['Cities'],
                    'TotalMinDays' => $itiVal['TotalMinDays'],
                    'Title' => $hotelVal['HotelName'],
                    'StarRating' => $hotelVal['StarRating'],
                    'InvnItemSysId' => $hotelVal['InvnItemSysId'],
                    'TotalCost' => $hotelVal['TotalCost'],
                    'FromDate' => $hotelVal['FromDate'],
                    'AccoSimilarHotel' => $hotelVal['AccoSimilarHotel'],
                    'RoomTypeStr' => $hotelVal['RoomTypeStr'],
                    'Title' => $hotelVal['Title'],
                    'NetCost' => $hotelVal['NetCost'],
                    'CurrencyType' => $hotelVal['CurrencyType'],
                    'RoomNumber' => $hotelVal['RoomNumber'],
                    'SupplierSysId' => $hotelVal['SupplierSysId'],
                    'NetPrice' => $hotelVal['NetPrice'],
                    'XServiceTaxAmount' => $hotelVal['XServiceTaxAmount'],
                    'AgentServiceTaxAmount' => $hotelVal['AgentServiceTaxAmount'],
                    'AgentsCustomServiceTaxAmount' => $hotelVal['AgentsCustomServiceTaxAmount'],
                    'ServiceTaxOnCustomDiscount' => $hotelVal['ServiceTaxOnCustomDiscount'],
                    'SupplierName' => $hotelVal['SupplierName'],
                    'SupplierSalution' => $hotelVal['SupplierSalution'],
                    'SupplierFirstName' => $hotelVal['SupplierFirstName'],
                    'SupplierLastName' => $hotelVal['SupplierLastName'],
                    'SupplierEmailId' => $hotelVal['SupplierEmailId'],
                    'AccomSysId' => $hotelVal['AccomSysId'],
                    'AccoAminitiesMask' => $hotelVal['AccoAminitiesMask'],
                    'IsAgentSpec' => $hotelVal['IsAgentSpec'],
                    'ICSourceSysId' => $hotelVal['ICSourceSysId'],
                    'DetailImg' => $hotelVal['DetailImg'],
                    'Brief' => $hotelVal['Brief'],
                    'Address' => $hotelVal['Address'],
                    'HotelName' => $hotelVal['HotelName'],
                    'RoomType' => $hotelVal['RoomType'],
                    'RoomTitle' => $hotelVal['RoomTitle'],
                    'MealTypeId' => $hotelVal['MealTypeId'],
                    'RoomMealType' => $hotelVal['RoomMealType'],
                    'Symbol' => $hotelVal['Symbol'],
                    'Stars' => $hotelVal['Stars'],
                    'Rating' => $hotelVal['Rating'],
                );
            }
            if (is_array($TransferData) && !empty($TransferData)) {
                $getTransportDetail = array_merge($getTransportDetail, $TransferData);
            }
        }
        $AddonsServicesPlanWise = array();
        foreach ($resultSetArr['AddonsServices'] as $key => $adValue) {
            $AddonsServicesPlanWise[$adValue['PlanType']][] = $adValue;
        }
        $getServiceFeeAmount = $AddonsServicesPlanWise[21][0];
        $RoadTypeList = $resultSetArr['RoadType'];
        $getpacktypemask = $resultSetArr['PackCategory'];
        $OtherServiceData = $resultSetArr['OtherServices'];
        $flexiPackageList = $resultSetArr;
        $packageTncList = $resultSetArr['TC'];
        $flexiPackageList['agentDetails'] = $resultSetArr['AgentDetails']['0'];
        $flexiPackageList['agencyDetails'] = $resultSetArr['AgencyDetails']['0'];
        $getcustomerDetail = $resultSetArr['CustomerDetails'];
        $getcustomerDetail['AgencyDetails'] = $resultSetArr['AgencyDetails']['0'];
        $childpackarr = $resultSetArr['ProposalList'];
        $inclusionAllArr = $resultSetArr['PackInclusion'];
        $inclusionArr = $objPackage->getMasking($resultSetArr['InclMask'], $inclusionAllArr, 'InclId');

        $getcustomerDetail['0']['TPSysId'] = $tpID;
        if ($secureCode != $code) {
            echo "Please check your request parameters";
            exit;
        }
        if ($strUrlData != '') {
            $this->view->isfromgtxnetwork = $isfromgtxnetwork = $arrUrlData['isfromgtxnetwork'];
            $intLoggedinUserAgencySysId = $arrUrlData['intLoggedinUserAgencySysId'];
        }
        if ($tpID > 0) {
            $otherlocationcity = $resultSetArr['otherlocationcity'];
            $getcustomerDetail = $getcustomerDetail;
            $flexiPackageList['tncDetails'] = $packageTncList;
            $flexiPackageList['QueryData'] = $resultSetArr['QueryData'][0];
            $flexiPackageList['CruiseData'] = $CruiseData;
            $flexiPackageList['inclusionDetails'] = $inclusionArr;
            $flexiPackagePlaces = $resultSetArr['flexiPackagePlaces'];

            $ssdaywisearr = $resultSetArr['ssdaywisearr'];
            $OtherServiceData = $OtherServiceData;
            $exchangerateAll = $resultSetArr['exchangerateAll'];

            $agencyData = $resultSetArr['AgencyDetails'][0];
            $agentDetail = $resultSetArr['AgentDetails'][0];
            $rateList = array('arrPkgCost' => array('AdultPax' => $flexiPackageList['MinPax'], 'ChildPax' => 0, 'FinalCost' => $flexiPackageList['NetPrice'], 'FinalDiscount' => $flexiPackageList['DiscountVal'], 'FinalMarkUp' => 0));
            $popupArray = array();
            $popupArray['rateList'] = json_encode($rateList);
            $isPlanViewed = $resultSetArr['isPlanViewed'];

            $this->view->otherlocationcity = $otherlocationcity;
            $this->view->GetPackageFLightData = $GetPackageFLightData;
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->proposalList = $childpackarr;
            $this->view->hotelarr = $hotelarr;
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            $this->view->cityMainDetail = $resultSetArr['cityMainDetail'];
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;
            $this->view->tourID = $tourID = !empty($tourID) ? $tourID : $flexiPackageList['TourType'];
            $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;
            $this->view->ssdaywisearr = $ssdaywisearr;
            $this->view->OtherServiceData = $OtherServiceData;
            $this->view->exchangerateAll = $exchangerateAll;
            $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            $this->view->getitinerarytransportdata = $getitinerarytransportdata;
            $this->view->RoadTypeList = $RoadTypeList;
            $this->view->packtypemask = $getpacktypemask;
            $this->view->tpID = $tpID;
            $this->view->getAgencyData = $agencyData;

            $this->view->getcustomerDetail = $getcustomerDetail;


            $this->view->popupArray = $popupArray;
            $this->view->queryTPSysId = $queryTPSysId;
            $this->view->encid = '';
            $this->view->getServiceFeeAmount = $getServiceFeeAmount;

            $this->view->intLoggedinUserAgencySysId = $intLoggedinUserAgencySysId;
            $this->view->intLoggedinUserId = $intLoggedinUserId;
            $this->view->getTransportDetail = $getTransportDetail;

//            if ($flexiPackageList['PackSpecType'] != '12' && $isPlanViewed['IsPlanViewed'] == 0 && $flexiPackageList['IsShared'] == 1 && $isAgentLoggedIn == 0) {
//                $manageNotifications = $resultSetArr['manageNotifications'];
//                $emailSendId = trim($agencyData['PrimaryEmail']);
//                $fromName = (isset($agencyData['DisplayName']) && !empty($agencyData['DisplayName'])) ? trim($agencyData['DisplayName']) : trim(trim($agencyData['Title']));
//                $emailId = trim($agentDetail['EmailId']);
//                $html = new Zend_View();
//                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
//                $html->assign('type', 'proposalViewPackageSendEmailToAgent');
//                $html->assign('customerDetails', $getcustomerDetail);
//                $html->assign('agentDetails', $agentDetail);
//                $html->assign('agencyDetails', $agencyData);
//                $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpID), 1);
//                $link = $this->view->baseUrl("/publicpackage/view-customer-final-package/id/" . base64_encode($tpID) . "/code/" . $secureCode);
//                $html->assign('link', $link);
//                $html->assign('data', $flexiPackageList);
//                $bodyText = $html->render('email-template.phtml');
//                $subject = 'HelloGTX - Proposal Open Alert !';
//                if ($agencyData['IsDisplayHelloGTX'] == 1) {
//                    $subject = $fromName . ' - Proposal Open Alert !';
//                }
//                $emailData = array('fromEmail' => trim($emailSendId), 'fromName' => trim($fromName), 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
//                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
//                $params['arrEmailStatisticsType'] = $arrEmailStatisticsType[2];
//                $arrEmailStatistics = array(
//                    "TPSysId" => $flexiPackageList['TPSysId'],
//                    "TypeSysId" => 1, // 1 For Email 2 For SMS
//                    "AgencySysId" => $flexiPackageList['AgencySysId'],
//                    "AgentSysId" => $flexiPackageList['AgentSysId'],
//                    "Title" => $bodyText,
//                    "Source" => isset($params['arrEmailStatisticsType']) ? $params['arrEmailStatisticsType'] : '', // 1 For Fresh Proposals
//                    "Status" => 0,
//                    "RefSysId" => "",
//                    "RefSysStatus" => "",
//                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
//                );
//                if (in_array('EmailOpenAlert', $manageNotifications)) {
//                    $mailsend = $this->mailSentByElastice($emailData, $arrEmailStatistics, 0, 0);
//                }
//                $getAgentDetails = $resultSetArr['getAgentDetails'];
//                $countrycode = (strpos($getCustomerDetail[0]['countrycode'], '+') !== false) ? $getCustomerDetail[0]['countrycode'] : "+" . $getCustomerDetail[0]['countrycode'];
//                $CustomerMobileNumber = trim($countrycode) . '' . trim($getCustomerDetail[0]['Contacts']);
//                $customerFirstName = trim($getCustomerDetail[0]['FirstName']);
//                $destination = (isset($flexiPackageList['DestinationPlaces']) && !empty($flexiPackageList['DestinationPlaces'])) ? trim($flexiPackageList['DestinationPlaces']) : '';
//                $postData = array(
//                    "UserSysId" => trim($flexiPackageList['AgentSysId']),
//                    "schedule_time" => "",
//                    "title" => "Proposal Open Alert",
//                    "body" => "Boom! Proposal Unlocked! $customerFirstName just opened the $destination proposal.",
//                    "URL" => "",
//                    "IsCall" => true,
//                    "mobileNo" => trim($CustomerMobileNumber)
//                );
//                if (isset($getAgentDetails['SecurityKey'])) {
//                    $curl = curl_init();
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => 'https://globaltravelexchange.com/gtxwebservices/agency/create-fire-base-message',
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => '',
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 0,
//                        CURLOPT_FOLLOWLOCATION => true,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => 'POST',
//                        CURLOPT_POSTFIELDS => $postData,
//                        CURLOPT_HTTPHEADER => array(
//                            'securitykey:' . trim($getAgentDetails['SecurityKey']),
//                        ),
//                    ));
//                    $response = curl_exec($curl);
//                    curl_close($curl);
//                }
//                $mobile_no = trim($agentDetail['ContactNo1']);
//                $params['TPSysId'] = $tpID;
//                $params['shared_url'] = $link;
//                $params['AgencySysId'] = $flexiPackageList['AgencySysId'];
//                $params['AgentSysId'] = $flexiPackageList['AgentSysId'];
//                $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
//                $params['arrSMSStatisticsType'] = $arrSMSStatisticsType[0];
//                $shorturl_response = Zend_Controller_Action_HelperBroker::getStaticHelper('ShortUrl')->url_get($params);
//                if (isset($shorturl_response['status_code']) && $shorturl_response['status_code'] == 200) {
//                    $link = $shorturl_response['data']['short_url'];
//                }
//                $RoomInfoJson = json_decode($flexiPackageList['RoomInfoJson'], true);
//                $departuredate = isset($RoomInfoJson[1]['departuredate']) ? $RoomInfoJson[1]['departuredate'] : '';
//                $AgentFirstName = trim($agentDetail['FirstName']) . ' ' . trim($agentDetail['LastName']);
//                $custPhone = trim($getcustomerDetail[0]['Contacts']);
//                $massage = "Dear " . trim($AgentFirstName) . ",\n" . trim($getcustomerDetail[0]['FirstName']) . " " . trim($getcustomerDetail[0]['LastName']) . " has just opened the proposal for " . trim(stripslashes($flexiPackageList['DestinationPlaces'])) . " using link " . $link . ". Call at " . $custPhone . " to help in trip planning.\nHappy Selling\nTRVCRM";
//
//                $this->postFields = "";
//                $this->postFields .= "&method=$this->SMSMETHOD";
//                $this->postFields .= "&api_key=$this->SMSAPIKEY";
//                $this->postFields .= "&to=$mobile_no";
//                $this->postFields .= "&sender=$this->SMSSENDER";
//                $this->postFields .= "&message=$massage";
//                $this->postFields .= "&format=$this->SMSFORMAT";
//                $postURL = $this->SMSURL;
//                // Added By Amit For SMS Count...
//                $arrSMSStatistics = array(
//                    "TPSysId" => isset($params['TPSysId']) ? $params['TPSysId'] : 0,
//                    "TypeSysId" => 2, // 1 For Email 2 For SMS
//                    "AgencySysId" => isset($params['AgencySysId']) ? $params['AgencySysId'] : 0,
//                    "AgentSysId" => isset($params['AgentSysId']) ? $params['AgentSysId'] : 0,
//                    "Title" => $massage,
//                    "Source" => isset($params['arrSMSStatisticsType']) ? $params['arrSMSStatisticsType'] : 1, // 2 Resend Proposals (Bulk)
//                    "Status" => '',
//                    "RefSysId" => '',
//                    "RefSysStatus" => "",
//                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
//                );
//                if (in_array('SMSOpenAlert', $manageNotifications)) {
//                    //$resultVal = $updateData->sendSmsDetails($postURL, $this->postFields, $arrSMSStatistics);
//                    $resultVal['status'] = 'OK';
//                    if (isset($resultVal['status']) && $resultVal['status'] == 'OK') {
//                        $errorMessage = "";
//                    } else {
//                        $errorMessage = "Oops! Please try again";
//                    }
//                }
//                $data = array(
//                    'IsPlanViewed' => 1,
//                    'UpdateDate' => date('Y-m-d H:i:s'),
//                );
//                $where = "TPSysId = " . $tpID;
//                $updatetravelplanrecord = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($data, $where);
//            }
        }
    }

    public function sendProposalToCustomerAction() {
        //                Zend_Session::destroy(); // to destroy package booking page session

        $this->_helper->layout->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;
        //echo "<pre>";print_r($this->getRequest()->getParam('cid'));
        //echo "<pre>";print_r($this->getRequest()->getParam('qId'));exit;
        $intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $tpID = base64_decode($this->getRequest()->getParam('id'));
        $CustomerSysId = (NULL != $this->getRequest()->getParam('cid')) ? base64_decode($this->getRequest()->getParam('cid')) : '';
        $queryTPSysId = (NULL != $this->getRequest()->getParam('qId')) ? base64_decode($this->getRequest()->getParam('qId')) : '';
        $code = $this->getRequest()->getParam('code');
        $email_id = $this->getRequest()->getParam('email_id');
        $subject = $this->getRequest()->getParam('subject');
        $addMarkup = (int) $this->getRequest()->getParam('addMarkup');
        if (trim($email_id) == '') {
            $reply = array('success' => false, 'msg' => 'Please enter email id');
            echo json_encode($reply);
            exit;
        }
        if (trim($subject) == '') {
            $reply = array('success' => false, 'msg' => 'Please enter sunject');
            echo json_encode($reply);
            exit;
        }
        $this->view->code = $code;
        $secureCode = Catabatic_ValidateCustomer::secureCode(trim($this->getRequest()->getParam('id')), 1);
        if ($secureCode != $code) {
            echo "Please check your request parameters";
            exit;
        }
        //die;
        // Added By Pardeep Panchal for Show T & C If Shared From GTX Network..............
        $strUrlData = ($this->getRequest()->getParam('data') != '') ? $this->getRequest()->getParam('data') : '';
        if ($strUrlData != '') {
            $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);
            //echo "<pre>";print_r($arrUrlData);exit;
            $packid = $arrUrlData['packid'];
            $this->view->isfromgtxnetwork = $isfromgtxnetwork = $arrUrlData['isfromgtxnetwork'];
            $intLoggedinUserAgencySysId = $arrUrlData['intLoggedinUserAgencySysId'];

            $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
            $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($intLoggedinUserAgencySysId, $packid);
        }






        if ($tpID > 0) {

            $flexiPackageList = $objPackage->getCustPackageList($tpID);

            if (isset($flexiPackageList['IsGTXNetwork']) && !empty($flexiPackageList['IsGTXNetwork'])) {
                $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
                $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($flexiPackageList['AgencySysId'], $flexiPackageList['TPId']);
            }
            //echo '<pre>';print_r($arrCustomizeTNCData);die;
            $objSupplier = new Travel_Model_TblSupplier();
            $PkgSupplierDetails = $objSupplier->getSupplierList($flexiPackageList['SupplierSysId']);
            //print_r($hotelDetails);
            $objSupplier->SupplierSysId = $flexiPackageList['SupplierSysId'];
            $packageSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $flexiPackageList['SupplierSysId']);

            if (isset($flexiPackageList['DestinationCovered']) && !empty($flexiPackageList['DestinationCovered'])) {
                $cityobj = new Travel_Model_TblCity();
                $cityIds = trim($flexiPackageList['DestinationCovered']);
                $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                $this->view->otherlocationcity = $otherlocationcity;
                //            echo '<pre>';print_r($otherlocationcity);die;
            }

            //echo "<pre>";print_r($flexiPackageList);die;
            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $getcustomerDetail = $objCusttravelplan->GetTravelPlanDetailsofCustomer($tpID);
            if ($getcustomerDetail[0]['CustomerSysId'] == '' && $CustomerSysId != '') {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $fetchRecord = $this->_crmcustomerObj->GetAgencyCustomerById(trim($CustomerSysId));
                $getcustomerDetail[0]['CustomerSysId'] = $fetchRecord['CustomerSysId'];
                $getcustomerDetail[0]['EmailId'] = $fetchRecord['EmailId'];
                $getcustomerDetail[0]['Contacts'] = $fetchRecord['Contacts'];
                $getcustomerDetail[0]['FirstName'] = $fetchRecord['FirstName'];
                $getcustomerDetail[0]['Salutation'] = $fetchRecord['Title'];
                $getcustomerDetail[0]['LastName'] = $fetchRecord['LastName'];
                $getcustomerDetail[0]['IsB2BAgent'] = $fetchRecord['IsB2BAgent'];
                $getcustomerDetail[0]['countrycode'] = $fetchRecord['countrycode'];
            }
            //echo "<pre>";print_r($fetchRecord);die;
            $IsB2BProposal = isset($flexiPackageList['IsB2BProposal']) ? $flexiPackageList['IsB2BProposal'] : 0;
            if ($IsB2BProposal == 1) {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }

            if ($flexiPackageList['MasterTPSysId'] == '0') {
                $childpackarr = $objCusttravelplan->GetVersionInfo($tpID);
            } else {
                $childpackarr = $objCusttravelplan->GetVersionInfo($flexiPackageList['MasterTPSysId']);
            }

            //            echo '<pre>'; print_r($childpackarr); die;

            $packRates = array();
            $tppackRate = array();
            if ($flexiPackageList['PackSpecType'] != '3' && $flexiPackageList['PackSpecType'] != '12') {
                //  echo "hello"; exit;
                foreach ($childpackarr as $key => $proposal) {
                    $StartDateTime = (array) $proposal['StartDate'];
                    $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));
                    //                $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripdate'])));
                    $packRates = $objPackage->getCustPackRate($proposal['TPSysId'], '', $TripDate);
                    $objCust = new Travel_Model_CRM_CustomerTravelPlan();
                    $tppackRate = $objCust->getCustTravelPackRate($proposal['TPSysId'], $TripDate);
                    $tppackRates = @$tppackRate[0];
                    $this->view->marketwiserate = $packRate = @$packRates[0];
                    $arrPkg['DiscountType'] = $proposal['DiscountType'];
                    $arrPkg['DiscountVal'] = $proposal['DiscountVal'];
                    $arrPkg['AdvBookingPercent'] = $proposal['AdvBookingPercent'];
                    //                echo '<pre>'; print_r($proposal); echo '</pre>';
                    $strRoomInfoJson = $proposal['RoomInfoJson'];
                    //Package Cost.....   
                    //if($flexiPackageList['PackSpecType'] != '3'){
                    $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetAgencyCustomerTravelPlanCost($proposal['TPSysId'], $strRoomInfoJson, $arrPkg, $packRate, $tppackRates);
                    $finalPackageCostWithDiscount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageCostwithDiscount($arrPkg, $arrPkgCost['FinalCost']);
                    $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
                    $taxdetailforagency = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax('', "P", 0);
                    $tax = (trim($taxdetailforagency['ServiceTaxPercentage']) > 0) ? trim(floatval($taxdetailforagency['ServiceTaxPercentage'])) : 0;
                    // $serviceTax = round(($proposal['MarkUp'] - $proposal['CustomDiscount']) * $tax / 100);
                    $gsttype = ($proposal['GSTSharedMode'] == 0) ? 1 : $proposal['GSTSharedMode'];
                    $GSTApplicableOn = $gsttype;
                    $packageCost = $finalPackageCostWithMarkupnTax;
                    $AgencyMarkUp = $arrPkgCost['FinalMarkUp'];
                    $AgencyExtraMarkUp = $proposal['MarkUp'];
                    $AgencyDiscount = $proposal['CustomDiscount'];
                    $intProductType = 9;
                    $intProductGeoType = 1; // 1 For Domestic, 2 For International

                    $arrInputData = array(
                        "GSTApplicableOn" => $GSTApplicableOn,
                        "intProductType" => $intProductType,
                        "intProductGeoType" => $intProductGeoType,
                        "Cost" => $packageCost,
                        "AgencyMarkUp" => $AgencyMarkUp,
                        "AgencyExtraMarkUp" => $AgencyExtraMarkUp,
                        "AgencyDiscount" => $AgencyDiscount
                    );
                    //print_r($arrInputData);
                    $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
                    $serviceTax = trim($arrGSTCalculations['GSTAmount']);

                    $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWithMarkupnTax + round($proposal['MarkUp']) + $serviceTax - round($proposal['CustomDiscount']);

                    $childpackarr[$key]['GrandTotal'] = $finalPackageCostWith_extramarkupNdiscount;
                    $childpackarr[$key]['arrPkgCost'] = $arrPkgCost;
                }
            }
            $this->view->proposalList = $childpackarr;
            // echo 'prashant';exit;
            $packageTncList = $objPackage->getCustPackageTncList($tpID);
            $flexiPackageList['tncDetails'] = $packageTncList;

            //for agency details
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
            $agencyObj = new Travel_Model_TblAgency();
            $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
            //            echo "<pre>".print_r($getAgencyDetail['AgencySysId']);die;
            $flexiPackageList['agencyDetails'] = $getAgencyDetail;
            $flexiPackageList['agentDetails'] = $getAgentDetail;
            $inclusionMastArray = $objPackage->getPackageInclusionList();
            //print_r($flexiPackageList['InclMask']);
            $inclusionArr = $objPackage->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
            $flexiPackageList['inclusionDetails'] = $inclusionArr;
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->PkgSupplierDetails = $PkgSupplierDetails;
            $this->view->packageSupplierDetails = $packageSupplierDetails;
            //echo "<pre>";print_r($packageSupplierDetails);die;
            if ($flexiPackageList['PackSpecType'] == '12') {
                $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotelsForB2BOptinal($flexiPackageList['TPSysId']);

                //echo "<pre>";print_r($gettransportoption);exit;
            } else {
                $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotels($flexiPackageList['TPSysId']); // for only hotel overview
            }
            //echo "<pre>";print_r($hotelarr);exit;
            $this->view->hotelarr = $hotelarr;

            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
            $flexiPackageAllDetailsList = $objPackage->getCustPackageAllDetailsList($tpID);
            //echo "<pre>";print_r($flexiPackageAllDetailsList);die;
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            $this->view->flexiPackageAllDetailsList = $flexiPackageAllDetailsList;
            $objCity = new Travel_Model_TblCity();
            if (!empty($flexiPackageItenList)) {
                $this->view->cityMainDetail = $objCity->getCityImagesDetailsById($flexiPackageItenList[0]['PlaceSysId'], 1, 1);
            }
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;

            $tourID = $this->getRequest()->getParam('tID');
            $this->view->tourID = $tourID = !empty($tourID) ? $tourID : $flexiPackageList['TourType'];
            //Get Package Hotels

            $packType = $flexiPackageList['PackSpecType'];

            if ($flexiPackageList['PackSpecType'] == '3') { // only for dynamic proposal
                $gettransportoption = $objPackage->GetTransPortOption($tpID);
                $totaltransport = array_sum(array_column($gettransportoption, 'total'));
                $this->view->totaltransportCount = $totaltransport;

                $catID = $this->getRequest()->getParam('cID');
                $mealID = $this->getRequest()->getParam('mID');
                $this->view->catID = $catID = !empty($catID) ? $catID : $flexiPackageList['EconomyMask']; // only for dynamic
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID, @$catID, $packType);

                $getotherservices = $this->_crmcusttravelplan->GetOtherServices($tpID);
                $gettransportdata = $this->_crmcusttravelplan->GetAllTransportOption($tpID);
                $this->view->getotherservices = $getotherservices;
                $this->view->gettransportdata = $gettransportdata;
                $flexiPackageHotelListArr1 = $flexiPackageHotelMealPlanWiseListArr = array();
                for ($h = 0; $h < count(@$flexiPackageHotelsList); $h++) {
                    if ($flexiPackageHotelsList[$h]['IsSelectedOnPkg'] == '1') {
                        $flexiPackageHotelListArr1[] = $flexiPackageHotelsList[$h];
                        $flexiPackageHotelMealPlanWiseListArr[$flexiPackageHotelsList[$h]['MealPlanType']][] = $flexiPackageHotelsList[$h];
                    }
                }

                $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList);
                $totalNight = $totalDaysNightsArr['totalnights'];
                $PackageCostCalType = $flexiPackageList['PackageCostCalType'];
                if ($PackageCostCalType) {
                    $PossibleCombinationsOfMealPlanArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPossibleCombinationsOfMealPlan($flexiPackageHotelListArr1, $totalNight, $catID);
                    $this->view->possibleCombinationsOfMealPlanArr = $PossibleCombinationsOfMealPlanArr;
                }

                //                echo '<pre>';print_r($PossibleCombinationsOfMealPlanArr); print_r($flexiPackageHotelsList); die;
                //                $mIDArr = array_keys($PossibleCombinationsOfMealPlanArr); // need a column for this in database
                $this->view->mID = $mID = !empty($mealID) ? $mealID : $flexiPackageList['SharedMealPlanType'];
                $this->view->flexiPackageHotelsList = !empty($PackageCostCalType) ? $flexiPackageHotelMealPlanWiseListArr[$mID] : $flexiPackageHotelsList;

                $marketwiseratebyo = $this->_crmcusttravelplan->GetMarketWiseRateBYOReadyMade($tpID, @$catID, $tourID, $mID, $MarketPlaceId);

                $this->view->marketwiseratebyo = $marketwiseratebyo;
            } else { // condition for readymade package
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsListReadymade($tpID);
                $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;

                $itenArray = $this->_crmcusttravelplan->getPackItenId($tpID, 2);
                //             echo "<pre>"; print_r($itenArray);die;
                $StartDateTime = (array) $flexiPackageList['StartDate'];
                $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));

                $ssdaywisearr = $this->_crmcusttravelplan->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $TripDate);
                $this->view->ssdaywisearr = $ssdaywisearr;

                $objActivities = new Travel_Model_TblActivities();
                $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($getAgencyDetail['AgencySysId'], $MarketPlaceId);
                //                echo "<pre>"; print_r($itenArray);die;
                $this->view->arrStandardNativesMarkups = $arrStandardMarkups;
            }
            //        $flexiPackageList = $objPackage->getCustPackageList($packid);
            //            


            if ($flexiPackageList['PackSpecType'] == 2) {
                $resflexiPackageActivityOnlyHotel = $objPackage->getCustPackageActivityListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageActivityList = $resflexiPackageActivityOnlyHotel;
                $resflexiPackageSSOnlyHotel = $objPackage->getCustPackageSightseenListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageSightseenList = $resflexiPackageSSOnlyHotel;
            } else {
                //Get Package Activity
                $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
                $this->view->flexiPackageActivityList = $flexiPackageActivityList;
                //Get Package Sightseen
                $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
                $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            }
            $this->view->gettransportdata = $gettransportdata = $this->_crmcusttravelplan->GetAllQuickTransportOption($flexiPackageList['TPSysId']);
            //            echo "<pre>"; print_r($gettransportdata);die;

            $getpacktypemask = $objPackage->GetMasterPackageList();
            $this->view->packtypemask = $getpacktypemask;

            //Get Package Flight
            //            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            //            $this->view->flexiPackageFlight = $flexiPackageFlight;
            ########## Code Added By Shobhit ##################
            $this->view->tpID = $tpID;
            $getcustomerDetail[0]['AgentName'] = trim($getAgentDetail['FirstName']) . ' ' . trim($getAgentDetail['LastName']);
            $getcustomerDetail[0]['AgentNo'] = $getAgentDetail['ContactNo1'];
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            $objAgency = new Travel_Model_TblAgency();
            $agencyData = $objAgency->getAgencyDataById($flexiPackageList['AgencySysId']);
            $this->view->getAgencyData = $agencyData;

            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
            $getChatHistoryDetail = array();
            $checkCustomerChatExist = (@$getcustomerDetail[0]['CustomerSysId'] > 0) ? $objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID, trim($flexiPackageList['AgentSysId'])) : array();
            // $checkCustomerChatExist = (count($checkCustomerChatExist)==0)?$objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID):$checkCustomerChatExist;
            if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'ASC');
            }
            $getcustomerDetail['userChatExist'] = (count($checkCustomerChatExist) > 0) ? count($checkCustomerChatExist) : count($getChatHistoryDetail);
            //  $this-view->getCustomerDetails = $getcustomerDetail;
            //query for get customer chat history
            $chatSenderDetails = array();
            $objAgencyStaff = new Travel_Model_TblAgencyStaff();
            $agentDetail = $objAgencyStaff->getUserDetailsById($flexiPackageList['AgentSysId']);
            if ($getcustomerDetail['userChatExist'] > 0) {
                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
                    $chatSenderDetails['TPSysId'] = $tpID;
                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
                    $chatSenderDetails['EmailId'] = $agentDetail['EmailId'];
                    //print_r($agentDetail);
                }
            }
            //end of customer chat history
            $getcustomerDetail['AgencyDetails'] = $agencyData;
            $chatSenderDetails['AgencyDetails'] = $agencyData;
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $getversiondetails;
            $this->view->chatSenderDetails = $chatSenderDetails;

            $termscond = $objPackage->getTermCond($tpID);
            $this->view->termc = $termscond;

            $rateList = array('arrPkgCost' => array('AdultPax' => $flexiPackageList['MinPax'], 'ChildPax' => 0, 'FinalCost' => $flexiPackageList['NetPrice'], 'FinalDiscount' => $flexiPackageList['DiscountVal'], 'FinalMarkUp' => 0));
            $popupArray = array();
            $popupArray['rateList'] = json_encode($rateList);

            $this->view->popupArray = $popupArray;
            //print_r($agentDetail);
            //send email to agent when customer open proposal
            $isPlanViewed = $this->_crmcusttravelplan->GetTravelPlanType($tpID);
            //echo "<pre>";print_r($getAgencyDetail);
            //echo $isPlanViewed['IsPlanViewed'];die;
            if ($this->getRequest()->isXmlHttpRequest()) {
                $request = Zend_Controller_Front::getInstance()->getRequest();
                $post = $request->getPost();
                $Logo = $getAgencyDetail['Logo'];
                $path = SITE_FULL_URL . 'public/assets/images';
                $pathAgency = SITE_FULL_URL . 'public/upload/media/agency/' . $getAgencyDetail['AgencySysId'];
                if (isset($Logo) && $Logo != '') {
                    $AgencyLogo = $pathAgency . '/' . $Logo;
                } else {
                    $AgencyLogo = $path . '/gtx-logo-white.png';
                }
                $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($flexiPackageList['TPSysId']), 1);
                $link = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . base64_encode($flexiPackageList['TPSysId']) . '/code/' . $secureCode;
                //echo "<pre>";print_r($getcustomerDetail);exit;
                $paramArray = array(
                    'flexiPackageList' => $flexiPackageList,
                    'marketwiserate' => @$packRates[0],
                    'proposalList' => $childpackarr,
                    'packtypemask' => $getpacktypemask,
                    'flexiPackageItenList' => $flexiPackageItenList,
                    'queryTPSysId' => $queryTPSysId,
                    'marketwiseratebyo' => isset($marketwiseratebyo) ? $marketwiseratebyo : '',
                    'possibleCombinationsOfMealPlanArr' => isset($PossibleCombinationsOfMealPlanArr) ? $PossibleCombinationsOfMealPlanArr : '',
                    'mID' => isset($mID) ? $mID : '',
                    'tpID' => $tpID,
                    'catID' => isset($catID) ? $catID : '',
                    'tourID' => $tourID,
                    'flexiPackagePlaces' => $flexiPackagePlaces,
                    'getcustomerDetail' => $getcustomerDetail,
                    'termscond' => $termscond,
                    'flexiPackageHotelsList' => $flexiPackageHotelsList,
                    'flexiPackageActivityList' => $flexiPackageActivityList,
                    'flexiPackageSightseenList' => $flexiPackageSightseenList,
                    'arrCustomizeTNCData' => isset($arrCustomizeTNCData) ? $arrCustomizeTNCData : '',
                    'isfromgtxnetwork' => isset($isfromgtxnetwork) ? $isfromgtxnetwork : '',
                    'ssdaywisearr' => $ssdaywisearr,
                    'arrStandardNativesMarkups' => $arrStandardMarkups,
                    'intLoggedinUserAgencySysId' => $intLoggedinUserAgencySysId,
                    'isAgentLoggedIn' => $isAgentLoggedIn,
                    'getAgencyDetail' => $getAgencyDetail,
                    'getAgentDetail' => $getAgentDetail,
                    'AgencyLogo' => $AgencyLogo,
                    'addMarkup' => $addMarkup,
                    'hotelarr' => $hotelarr,
                    'proposallink' => $link,
                    'otherlocationcity' => isset($otherlocationcity) ? $otherlocationcity : '',
                );
                //echo '<pre>';print_r($paramArray);die;
                $subject = $subject;

                $response = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendProposalToB2BCustomer($email_id, $subject, $paramArray);
                //print_r($response);die;
                if ($response == 1) {
                    $reply = array('success' => true, 'msg' => 'Proposal has been shared with customer');
                    echo json_encode($reply);
                    exit;
                } else {
                    $reply = array('success' => true, 'msg' => 'There is some error in sending email. Please try after sometime.');
                    echo json_encode($reply);
                    exit;
                }
                die('ok');
            }
        }
    }

//    public function viewCustomerFinalPackageNew_oldAction() {
//        $this->_helper->layout->disableLayout();
//        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
//        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
//        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;
//        $intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
//        $objPackage = new Travel_Model_TblPackage();
//        $dynaminpackagexml = new Gtxwebservices_Model_GetPackageDetailForCustomer();
//        $tpID = trim(base64_decode($this->getRequest()->getParam('id')));
//        $CustomerSysId = (NULL != $this->getRequest()->getParam('cid')) ? base64_decode($this->getRequest()->getParam('cid')) : '';
//        // Added By Pardeep Panchal for Show T & C If Shared From GTX Network..............
//        $strUrlData = ($this->getRequest()->getParam('data') != '') ? $this->getRequest()->getParam('data') : '';
//        if ($strUrlData != '') {
//            $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);
//            $packid = $arrUrlData['packid'];
//            $this->view->isfromgtxnetwork = $isfromgtxnetwork = $arrUrlData['isfromgtxnetwork'];
//            $intLoggedinUserAgencySysId = $arrUrlData['intLoggedinUserAgencySysId'];
//            $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
//            $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($intLoggedinUserAgencySysId, $packid);
//        }
//
//        $resultSet = $dynaminpackagexml->checkPackageType($tpID);
//        if (is_array($resultSet) && $resultSet[0]["PackSpecType"] == 3) {
//            $finalResultset = $dynaminpackagexml->getPackageDetailForCustomer($tpID);
//            $flexiPackageList = $finalResultset['Result1'][0];
//            //$objSupplier = new Travel_Model_TblSupplier();
//            //$PkgSupplierDetails = $objSupplier->getSupplierList($flexiPackageList['SupplierSysId']);
//            //$this->view->PkgSupplierDetails = $PkgSupplierDetails;
//            //$objSupplier->SupplierSysId = $flexiPackageList['SupplierSysId'];
//            //$packageSupplierDetails = $objSupplier->getSuppliersDetailsById();
//            //$this->view->packageSupplierDetails = $packageSupplierDetails;
//            //  echo "<pre>";print_r($packageSupplierDetails);die;
//            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
//            //$getcustomerDetail = $objCusttravelplan->GetTravelPlanDetailsofCustomer($tpID);
//            $getcustomerDetail = $resultSet;
//            if ($getcustomerDetail[0]['CustomerSysId'] == '' && $CustomerSysId != '') {
//                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
//                $fetchRecord = $this->_crmcustomerObj->GetAgencyCustomerById(trim($CustomerSysId));
//                $getcustomerDetail[0]['CustomerSysId'] = $fetchRecord['CustomerSysId'];
//                $getcustomerDetail[0]['EmailId'] = $fetchRecord['EmailId'];
//                $getcustomerDetail[0]['Contacts'] = $fetchRecord['Contacts'];
//                $getcustomerDetail[0]['FirstName'] = $fetchRecord['FirstName'];
//                $getcustomerDetail[0]['Salutation'] = $fetchRecord['Title'];
//                $getcustomerDetail[0]['LastName'] = $fetchRecord['LastName'];
//                $getcustomerDetail[0]['IsB2BAgent'] = $fetchRecord['IsB2BAgent'];
//            }
//            $IsB2BProposal = isset($flexiPackageList['IsB2BProposal']) ? $flexiPackageList['IsB2BProposal'] : 0;
//            if ($IsB2BProposal == 1) {
//                $MarketPlaceId = 2;
//            } else {
//                $MarketPlaceId = 1;
//            }
//
//            //            if ($flexiPackageList['MasterTPSysId'] == '0') {
//            //                $childpackarr = $objCusttravelplan->GetVersionInfo($tpID);
//            //            } else {
//            //                $childpackarr = $objCusttravelplan->GetVersionInfo($flexiPackageList['MasterTPSysId']);
//            //            }
//            $childpackarr = $finalResultset['Result1'];
//            //echo '<pre>'; print_r($childpackarr); die;
//            //  $packRates = array();
//            //  $tppackRate = array();
//            //            if($flexiPackageList['PackSpecType'] != '3'){
//            //            foreach ($childpackarr as $key => $proposal) {
//            //                $StartDateTime = (array) $proposal['StartDate'];
//            //                $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));
//            ////                $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripdate'])));
//            //                $packRates = $objPackage->getCustPackRate($proposal['TPSysId'], '', $TripDate);
//            //                $objCust = new Travel_Model_CRM_CustomerTravelPlan();
//            //                $tppackRate = $objCust->getCustTravelPackRate($proposal['TPSysId'], $TripDate);
//            //                $tppackRates = @$tppackRate[0];
//            //                $packRate = @$packRates[0];
//            //                $arrPkg['DiscountType'] = $proposal['DiscountType'];
//            //                $arrPkg['DiscountVal'] = $proposal['DiscountVal'];
//            //                $arrPkg['AdvBookingPercent'] = $proposal['AdvBookingPercent'];
//            //                //echo '<pre>'; print_r($proposal); echo '</pre>';
//            //                $strRoomInfoJson = $proposal['RoomInfoJson'];
//            //                //Package Cost.....   
//            ////if($flexiPackageList['PackSpecType'] != '3'){
//            //                $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetAgencyCustomerTravelPlanCost($proposal['TPSysId'], $strRoomInfoJson, $arrPkg, $packRate, $tppackRates);
//            //                $finalPackageCostWithDiscount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageCostwithDiscount($arrPkg, $arrPkgCost['FinalCost']);
//            //                $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
//            //                $taxdetailforagency = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax('', "P", 0);
//            //                $tax = (trim($taxdetailforagency['ServiceTaxPercentage']) > 0) ? trim(floatval($taxdetailforagency['ServiceTaxPercentage'])) : 0;
//            //               // $serviceTax = round(($proposal['MarkUp'] - $proposal['CustomDiscount']) * $tax / 100);
//            //						$gsttype=($proposal['GSTSharedMode']==0)?1:$proposal['GSTSharedMode'];
//            //						$GSTApplicableOn    = $gsttype;
//            //						$packageCost        = $finalPackageCostWithMarkupnTax;
//            //						$AgencyMarkUp       = $arrPkgCost['FinalMarkUp'];
//            //						$AgencyExtraMarkUp  = $proposal['MarkUp'];
//            //						$AgencyDiscount     = $proposal['CustomDiscount'];
//            //						$intProductType     = 9;
//            //						$intProductGeoType  = 1; // 1 For Domestic, 2 For International
//            //								
//            //						$arrInputData = array(
//            //											"GSTApplicableOn"   => $GSTApplicableOn,
//            //											"intProductType"    => $intProductType,
//            //											"intProductGeoType" => $intProductGeoType,
//            //											"Cost"              => $packageCost,
//            //											"AgencyMarkUp"      => $AgencyMarkUp,
//            //											"AgencyExtraMarkUp" => $AgencyExtraMarkUp,
//            //											"AgencyDiscount"    => $AgencyDiscount
//            //										);
//            //					//print_r($arrInputData);
//            //				$arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
//            //				$serviceTax=trim($arrGSTCalculations['GSTAmount']);
//            //						
//            //                $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWithMarkupnTax + round($proposal['MarkUp']) + $serviceTax -round($proposal['CustomDiscount']);
//            //
//            //                $childpackarr[$key]['GrandTotal'] = $finalPackageCostWith_extramarkupNdiscount;
//            //            }}
//            $this->view->proposalList = $childpackarr;
//            $packageTncList = $finalResultset['Result6'];
//            // $packageTncList = $objPackage->getCustPackageTncList($tpID);
//            //echo "<pre>";print_r($packageTncList);exit;
//            $flexiPackageList['tncDetails'] = $packageTncList;
//
//            //for agency details
//            $crmcustomerObj = new Travel_Model_CRM_Customer();
//            //$getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
//            // echo "<pre>";print_r($getAgencyDetail);die;
//            $getAgencyDetail = $resultSet[0];
//            $agencyObj = new Travel_Model_TblAgency();
//            // $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
//            $getAgentDetail = $resultSet[0];
//            //echo "<pre>";print_r($getAgentDetail);die;
//            $flexiPackageList['agencyDetails'] = $getAgencyDetail;
//            $flexiPackageList['agentDetails'] = $getAgentDetail;
//            //$inclusionMastArray = $objPackage->getPackageInclusionList();
//            $inclusionMastArray = $finalResultset['Result11'];
//            $inclusionArr = $objPackage->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
//            $flexiPackageList['inclusionDetails'] = $inclusionArr;
//            $this->view->flexiPackageList = $flexiPackageList;
//
//
//
//            $hotelarr = $finalResultset['Result3'];
//
//            //$hotelarr = $objPackage->getCustomerFlexiPackageFinalHotels($flexiPackageList['TPSysId']); // for only hotel overview
//
//            $this->view->hotelarr = $hotelarr;
//
//            $flexiPackageItenList = $finalResultset['Result2'];
//            $flexiPackageAllDetailsList = $finalResultset['Result2'];
//            // $flexiPackageAllDetailsList = $objPackage->getCustPackageAllDetailsList($tpID);
//            //echo "<pre>";print_r($flexiPackageAllDetailsList);exit;
//            $this->view->flexiPackageItenList = $flexiPackageItenList;
//            $this->view->flexiPackageAllDetailsList = $flexiPackageAllDetailsList;
//            $objCity = new Travel_Model_TblCity();
//            $this->view->cityMainDetail = $objCity->getCityImagesDetailsById($flexiPackageItenList[0]['PlaceSysId'], 1, 1);
//            //Get Package Places 
//            $flexiPackagePlaces = $finalResultset['Result7'];
//            //$flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID);
//            $this->view->flexiPackagePlaces = $flexiPackagePlaces;
//
//
//            $tourID = $this->getRequest()->getParam('tID');
//            $this->view->tourID = $tourID = !empty($tourID) ? $tourID : $flexiPackageList['TourType'];
//            //Get Package Hotels
//
//            $packType = $flexiPackageList['PackSpecType'];
//
//            //            if($flexiPackageList['PackSpecType'] == '3'){ // only for dynamic proposal
//            //$gettransportoption = $objPackage->GetTransPortOption($tpID);
//            $gettransportoption = $finalResultset['Result9'];
//            //echo "<pre>";print_r($gettransportoption);exit;
//
//            $totaltransport = array_sum(array_column($gettransportoption, 'total'));
//            $this->view->totaltransportCount = $totaltransport;
//
//            $catID = $this->getRequest()->getParam('cID');
//            $mealID = $this->getRequest()->getParam('mID');
//            $this->view->catID = $catID = !empty($catID) ? $catID : $flexiPackageList['EconomyMask']; // only for dynamic
//            $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID, @$catID, $packType);
//
//            // $getotherservices = $this->_crmcusttravelplan->GetOtherServices($tpID);
//            // $gettransportdata = $this->_crmcusttravelplan->GetAllTransportOption($tpID);
//            $getotherservices = $finalResultset['Result8'];
//            $gettransportdata = $finalResultset['Result10'];
//            $this->view->getotherservices = $getotherservices;
//            $this->view->gettransportdata = $gettransportdata;
//            $flexiPackageHotelListArr1 = $flexiPackageHotelMealPlanWiseListArr = array();
//            for ($h = 0; $h < count(@$flexiPackageHotelsList); $h++) {
//                if ($flexiPackageHotelsList[$h]['IsSelectedOnPkg'] == '1') {
//                    $flexiPackageHotelListArr1[] = $flexiPackageHotelsList[$h];
//                    $flexiPackageHotelMealPlanWiseListArr[$flexiPackageHotelsList[$h]['MealPlanType']][] = $flexiPackageHotelsList[$h];
//                }
//            }
//
//            $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList);
//            $totalNight = $totalDaysNightsArr['totalnights'];
//            $PackageCostCalType = $flexiPackageList['PackageCostCalType'];
//            if ($PackageCostCalType) {
//                $PossibleCombinationsOfMealPlanArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPossibleCombinationsOfMealPlan($flexiPackageHotelListArr1, $totalNight, $catID);
//                $this->view->possibleCombinationsOfMealPlanArr = $PossibleCombinationsOfMealPlanArr;
//            }
//
//            //                echo '<pre>';print_r($PossibleCombinationsOfMealPlanArr); print_r($flexiPackageHotelsList); die;
//            //                $mIDArr = array_keys($PossibleCombinationsOfMealPlanArr); // need a column for this in database
//            $this->view->mID = $mID = !empty($mealID) ? $mealID : $flexiPackageList['SharedMealPlanType'];
//            $this->view->flexiPackageHotelsList = !empty($PackageCostCalType) ? $flexiPackageHotelMealPlanWiseListArr[$mID] : $flexiPackageHotelsList;
//
//            $marketwiseratebyo = $this->_crmcusttravelplan->GetMarketWiseRateBYOReadyMade($tpID, @$catID, $tourID, $mID, $MarketPlaceId);
//            $this->view->marketwiseratebyo = $marketwiseratebyo;
//            //            } else { // condition for readymade package
//            //            $flexiPackageHotelsList = $objPackage->getCustPackageHotelsListReadymade($tpID);
//            //            $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;
//            //            }
//            //        $flexiPackageList = $objPackage->getCustPackageList($packid);
//            //            
//            //            if ($flexiPackageList['PackSpecType'] == 2) {
//            //                $resflexiPackageActivityOnlyHotel = $objPackage->getCustPackageActivityListBySeq(@$flexiPackageList['TPSysId'], 2);
//            //                $this->view->flexiPackageActivityList = $resflexiPackageActivityOnlyHotel;
//            //                $resflexiPackageSSOnlyHotel = $objPackage->getCustPackageSightseenListBySeq(@$flexiPackageList['TPSysId'], 2);
//            //                $this->view->flexiPackageSightseenList = $resflexiPackageSSOnlyHotel;
//            //            } else {
//            //Get Package Activity
//            $flexiPackageActivityList = $finalResultset['Result5'];
//            // $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
//            $this->view->flexiPackageActivityList = $flexiPackageActivityList;
//            //Get Package Sightseen
//            $flexiPackageSightseenList = $finalResultset['Result4'];
//            //  $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
//            $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
//            // }
//
//
//            $getpacktypemask = $finalResultset['Result12'];
//            // $getpacktypemask = $objPackage->GetMasterPackageList();
//            $this->view->packtypemask = $getpacktypemask;
//
//            //Get Package Flight
//            //            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
//            //            $this->view->flexiPackageFlight = $flexiPackageFlight;
//            ########## Code Added By Shobhit ##################
//            $this->view->tpID = $tpID;
//            $getcustomerDetail[0]['AgentName'] = trim($getAgentDetail['AgentFirstName']) . ' ' . trim($getAgentDetail['AgentLastName']);
//            $getcustomerDetail[0]['AgentNo'] = $getAgentDetail['AgentContactNo1Name'];
//            //echo $tpID;
//            // $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID); need discussion
//            $getversiondetails = array();
//            //echo '<pre>'; print_r($getversiondetails);die;
//            $objAgency = new Travel_Model_TblAgency();
//            //$agencyData = $objAgency->getAgencyDataById($flexiPackageList['AgencySysId']);
//            //  echo "<pre>";print_r($agencyData);exit;
//            $agencyData = $resultSet[0];
//            //echo "<pre>";print_r($agencyData);exit;
//
//            $this->view->getAgencyData = $agencyData;
//
//            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
//            $getChatHistoryDetail = array();
//            $checkCustomerChatExist = (@$getcustomerDetail[0]['CustomerSysId'] > 0) ? $objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID, trim($flexiPackageList['AgentSysId'])) : array();
//            // $checkCustomerChatExist = (count($checkCustomerChatExist)==0)?$objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID):$checkCustomerChatExist;
//            if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
//                $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'ASC');
//            }
//            $getcustomerDetail['userChatExist'] = (count($checkCustomerChatExist) > 0) ? count($checkCustomerChatExist) : count($getChatHistoryDetail);
//            //  $this-view->getCustomerDetails = $getcustomerDetail;
//            //query for get customer chat history
//            $chatSenderDetails = array();
//            $objAgencyStaff = new Travel_Model_TblAgencyStaff();
//            //$agentDetail = $objAgencyStaff->getUserDetailsById($flexiPackageList['AgentSysId']);
//
//            $agentDetail = $getAgencyDetail;
//
//            if ($getcustomerDetail['userChatExist'] > 0) {
//                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
//                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
//                    $chatSenderDetails['TPSysId'] = $tpID;
//                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
//                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
//                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
//                    $chatSenderDetails['EmailId'] = $agentDetail['EmailId'];
//                    //print_r($agentDetail);
//                }
//            }
//            //end of customer chat history
//            $getcustomerDetail['AgencyDetails'] = $agencyData;
//            $chatSenderDetails['AgencyDetails'] = $agencyData;
//            //echo '<pre>'; print_r($getcustomerDetail);die;
//            $this->view->getcustomerDetail = $getcustomerDetail;
//            $this->view->getversionDetails = $getversiondetails;
//            $this->view->chatSenderDetails = $chatSenderDetails;
//            $termscond = $finalResultset['Result6'];
//            // $termscond = $objPackage->getTermCond($tpID);
//            //echo "<pre>";print_r($termscond);exit;
//
//            $this->view->termc = $termscond;
//
//            $rateList = array('arrPkgCost' => array('AdultPax' => $flexiPackageList['MinPax'], 'ChildPax' => 0, 'FinalCost' => $flexiPackageList['NetPrice'], 'FinalDiscount' => $flexiPackageList['DiscountVal'], 'FinalMarkUp' => 0));
//            $popupArray = array();
//            $popupArray['rateList'] = json_encode($rateList);
//
//            $this->view->popupArray = $popupArray;
//            //print_r($agentDetail);
//            //send email to agent when customer open proposal
//            //$isPlanViewed = $this->_crmcusttravelplan->GetTravelPlanType($tpID);
//            $isPlanViewed = $finalResultset['Result1'][0];
//            //echo "<pre>";print_r($flexiPackageList);
//            //echo $isPlanViewed['IsPlanViewed'];die;
//            if ($isPlanViewed['IsPlanViewed'] == 0 && $flexiPackageList['IsShared'] == 1 && $isAgentLoggedIn == 0) {
//                $emailSendId = trim($agencyData['PrimaryEmail']);
//                $fromName = (isset($agencyData['DisplayName']) && !empty($agencyData['DisplayName'])) ? trim($agencyData['DisplayName']) : trim(trim($agencyData['Title']));
//                $emailId = trim($agentDetail['EmailId']);
//                //$emailId = trim('amit.k@catpl.co.in');
//                $html = new Zend_View();
//                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
//                $html->assign('type', 'proposalViewPackageSendEmailToAgent');
//                $html->assign('customerDetails', $getcustomerDetail);
//                $html->assign('agentDetails', $agentDetail);
//                $html->assign('agencyDetails', $agencyData);
//                $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpID), 1);
//                $link = $this->view->baseUrl("/publicpackage/view-customer-final-package/id/" . base64_encode($tpID) . '/code/' . $secureCode);
//                $html->assign('link', $link);
//                $html->assign('data', $flexiPackageList);
//                //$html->assign('data', $hotelValues);
//                $bodyText = $html->render('email-template.phtml');
//                //$bodyText='Customer open your proposal' .$this->view->baseUrl("/proposal/preview-hotel-result/mid/".base64_encode($mid)."/pid/".base64_encode($pid)."/uid/".base64_encode($uid)."/type/".base64_encode($type));
//                //$bodyText='Customer open your proposal' .$this->view->baseUrl("/proposal/preview-hotel-result/mid/".base64_encode($mid)."/pid/".base64_encode($pid)."/uid/".base64_encode($uid)."/type/".base64_encode($type));
//                $subject = 'HelloGTX - Proposal Open Alert !';
//                if($agencyData['IsDisplayHelloGTX'] == 1){
//                    $subject = $fromName.' - Proposal Open Alert !';
//                }
//                $emailData = array('fromEmail' => trim($emailSendId), 'fromName' => trim($fromName), 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
//                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
//                $params['arrEmailStatisticsType'] = $arrEmailStatisticsType[2];
//                $arrEmailStatistics = array(
//                    "TPSysId" => $flexiPackageList['TPSysId'],
//                    "TypeSysId" => 1, // 1 For Email 2 For SMS
//                    "AgencySysId" => @$flexiPackageList['AgencySysId'],
//                    "AgentSysId" => @$flexiPackageList['AgentSysId'],
//                    "Title" => $bodyText,
//                    "Source" => @$params['arrEmailStatisticsType'], // 1 For Fresh Proposals
//                    "Status" => 0,
//                    "RefSysId" => "",
//                    "RefSysStatus" => "",
//                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
//                );
//                $this->mailSentByElastice($emailData, $arrEmailStatistics, 0, 0);
//
//                //send sms
//                $mobile_no = trim($agentDetail['ContactNo1']);
//                $updateData = new Payment_Model_Checkotp();
//                //$massage = "Your Customer(".trim($getcustomerDetail[0]['Contacts']).") has just opened the proposal. Team HelloGTX";
//                $params['TPSysId'] = $tpID;
//                $params['shared_url'] = $link;
//                $params['AgencySysId'] = $flexiPackageList['AgencySysId'];
//                $params['AgentSysId'] = $flexiPackageList['AgentSysId'];
//                $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
//                $params['arrSMSStatisticsType'] = $arrSMSStatisticsType[0];
//                $shorturl_response = Zend_Controller_Action_HelperBroker::getStaticHelper('ShortUrl')->url_get($params);
//                if (isset($shorturl_response['status_code']) && $shorturl_response['status_code'] == 200) {
//                    $link = $shorturl_response['data']['short_url'];
//                }
//                /* $bitly_response = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->getSmallLinkFromBitlyAPI($link, $this->BITLYLOGIN, $this->BITLYAPIKEY);
//                  if ($bitly_response['errorCode'] == 0) {
//                  $link = $bitly_response['results'][$link]['shortUrl'];
//                  } */
//                //print_r($link);die;
//                $RoomInfoJson = json_decode($flexiPackageList['RoomInfoJson'], true);
//                $departuredate = isset($RoomInfoJson[1]['departuredate']) ? $RoomInfoJson[1]['departuredate'] : '';
//                $massage = "Your Customer(" . trim($getcustomerDetail[0]['FirstName']) . " " . trim($getcustomerDetail[0]['LastName']) . "-" . trim($getcustomerDetail[0]['Contacts']) . ") has just opened the proposal for " . trim(stripslashes($flexiPackageList['DestinationPlaces'])) . ",Click: " . $link . " to view and assist for finalizing.";
//                $this->postFields = "";
//                $this->postFields .= "&method=$this->SMSMETHOD";
//                $this->postFields .= "&api_key=$this->SMSAPIKEY";
//                $this->postFields .= "&to=$mobile_no";
//                $this->postFields .= "&sender=$this->SMSSENDER";
//                $this->postFields .= "&message=$massage";
//                $this->postFields .= "&format=$this->SMSFORMAT";
//                $postURL = $this->SMSURL;
//                // Added By Amit For SMS Count...
//                $arrSMSStatistics = array(
//                    "TPSysId" => isset($params['TPSysId']) ? $params['TPSysId'] : 0,
//                    "TypeSysId" => 2, // 1 For Email 2 For SMS
//                    "AgencySysId" => isset($params['AgencySysId']) ? $params['AgencySysId'] : 0,
//                    "AgentSysId" => isset($params['AgentSysId']) ? $params['AgentSysId'] : 0,
//                    "Title" => $massage,
//                    "Source" => isset($params['arrSMSStatisticsType']) ? $params['arrSMSStatisticsType'] : 1, // 2 Resend Proposals (Bulk)
//                    "Status" => '',
//                    "RefSysId" => '',
//                    "RefSysStatus" => "",
//                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
//                );
//                //print_r($arrSMSStatistics);
//                // Added By AmitFor SMS Count Ends...
//                $resultVal = $updateData->sendSmsDetails($postURL, $this->postFields, $arrSMSStatistics);
//                if (isset($resultVal['status']) && $resultVal['status'] == 'OK') {
//                    $errorMessage = "";
//                } else {
//                    $errorMessage = "Oops! Please try again";
//                }
//                //echo $errorMessage."/".print_r($resultVal)."/".$massage."/".$mobile_no;
//                //end of send sms
//                $data = array(
//                    'IsPlanViewed' => 1,
//                    'UpdateDate' => date('Y-m-d H:i:s'),
//                );
//                $where = "TPSysId = " . $tpID;
//                $updatetravelplanrecord = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($data, $where);
//            }
//            //#end
//            //            $objHotel = new Travel_Model_TblHotel();
//            //            $objHotel->orderByField = " TB_Master_Accom_AccomAminity.AminityId";
//            //            $objHotel->orderBy = "";
//            //$arrAmenites = $objHotel->getMasterAccomAminities();
//            $arrAmenites = $finalResultset['Result13'];
//            $this->view->arrAmenites = $arrAmenites;
//
//            //        echo '<pre>'; print_r($gettransportdata); echo '</pre>'; die;
//        }
//        $this->view->intLoggedinUserAgencySysId = $intLoggedinUserAgencySysId;
//    }

    public function changePackageHotelByoAction() {
        /* Disable Layout */
        // ini_set('display_errors',0);
        $this->_helper->layout->disableLayout();
        $tpintsysId = $this->_request->getParam('itnID');
        $tpintsysId = $this->_request->getParam('itnID');
        $tpsysID = $this->_request->getParam('tpsysID');
        $objPackage = new Travel_Model_TblPackage();
        $getapihotel = $objPackage->GetAllAPIHotel($tpintsysId);
        /*

          for($i=0;$i<count($getapihotel);$i++){
          $sourcesysID = $getapihotel[$i]['SourceSysId'];

          ########### GRN API SEARCH ####################
          $accomsysID = $getapihotel[$i]['AccoSysId'];
          $totalprice = $getapihotel[$i]['TotalCost'];
          $tpintsysID = $getapihotel[$i]['TPIntSysId'];
          $VersionId =  $getapihotel[$i]['VersionId'];
          $isselected = $getapihotel[$i]['IsSelectedOnPkg'];
          $checkintime = $getapihotel[$i]['FromDate'];
          $checkintimestr = $checkintime->format('Y-m-d');
          $checkouttime = $getapihotel[$i]['ToDate'];
          $checkoutimestr = $checkouttime->format('Y-m-d');
          if($sourcesysID == '4'){
          $roominfojson =  $getapihotel[$i]['RoomMemInfoJson'];
          $roominfojsondecode = json_decode($roominfojson,1);
          $roominfoarr = array_values($roominfojsondecode);
          $k = 0;
          $arrMemberDetails = array();
          $arrMemberDetails[$k]['adults'] = $roominfoarr[$k]['adult'];
          //$arrMemberDetails[$i]['NoOfChild'] = $memberDetails[$i]['ChildPax'];
          if($roominfoarr[$k]['child']['childcount'] == 1){
          $arrChildAge = $roominfoarr[$k]['child']['childage'];
          $arrMemberDetails[$k]['children_ages'][] = $arrChildAge;
          }
          if($roominfoarr[$k]['child']['childcount'] > 1){
          $arrChildAge = explode(",",$roominfoarr[$k]['child']['childage']);
          $arrMemberDetails[$k]['children_ages'][] = $arrChildAge;
          }

          $k = $k+1;

          $grnsearch = $objPackage->GetICAccom($accomsysID);
          #################### GRN API CHECK #################
          $datah = array(
          "hotel_codes" => [trim($grnsearch[0]['ShortName'])],
          "checkin" => $checkintimestr,
          "checkout" => $checkoutimestr,
          "client_nationality" => 'IN',
          "response" => "full",
          "currency" => "INR",
          "rates" => "comprehensive", //comprehensive //comprehensive
          "hotel_category" => [$getapihotel[$i]['StarRating']],
          "rooms" => $arrMemberDetails
          );

          $data_stringh = json_encode($datah);

          //Write Request Logs starts...
          //                $strFilePath = "apihotels/search/".time()."_search_request1.json";
          //                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath,$data_stringh);
          //Write Request Logs starts...
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, GRN_HOTEL_API_SEARCH_URL);
          curl_setopt($ch, CURLOPT_ENCODING , "gzip");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Accept: application/json',
          'Content-Type: application/json',
          'api-key: '.GRN_HOTEL_API_KEY

          ));
          $outputH = curl_exec($ch);
          $response = json_decode($outputH, true);

          $hotelinfo = $response['hotels'][0]['rates'][0]['rooms'][0]['description'];
          $room_type = $response['hotels'][0]['rates'][0]['rooms'][0]['room_type'];
          $netprice = round($response['hotels'][0]['rates'][0]['price']);
          @$currentDate = date('Y-m-d');
          if($accomsysID == $room_type && $totalprice == $netprice){
          ############# No Action Required #################
          }
          else{

          ############ Update Data and Cost Sheet ##########
          $updatedData = array(
          'TotalCost' => $netprice,
          'UpdateDate' => @$currentDate,
          'IsActive' => '0'
          );
          $where1 = array('TPIntSysId = ? ' => @$getapihotel[$i]['TPIntSysId'],
          'VersionId = ? ' => @$getapihotel[$i]['VersionId']);
          $updateprice = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Accom', $updatedData, $where1);
          }
          if($isselected == '1'){
          $objPackage->UpdateHotelSelection($accomsysID,$tpintsysID,$VersionId,$tpsysID,'API');
          }
          }

          if($sourcesysID == '3'){
          $tokenId = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();
          $m = 0;
          $roominfojson =  $getapihotel[$i]['RoomMemInfoJson'];
          $roominfojsondecode = json_decode($roominfojson,1);
          $roominfoarr = array_values($roominfojsondecode);
          $arrMemberDetails = array();

          if(count($roominfoarr) > 0){
          for($m=0; $m<count($roominfoarr); $m++){
          $arrMemberDetails[$m]['NoOfAdults'] = $roominfoarr[$m]['adult'];
          $arrMemberDetails[$m]['NoOfChild'] = $roominfoarr[$m]['child']['childcount'];
          if($roominfoarr[$m]['child']['childcount'] == 1){
          $arrChildAge = $roominfoarr[$m]['child']['childage'];
          $arrMemberDetails[$m]['ChildAge'] = 1;
          }
          if($roominfoarr[$m]['child']['childcount'] > 1){
          $arrChildAge = explode(",",$roominfoarr[$m]['child']['childage']);
          $arrMemberDetails[$i]['ChildAge'] = $arrChildAge;
          }
          else{
          $arrMemberDetails[$i]['ChildAge'] = NULL;
          }

          }
          }



          $grnsearch = $objPackage->GetICAccom($accomsysID);
          $checkintimestrto = explode('-',$checkintimestr);
          $checkinstring = $checkintimestrto[2].'/'.$checkintimestrto[1].'/'.$checkintimestrto[0];

          $datah = array(
          "CheckInDate" => $checkinstring,
          "NoOfNights" => 2,
          "CountryCode" => 'IN',
          "CityId" => $grnsearch[0]['APICityId'],
          "ResultCount" => null,
          "PreferredCurrency" => "INR",
          "GuestNationality" => 'IN',
          "NoOfRooms" => $getapihotel[$i]['TotalPax'],
          "RoomGuests" => $arrMemberDetails,
          'PreferredHotel' => '',
          'MaxRating' => $getapihotel[$i]['StarRating'],
          'MinRating' => '0',
          'ReviewScore' => null,
          'IsNearBySearchAllowed' => 'false',
          'EndUserIp' => $_SERVER['REMOTE_ADDR'],
          'PreferredHotel' =>  $getapihotel[$i]['Title'],
          'TokenId' => $tokenId
          );
          $data_stringh = json_encode($datah);

          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, TBO_HOTEL_API_SEARCH_URL);
          curl_setopt($ch, CURLOPT_ENCODING , "gzip");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/json',
          'Content-Length: ' . strlen($data_stringh)
          ));
          $outputH = curl_exec($ch);
          $responseTBO = json_decode($outputH, true);
          if(isset($responseTBO['HotelSearchResult']['HotelResults'])){
          $hotelresults = $responseTBO['HotelSearchResult']['HotelResults'];
          $traceID = $responseTBO['HotelSearchResult']['TraceId'];

          for($j=0;$j<count($hotelresults);$j++){
          if($hotelresults[$j]['HotelName'] == trim($getapihotel[$i]['Title']) && $hotelresults[$j]['HotelCode'] == trim($grnsearch[0]['ShortName'])){
          $hotelresultindex = $hotelresults[$j]['ResultIndex'];
          }
          }

          $roomdata = array(
          "EndUserIp" => $_SERVER['REMOTE_ADDR'],
          "TokenId" => $tokenId,
          "TraceId" => $traceID,
          "ResultIndex" => $hotelresultindex,
          "HotelCode" => trim($grnsearch[0]['ShortName'])
          );
          $roomencodedata = json_encode($roomdata);
          $roomsearchurl = 'http://api.tektravels.com/BookingEngineService_Hotel/hotelservice.svc/rest/GetHotelRoom/';
          $roomencodedata = json_encode($roomdata);
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $roomsearchurl);
          curl_setopt($ch, CURLOPT_ENCODING , "gzip");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $roomencodedata);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/json',
          'Content-Length: ' . strlen($roomencodedata)
          ));
          $outputroomH = curl_exec($ch);
          $responsehotelresult = json_decode($outputroomH, true);
          @$currentDate = date('Y-m-d');
          $roominfodata = $responsehotelresult['GetHotelRoomResult']['HotelRoomsDetails'];

          for($a=0;$a<count($roominfodata);$a++){
          $apiprice = round($roominfodata[$a]['Price']['PublishedPrice']);

          if($roominfodata[$a]['RoomTypeCode'] == trim($getapihotel[$i]['RoomNumber']) && $totalprice == $apiprice){
          ############## Nothing to update #################
          }
          else{
          $updatedData = array(
          'TotalCost' => $apiprice,
          'UpdateDate' => @$currentDate,
          'IsActive' => '0'
          );
          $where1 = array('TPIntSysId = ? ' => @$getapihotel[$i]['TPIntSysId'],
          'VersionId = ? ' => @$getapihotel[$i]['VersionId']);
          $updateprice = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Accom', $updatedData, $where1);

          if($isselected == '1'){
          $objPackage->UpdateHotelSelection($accomsysID,$tpintsysID,$VersionId,$tpsysID,'API');
          }

          }
          }
          }
          }
          }

         */
    }

    public function displayproposalAction() {
        $this->_helper->layout->disableLayout();
        $getData = $this->getRequest()->getPost();
        $tpID = $getData['tpsysID'];
        $objPackage = new Travel_Model_TblPackage();
        //echo $this->getRequest()->getParam('id');		
        if ($tpID) {
            $flexiPackageList = $objPackage->getCustPackageList($tpID);
            $this->view->flexiPackageList = $flexiPackageList;
            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;
            //Get Package Activity
            $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
            $this->view->flexiPackageActivityList = $flexiPackageActivityList;
            //Get Package Sightseen
            $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
            $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            //Get Package Hotels
            $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID);
            $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;
            //Get Package Flight
            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            $this->view->flexiPackageFlight = $flexiPackageFlight;
            ########## Code Added By Shobhit ##################
            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->view->tpID = $tpID;
            $getcustomerDetail = $this->_crmcusttravelplan->GetTravelPlanDetailsofCustomer($tpID);
            $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            //  $this-view->getCustomerDetails = $getcustomerDetail;
            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $getversiondetails;
        }
    }

    public function changeHotelAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $AccoSysId = $this->getRequest()->getPost('AccoSysId');
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $VersionId = $this->getRequest()->getPost('VersionId');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $adultpax = $this->getRequest()->getPost('adultpax');
        $childpax = $this->getRequest()->getPost('childpax');
        $totaltraveler = $this->getRequest()->getPost('totaltraveler');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $tproomnumber = $this->getRequest()->getPost('tproomnumber');
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->UpdateHotelSelection($AccoSysId, $TPIntSysId, $VersionId, $tpsysID, 'PKG', $roominfojson, $adultpax, $childpax, $totaltraveler, $tproomnumber);
    }

    /*
      public function getmasterdataAction(){
      $this->_helper->layout->disableLayout();
      $front = Zend_Controller_Front::getInstance();
      $front->setParam('noViewRenderer', true);
      $objPackage = new Travel_Model_TblPackage();
      $AccoSysId = $this->getRequest()->getPost('AccoSysId');
      $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
      $roomnumber = $this->getRequest()->getPost('roomnumber');
      if(empty($roomnumber)){
      $roomnumber = '';
      }

      $resultdata = $objPackage->CountMasterId($AccoSysId,$TPIntSysId,$roomnumber);
      echo count($resultdata);
      }
     */

    public function updatePriceAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $finalcost = $this->getRequest()->getPost('finalcost');
        //$roominfojson = $this->getRequest()->getPost('roominfojson');
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->ChangeHotelPrice($tpintsysID, $tpsysID, $finalcost);
    }

    public function savepkgproposalbyoAction() {
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $this->_crmcusttravelplanItenaryAccom = new Travel_Model_CRM_CustomerTravelPlanAccom();
        $this->_crmcustomertravelItenary = new Travel_Model_CRM_CustomerTravelItenary();
        $this->_travelplanevents = new Travel_Model_Package_TravelPlanItenaryEvents();
        $this->_travelplanplaces = new Travel_Model_Package_TravelPlanItenaryPlaces();
        $this->_crmcustomertravelSightSeeing = new Travel_Model_CRM_CustomerTravelItenarySightSeeing();
        $this->_crmcustomertravelMarketPlaces = new Travel_Model_CRM_CustomerTravelItenaryMarketRate();
        $this->_crmcustomertravelItenaryEvents = new Travel_Model_CRM_CustomerTravelItenaryEvents();
        $this->_crmcustomertravelItenaryPlaces = new Travel_Model_CRM_CustomerTravelItenaryPlaces();
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        $sentprice = $getData['totalprice'];
        //echo $url = $this->userAgent()->getServerValue('request_uri');

        $aboutpackage = $getData['aboutpackage'];
        $tripaddress = $getData['tripaddress'];
        $pricerange = $getData['pricerange'];
        $pricetype = $getData['pricetypeval'];
        $createDate = date('Y-m-d');
        $travelplanID = $getData['tpID'];

        $booknowurl = $_SERVER['SERVER_NAME'] . '/publicpackage/customerview/id/' . base64_encode($travelplanID);
        // $booknowurl = 'http://st.tb.tripsbank.com/publicpackage/customerview/id/'.base64_encode($travelplanID);

        $totprice = $getData['totalprice'];
        $sentemail = trim($getData['customeremail']);
        $FirstName = $getData['customername'];
        $totalprice = $getData['totalprice'];
        $priceperadult = $getData['costpp'];
        // $travelplandata = $this->_crmcusttravelplan->GetTravelPlan($travelplanID);
        $gettplandataforcustomer = $this->_crmcusttravelplan->GetTravelPlanByCustomer($travelplanID);
        $pkgtitle = $gettplandataforcustomer[0]['Title'];
        #### For Fetching the Lead Detail which is sent to customer ####
        $objPackage = new Travel_Model_TblPackage();
        // $sessionLogin_user           = new Zend_Session_Namespace('sessionLogin_user');
        $agencySysId = $getData['agencysysID'];
        $agencyUser = $objPackage->getAgencyUser($agencySysId);
        $agentname = $agencyUser['PrimaryContactName'];
        $agentnumber = $agencyUser['ContactInfo'];

        $path = SITE_FULL_URL . 'public/assets/images';
        $Logo = $agencyUser['Logo'];
        $agencyDisplayName = trim($agencyUser['DisplayName']);
        $sendersEmailId = trim($agencyUser['PrimaryEmail']);

        $pathAgency = SITE_FULL_URL . 'public/upload/media/agency/' . $agencySysId;
        if (isset($Logo) && $Logo != '') {
            $AgencyLogo = $pathAgency . '/' . $Logo;
        } else {
            $AgencyLogo = $path . '/logo.png';
        }
        //echo $AgencyLogo;

        $aboutpackage = $aboutpackage ? $aboutpackage : '';
        $bodyText = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
         <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <style type="text/css">
            body {
                margin-left: 0px;
                margin-top: 0px;
                margin-right: 0px;
                margin-bottom: 0px;
            }
        </style>
        </head>

        <body>
        <table width="650" border="0" cellspacing="0" cellpadding="0" align="center" bgcolor="#fff" style="font-family:Tahoma, Geneva, sans-serif; color:#434343;">
            <tr>
                <td style="padding:25px 25px 0 25px; background:#ff9900"><table width="100%" border="0" align="left" cellpadding="0" cellspacing="0">

                        <tr>
                            <td align="center" style="padding-bottom:10px;"><a href="http://www.tripsbank.com/"><img src="' . $AgencyLogo . '" alt="Tripsbank" title="Tripsbank" border="0" /></a></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td style="background: #fff;	border-radius:5px 5px  0 0; padding:20px 25px  0 25px; font-size:14px; line-height:24px; border-left:1px solid #CCC; border-right:1px solid #CCC; border-top:1px solid #CCC; font-family:Tahoma, Geneva, sans-serif;">Dear <strong>' . $FirstName . ',</strong><br />
                                This mail contains the itinerary for your trip to <strong>' . $tripaddress . '</strong>. We sincerely hope that
                                every detail has been tailored to your requirements and preferences.<br />
                                <br />

                                <strong>Total Price - ' . $sentprice . '.</strong> The exact price of the package will be
                                communicated only once you finalise the itinerary.</td>
                        </tr>
                    </table></td>
            </tr>
            <tr>
                <td style="padding:0 25px 10px 25px; background:#eee;"><table width="100%" border="0" cellpadding="0" cellspacing="0" align="left">

                        <tr>
                            <td colspan="3" style="	background: #fff;	border-radius:0 0 5px 5px;	padding:20px 25px ; font-size:14px; line-height:24px; border-left:1px solid #d9d9d9; border-right:1px solid #d9d9d9; border-bottom:1px solid #d9d9d9; font-family:Tahoma, Geneva, sans-serif;">
                               ' . $aboutpackage . '<br /><br />
                                
                                Feel free reach out to us in case you want any further iterations.<br />
                                <br />

                                Your personal trip manager,<br />
                                ' . $agencyUser['PrimaryContactName'] . '<br />
                                ' . $agencyUser['ContactInfo'] . '</td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="3" style="	background:#fff; border-radius:5px;	padding:20px 25px ; font-size:22px; line-height:24px; text-align:center; border:1px solid #d9d9d9"><a href="' . $booknowurl . '" style="text-decoration:none; color:#ff9900; font-weight:500; font-family:Tahoma, Geneva, sans-serif;">Click here to view your trip itinerary</a></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="3" align="center"><img src="' . $path . '/heart.png" border="0" alt="" title=""/></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="3" style="font-family:Tahoma, Geneva, sans-serif; padding:0 25px ; font-size:14px; line-height:30px; text-align:center; color:#999;"><span style="font-size:18px; font-weight:700; color:#5b5b58;">Help us spread the word.</span><br />
                                If you like us, please help us grow by telling your friends<br />
                                and family about us. We\'ll truly appreciate the gesture.</td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                       
                        <tr>
                            <td colspan="3" style="padding:10px 25px; font-size:9px; line-height:30px; font-weight:500; text-align:center; color:#484343; font-family:Verdana, Geneva, sans-serif">2016 &copy; Global Travel Exchange <span style="font-size:12px; ">|</span> Technology By Global Travel Exchange </td>
                        </tr>
                    </table></td>
            </tr>
        </table>
    </body>
</html>';

        $emailId = trim($sentemail);
        $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => 'Proposal Details', 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
        try {
            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $arrEmailStatistics = array(
                "TPSysId" => $gettplandataforcustomer[0]['TPSysId'],
                "TypeSysId" => 1, // 1 For Email 2 For SMS
                "AgencySysId" => $gettplandataforcustomer[0]['AgencySysId'],
                "AgentSysId" => $gettplandataforcustomer[0]['AgentSysId'],
                "Title" => $bodyText,
                "Source" => $arrEmailStatisticsType[2], // 3 For Resend proposal
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
            );
            $this->mailSentByElastice($emailData, $arrEmailStatistics, 1, $gettplandataforcustomer[0]['CustomerSysId']);
            echo 'Email has sent to customer';
        } catch (Exception $err) {
            print_r($err, true);
        }
    }

    public function preBookingViewAction() {

        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $params = $this->getRequest()->getParams();
        $createDate = date('Y-m-d H:i:s');
        $tpsysID = (isset($params['id'])) ? base64_decode($params['id']) : '';

        $code = (isset($params['code'])) ? trim($params['code']) : '';
        $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpsysID), 1);

        if (!empty($tpsysID) && $code == $secureCode) {

            $objPackage = new Travel_Model_TblPackage();
            $packInfo = $objPackage->getCustPackageList($tpsysID);
            if (isset($packInfo['StatusType']) && $packInfo['StatusType'] == 4) {
                $customHelper = Zend_Controller_Action_HelperBroker::getStaticHelper("Custom");
                $statusArray = $customHelper->changeQueryStatusByProposal();
                $querystatus = $statusArray[5];
                $whereQuery = "TPSysId = " . $tpsysID;
                $updatetravelplanproposal = array(
                    'StatusType' => 5,
                    'UpdateDate' => $createDate
                );
                $update = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanproposal, $whereQuery);
                if (isset($querystatus) && !empty($querystatus)) {
                    $whereQuery = "TPSysId = " . $packInfo['MasterTPSysId'];
                    $updatetravelplanquery = array(
                        'StatusType' => $querystatus,
                        'UpdateDate' => $createDate,
                        'ExpectedClosureDate' => $packInfo['StartDate']->format('Y-m-d'),
                        'ExpectedValue' => $packInfo['NetPrice'],
                    );
                    $updatetravelPlanQuery = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplanquery, $whereQuery);

//                    $ClosureData = $this->_crmcusttravelplan->expectedClosureData($packInfo['MasterTPSysId'], $expectedClosureData);
                }
            }

            $paybalance = $this->baseUrl . '/package-booking/package-booking-view/pid/' . base64_encode($tpsysID) . '/ptype/f/code/' . $secureCode;
            $this->_redirect($paybalance);
        } else {
            die('Do not Change code.');
        }
    }

    public function updatePackageStatusAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->getRequest()->getPost('packid');
        $postData = $this->getRequest()->getPost();
        $IsSendMail = isset($postData['IsSendMail']) ? $postData['IsSendMail'] : 1;
        $IsSendSms = isset($postData['IsSendSms']) ? $postData['IsSendSms'] : 1;
        $objPackage = new Travel_Model_TblPackage();
        $packInfo = $objPackage->getCustPackageList($tpsysID);
        $AgencySysId = isset($packInfo['AgencySysId']) ? $packInfo['AgencySysId'] : null;
        if ($AgencySysId) {
            $TblAgencyStaff = new Travel_Model_TblAgencyStaff();
            $checkMailArray = $TblAgencyStaff->checkAgencyWiseMail($AgencySysId, 4);
            $IsSendMail = isset($checkMailArray[0]['IsActive'])?$checkMailArray[0]['IsActive']:0;
        }
        $createDate = date('Y-m-d H:i:s');
        $ARR_SALUTION = unserialize(ARR_SALUTION);
        $customHelper = Zend_Controller_Action_HelperBroker::getStaticHelper("Custom");
        $statusArray = $customHelper->changeQueryStatusByProposal();
        $querystatus = $statusArray[5];
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $whereProposal = "TPSysId = " . $tpsysID;
        $updatetravelplanproposal = array(
            'StatusType' => 5,
            'UpdateDate' => $createDate
        );
        $update = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanproposal, $whereProposal);
        if (isset($querystatus) && !empty($querystatus)) {
            $whereQuery = "TPSysId = " . $packInfo['MasterTPSysId'];
            $updatetravelplanquery = array(
                'StatusType' => $querystatus,
                'UpdateDate' => $createDate,
                'ExpectedClosureDate' => $packInfo['StartDate']->format('Y-m-d'),
                'ExpectedValue' => $packInfo['NetPrice'],
            );
            $updatetravelPlanQuery = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplanquery, $whereQuery);

            if (empty($packInfo['RefTPSysId'])) {
                $whereProposalOthers = "TPSysId != " . $tpsysID . " AND MasterTPSysId = " . $packInfo['MasterTPSysId'];
                $updatetravelplanproposalOthers = array(
                    'StatusType' => 160,
                    'UpdateDate' => $createDate
                );
                $update = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanproposalOthers, $whereProposalOthers);
            }

            //$ClosureData = $this->_crmcusttravelplan->expectedClosureData($packInfo['MasterTPSysId'], $expectedClosureData);

            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails(trim($packInfo['AgentSysId']));
            //            echo "<pre>";print_r($getAgentDetail);die;
            $Salutation = (isset($getAgentDetail['Salutation']) && !empty(trim($getAgentDetail['Salutation']))) ? $ARR_SALUTION[trim($getAgentDetail['Salutation'])] : '';
            $FirstName = trim($getAgentDetail['FirstName']);
            $LastName = trim($getAgentDetail['LastName']);
            $EmailId = $getAgentDetail['EmailId'];
            $agencysysID = $getAgentDetail['AgencySysId'];
            $AgencyContact = $getAgentDetail['ContactNo1'];
            $AgencyCountrycode = $getAgentDetail['countrycode'];
            $Signature = $getAgentDetail['Signature'];
            //$EmailId = 'mangal@catpl.co.in';
            // $modelAgency = new Travel_Model_TblAgency();
            //$masterAgencyData = $modelAgency->getUserDataByAgency($agencysysID);
            $GetTravelPlanByCustomer = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);

            if (isset($GetTravelPlanByCustomer[0]['RefTPSysId']) && (int) $GetTravelPlanByCustomer[0]['RefTPSysId'] > 0) {
                $returnMM = $this->_crmcusttravelplan->CopyProposalPaymentData($GetTravelPlanByCustomer[0]);
            }

            $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpsysID), 1);
            $link = $this->baseUrl . "/publicpackage/view-customer-final-package/id/" . base64_encode($tpsysID) . '/code/' . $secureCode;

            $custsalutation = (isset($GetTravelPlanByCustomer[0]['Salutation']) && !empty(trim($GetTravelPlanByCustomer[0]['Salutation']))) ? $ARR_SALUTION[trim($GetTravelPlanByCustomer[0]['Salutation'])] : '';
            $customerFullName = ucfirst($custsalutation . ' ' . trim($GetTravelPlanByCustomer[0]['FirstName']) . ' ' . trim($GetTravelPlanByCustomer[0]['LastName']));
            $customerFirstName = trim($GetTravelPlanByCustomer[0]['FirstName']);
            $DestinationPlaces = $GetTravelPlanByCustomer[0]['DestinationPlaces'];
            //   echo "<pre>";print_r($GetTravelPlanByCustomer);die;  
            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpsysID);
            $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList, $packInfo['NoofNight']);
            $CurrencyTypeName = 'INR';
            $currencyarr = $objPackage->getCurrencyList();
            foreach ($currencyarr as $cKey => $cValue) {
                if ($cValue['CurrencyType'] === $GetTravelPlanByCustomer[0]['CurrencyType']) {
                    $CurrencyTypeName = $cValue['Symbol'];
                }
            }


            $RoomInfoJson = json_decode($GetTravelPlanByCustomer[0]['RoomInfoJson'], 1);
            $noofPaxTotal = 0;
            foreach ($RoomInfoJson as $roomKey => $roomValue) {
                $noofPax = $roomValue['Adult'] + $roomValue['Child'] + $roomValue['Infant'];
                $noofPaxTotal = $noofPaxTotal + $noofPax;
            }
            $tripText = 'Trip';
            $OrderForText = 'Package';
            if ($packInfo['PlanType'] == 6) {
                $tripText = 'Visa';
                $OrderForText = 'Visa';
            }
            $agentparams = array(
                'agentName' => ucfirst($Salutation . ' ' . $FirstName . ' ' . $LastName),
                'emailId' => $EmailId,
                'ProposalId' => $packInfo['TPSysId'],
                'queryId' => $packInfo['MasterTPSysId'],
                'customerName' => trim($customerFullName),
                'customerEmailId' => $GetTravelPlanByCustomer[0]['EmailId'],
                'customerContacts' => $GetTravelPlanByCustomer[0]['Contacts'],
                'countrycode' => $GetTravelPlanByCustomer[0]['countrycode'],
                'TravelDate' => $GetTravelPlanByCustomer[0]['StartDate']->format('d-M-y'),
                'NetPrice' => $this->moneyFormatIndia((float) $GetTravelPlanByCustomer[0]['NetPrice']),
                'MinPax' => $noofPaxTotal,
                'NoofDays' => $totalDaysNightsArr['totaldays'],
                'PlanType' => $GetTravelPlanByCustomer[0]['PlanType'],
                'packageTitle' => $GetTravelPlanByCustomer[0]['Title'],
                'link' => $link,
                'DestinationPlaces' => $DestinationPlaces,
                'AgencyContact' => $AgencyContact,
                'AgencyCountrycode' => $AgencyCountrycode,
                'CurrencyTypeName' => $CurrencyTypeName,
                'Signature' => $Signature,
                'OrderForText' => $OrderForText,
                'tripText' => $tripText,
                'IsDisplayHelloGTX' => $getAgentDetail['IsDisplayHelloGTX']
            );

            $subjectAgent = ' Confirmation by ' . trim($customerFullName) . ' for ' . trim($DestinationPlaces) . ' ' . $tripText;
            $agenthtml = new Zend_View();
            $agenthtml->setScriptPath(APPLICATION_PATH . '/views/emails/');
            $agenthtml->assign($agentparams);
            $agentbodyText = $agenthtml->render('confirmationProposal.phtml');
            $agentemailData = array('fromEmail' => $EmailId, 'fromName' => ucfirst($FirstName . ' ' . $LastName), 'subject' => $subjectAgent, 'to' => array($EmailId), 'bodyHtml' => $agentbodyText, 'bodyText' => '');

            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $arrEmailStatistics = array(
                "TPSysId" => 0,
                "TypeSysId" => 1, // 1 For Email 2 For SMS
                "AgencySysId" => $getAgentDetail['AgencySysId'],
                "AgentSysId" => $getAgentDetail['UserSysId'],
                "Title" => '',
                "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
            );

            if ($IsSendMail == 1) {
                $checkStatus1 = $this->mailSentByElastice($agentemailData, $arrEmailStatistics);
            }

            $countrycode = (strpos($GetTravelPlanByCustomer[0]['countrycode'], '+') !== false) ? $GetTravelPlanByCustomer[0]['countrycode'] : "+" . $GetTravelPlanByCustomer[0]['countrycode'];
            $CustomerMobileNumber = trim($countrycode) . '' . trim($GetTravelPlanByCustomer[0]['Contacts']);
            $amount = trim($CurrencyTypeName) . ' ' . trim($GetTravelPlanByCustomer[0]['NetPrice']);
            $destinationLocation = trim($DestinationPlaces);
            $postData = array(
                "UserSysId" => trim($packInfo['AgentSysId']),
                // "IsSchedule" => False,
                "schedule_time" => "",
                "title" => "Verbal Confirmaiton Alert",
                "body" => "$customerFirstName has just confirmed verbally for $destinationLocation offer for $amount.",
                //"IsButton" => True,
                "URL" => "/publicpackage/view-customer-final-package/id/" . base64_encode($tpsysID) . '/code/' . $secureCode,
                "IsCall" => true,
                "mobileNo" => trim($CustomerMobileNumber)
            );
            if (isset($getAgentDetail['SecurityKey'])) {
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://globaltravelexchange.com/gtxwebservices/agency/create-fire-base-message',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $postData,
                    CURLOPT_HTTPHEADER => array(
                        'securitykey:' . trim($getAgentDetail['SecurityKey']),
                    //'Content-Type: application/json'
                    ),
                ));
                $response = curl_exec($curl);
                curl_close($curl);
                //echo "<pre>";print_r($response);exit;
            }


            $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpsysID), 1);
            $paybalance = $this->baseUrl . '/package-booking/package-booking-view/pid/' . base64_encode($tpsysID) . '/cid/' . base64_encode($GetTravelPlanByCustomer[0]['CustomerSysId']) . '/code/' . $secureCode;
            if ($getAgentDetail['IsB2CSite'] == 1) {
                $paybalance = $getAgentDetail['Url'] . "detail/index/view/id/" . base64_encode($paybalance);
            } else if (($getAgentDetail['IsB2CSite'] == 2) && ($getAgentDetail['IsSiteType'] == 1)) {
                $paybalance = $getAgentDetail['Url'] . "hellogtx/index.html?id=" . base64_encode($paybalance);
            } else if (($getAgentDetail['IsB2CSite'] == 2) && ($getAgentDetail['IsSiteType'] == 0)) {
                $paybalance = $getAgentDetail['Url'] . "hellogtx/gtx.php?id=" . base64_encode($paybalance);
            }
            $custparams = array(
                'agentName' => ucfirst($FirstName . ' ' . $LastName),
                'emailId' => $EmailId,
                'ProposalId' => $packInfo['TPSysId'],
                'queryId' => $packInfo['MasterTPSysId'],
                'customerName' => $customerFullName,
                'customerEmailId' => $GetTravelPlanByCustomer[0]['EmailId'],
                'customerContacts' => $GetTravelPlanByCustomer[0]['Contacts'],
                'countrycode' => $GetTravelPlanByCustomer[0]['countrycode'],
                'TravelDate' => $GetTravelPlanByCustomer[0]['StartDate']->format('d-M-y'),
                'NetPrice' => $this->moneyFormatIndia((float) $GetTravelPlanByCustomer[0]['NetPrice']),
                'MinPax' => $noofPaxTotal,
                'NoofDays' => $totalDaysNightsArr['totaldays'],
                'PlanType' => $GetTravelPlanByCustomer[0]['PlanType'],
                'packageTitle' => $GetTravelPlanByCustomer[0]['Title'],
                'link' => $link,
                'DestinationPlaces' => $DestinationPlaces,
                'AgencyContact' => $AgencyContact,
                'AgencyCountrycode' => $AgencyCountrycode,
                'CurrencyTypeName' => $CurrencyTypeName,
                'Signature' => $Signature,
                'OrderForText' => '',
                'tripText' => $tripText,
                'paybalance' => '(<a href="' . $paybalance . '" style="text-decoration: none;">Click here to PAY</a>)',
            );
            //            echo "<pre>";print_r($_SESSION);die;
            $subjectCust = 'Confirmation for ' . trim($DestinationPlaces) . ' ' . $tripText;
            $custhtml = new Zend_View();
            $custhtml->setScriptPath(APPLICATION_PATH . '/views/emails/');
            $custhtml->assign($custparams);
            $custbodyText = $custhtml->render('confirmationProposalCustomer.phtml');
            $custemailData = array('fromEmail' => $EmailId, 'fromName' => $FirstName . ' ' . $LastName, 'subject' => $subjectCust, 'to' => array($GetTravelPlanByCustomer[0]['EmailId']), 'bodyHtml' => $custbodyText, 'bodyText' => '');

            if ($IsSendMail == 1) {
                $checkStatus2 = $this->mailSentByElastice($custemailData, $arrEmailStatistics);
            }
            echo 1;
            exit;
        }
    }

    public function updatePackageInterestedstatusAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->getRequest()->getPost('packid');
        $objPackage = new Travel_Model_TblPackage();
        $packInfo = $objPackage->getCustPackageList($tpsysID);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $createDate = date('Y-m-d H:i:s');
        $customHelper = Zend_Controller_Action_HelperBroker::getStaticHelper("Custom");
        $statusArray = $customHelper->changeQueryStatusByProposal();
        $querystatus = $statusArray[5];
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $whereProposal = "TPSysId = " . $tpsysID;
        $updatetravelplanproposal = array(
            'StatusType' => 81,
            'UpdateDate' => $createDate
        );
        $update = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanproposal, $whereProposal);
        if (isset($querystatus) && !empty($querystatus)) {
            $whereQuery = "TPSysId = " . $packInfo['MasterTPSysId'];
            $updatetravelplanquery = array(
                'StatusType' => 86, //old 58
                'UpdateDate' => $createDate
            );
            $updatetravelPlanQuery = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplanquery, $whereQuery);
            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails(trim($packInfo['AgentSysId']));
            //            echo "<pre>";print_r($getAgentDetail);die;
            $FirstName = $getAgentDetail['FirstName'];
            $LastName = $getAgentDetail['LastName'];
            $EmailId = $getAgentDetail['EmailId'];
            $agencysysID = $getAgentDetail['AgencySysId'];
            $AgencyContact = $getAgentDetail['ContactNo1'];
            $Signature = $getAgentDetail['Signature'];
            //echo "<pre>";print_r($_SESSION);die;
            //$modelAgency = new Travel_Model_TblAgency();
            //$masterAgencyData = $modelAgency->getUserDataByAgency($agencysysID);
            //$EmailId = 'mangal@catpl.co.in';
            $GetTravelPlanByCustomer = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);

            $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($tpsysID), 1);
            $link = $this->baseUrl . "/publicpackage/view-customer-final-package/id/" . base64_encode($tpsysID) . '/code/' . $secureCode;
            $agentparams = array(
                'agentName' => ucfirst($FirstName . ' ' . $LastName),
                'emailId' => $EmailId,
                'ProposalId' => $tpsysID,
                'customerName' => $GetTravelPlanByCustomer[0]['FirstName'] . ' ' . $GetTravelPlanByCustomer[0]['LastName'],
                'customerEmailId' => $GetTravelPlanByCustomer[0]['EmailId'],
                'customerContacts' => $GetTravelPlanByCustomer[0]['Contacts'],
                'TravelDate' => $GetTravelPlanByCustomer[0]['StartDate']->format('d-M-y'),
                'NetPrice' => $GetTravelPlanByCustomer[0]['PriceRange'],
                'link' => $link,
                'DestinationPlaces' => $GetTravelPlanByCustomer[0]['DestinationPlaces'],
                'packageTitle' => $GetTravelPlanByCustomer[0]['Title'],
                'Signature' => $Signature,
            );
            $subjectAgent = 'Interest shown by the customer';
            $agenthtml = new Zend_View();
            $agenthtml->setScriptPath(APPLICATION_PATH . '/views/emails/');
            $agenthtml->assign($agentparams);
            $agentbodyText = $agenthtml->render('interestedProposal.phtml');
            $agentemailData = array('fromEmail' => $EmailId, 'fromName' => $FirstName . ' ' . $LastName, 'subject' => $subjectAgent, 'to' => array($EmailId), 'bodyHtml' => $agentbodyText, 'bodyText' => '');
            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $arrEmailStatistics = array(
                "TPSysId" => 0,
                "TypeSysId" => 1, // 1 For Email 2 For SMS
                "AgencySysId" => $getAgentDetail['AgencySysId'],
                "AgentSysId" => $getAgentDetail['UserSysId'],
                "Title" => '',
                "Source" => $arrEmailStatisticsType[2], // 6 For Misc
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
            );

            $checkStatus1 = $this->mailSentByElastice($agentemailData, $arrEmailStatistics);

            $custparams = array(
                'agentName' => ucfirst($FirstName . ' ' . $LastName),
                'emailId' => $EmailId,
                'ProposalId' => $tpsysID,
                'customerName' => $GetTravelPlanByCustomer[0]['FirstName'] . ' ' . $GetTravelPlanByCustomer[0]['LastName'],
                'customerEmailId' => $GetTravelPlanByCustomer[0]['EmailId'],
                'customerContacts' => $GetTravelPlanByCustomer[0]['Contacts'],
                'TravelDate' => $GetTravelPlanByCustomer[0]['StartDate']->format('d-M-y'),
                'NetPrice' => $GetTravelPlanByCustomer[0]['PriceRange'],
                'link' => $link,
                'DestinationPlaces' => $GetTravelPlanByCustomer[0]['DestinationPlaces'],
                'packageTitle' => $GetTravelPlanByCustomer[0]['Title'],
                'MinPax' => $GetTravelPlanByCustomer[0]['MinPax'],
                'NoofDays' => $GetTravelPlanByCustomer[0]['NoofNight'] + 1,
                'AgencyContact' => $AgencyContact,
                'Signature' => $Signature,
            );
            $DestinationPlaces = $GetTravelPlanByCustomer[0]['DestinationPlaces'];
            $subjectCust = 'Thanks for your interest in ' . trim($DestinationPlaces) . ' trip';
            $custhtml = new Zend_View();
            $custhtml->setScriptPath(APPLICATION_PATH . '/views/emails/');
            $custhtml->assign($custparams);
            $custbodyText = $custhtml->render('interestedProposalCustomer.phtml');
            $custemailData = array('fromEmail' => $EmailId, 'fromName' => $FirstName . ' ' . $LastName, 'subject' => $subjectCust, 'to' => array($GetTravelPlanByCustomer[0]['EmailId']), 'bodyHtml' => $custbodyText, 'bodyText' => '');

            $checkStatus2 = $this->mailSentByElastice($custemailData, $arrEmailStatistics);

            echo 1;
            exit;
        }
    }

    public function updateOptionalTransportAction() {

        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $FixTransSysId = $this->getRequest()->getPost('FixTransSysId');
        $adult = $this->getRequest()->getPost('adult');
        $child = $this->getRequest()->getPost('child');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->UpdateTransPort($tpsysID, $tpintsysID, $FixTransSysId, $adult, $child, $roominfojson);
    }

    public function removeOptionalTransportAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $FixTransSysId = $this->getRequest()->getPost('FixTransSysId');
        $adult = $this->getRequest()->getPost('adult');
        $child = $this->getRequest()->getPost('child');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->RemoveTransPort($tpsysID, $tpintsysID, $FixTransSysId, $adult, $child, $roominfojson);
    }

    public function getflightpriceAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $discount = $this->getRequest()->getPost('discount');
        $objPackage = new Travel_Model_TblPackage();
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $adultpax = $this->getRequest()->getPost('adultpax');
        $childpax = $this->getRequest()->getPost('childpax');
        $totaltraveler = $this->getRequest()->getPost('totaltraveler');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $finalcost = $this->getRequest()->getPost('TPIntSysId');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $versionID = $this->getRequest()->getPost('versionID');
        ######## UPDATE HOTEL DATA END ##########
        $itenaryid = $objPackage->GetItenaryIdOnly($tpsysID);
        ######## CALCULATE NEW COST FOR HOTEL ###########
        // $hoteldetails = array();
        $flightprice = 0;
        $totelhotelprice = 0;
        $totalhotelpriceperperson = 0;
        $totalactivitycost = 0;
        $totalactivitycostperperson = 0;
        $totalsscost = 0;
        $totalsscostpp = 0;
        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            if ($intsysId == $TPIntSysId) {
                $flightcost = $objPackage->GetFlightByVersion($versionID);
            } else {
                $flightcost = $objPackage->GetFlightByItenary($itenaryid[$i]['TPIntSysId']);
            }
            $flightprice = $flightprice + $flightcost['Cost'];
        }


        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $hoteldetails[] = $objPackage->GetHotelCost($intsysId, $roominfojson, $adultpax, $childpax, $totaltraveler);
            $totelhotelprice = round($totelhotelprice + $hoteldetails[$i]['totalprice']);
            $totalhotelpriceperperson = round($totalhotelpriceperperson + $hoteldetails[$i]['perperson']);
        }


        //echo 'Total Hotel Price'.$totelhotelprice;

        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $getactivitycost[] = $objPackage->GetActivityCostByIten($intsysId, $roominfojson, $adultpax, $childpax, $totaltraveler);
            $totalactivitycost = $totalactivitycost + $getactivitycost[$i]['totalcost'];
            $totalactivitycostperperson = $totalactivitycostperperson + $getactivitycost[$i]['costperperson'];
        }


        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $sscost[] = $objPackage->GetSightSeeingCostByIten(@$intsysId, $roominfojson, $adultpax, $childpax, $totaltraveler);
            $totalsscost = $totalsscost + $sscost[$i]['totalcost'];
            $totalsscostpp = $totalsscostpp + $sscost[$i]['costperperson'];
        }
        $totalinsurancecost = 0;
        ########### Calculate Cost For Travel Insurance #########  
        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $insurancecost = $objPackage->GetInsuranceCost($intsysId);
            $totalinsurancecost = $totalinsurancecost + $insurancecost['NetPaid'];
        }



        ########### Get Fixed Costing Data #####################

        $gettransportcost = $objPackage->GetFixedTrnsportCost($tpsysID);

        $totaltransportperpersoncost = 0;
        $totaltransportcost = 0;
        for ($i = 0; $i < count($gettransportcost); $i++) {

            $totaltransportcost = $totaltransportcost + $gettransportcost[$i]['TotalPrice'];
            $totaltransportperpersoncost = $totaltransportperpersoncost + $gettransportcost[$i]['CostPerson'];
        }
        $getmarketwiserate = $objPackage->GetMarketWiseRate($tpsysID);

        if ($getmarketwiserate[0]['MarkType'] == 'FixedAmount') {
            $totalcost = $totelhotelprice + $flightprice + $totalactivitycost + $totalsscost + $totaltransportcost + $totalinsurancecost + $getmarketwiserate[0]['MarkPercent'];
            $flightppprice = $flightprice / $totaltraveler;
            $totalcostperperson = $totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost + $getmarketwiserate[0]['MarkPercent'];
        }
        if ($getmarketwiserate[0]['MarkType'] == 'FixedPercnt') {
            $nettotalcostwithmarkuppercent = $totelhotelprice + $flightprice + $totalactivitycost + $totalsscost + $totaltransportcost + $totalinsurancecost + $getmarketwiserate[0]['MarkPercent'];
            $nettotalcostwithmarkup = ($nettotalcostwithmarkuppercent * $getmarketwiserate[0]['ExcludedPercent']) / 100;
            $totalcost = $nettotalcostwithmarkuppercent + $nettotalcostwithmarkup;
            //      $totalcost =  $nettotalcostwithmarkup+$totalcostwomp;       
            $flightppprice = $flightprice / $totaltraveler;
            $totalcostperpersonwomp = $totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost;
            $totalcostperpersonwmp = ($totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost) * ($getmarketwiserate[0]['MarkPercent']) / 100;
            $totalcostperperson = $totalcostperpersonwomp + $totalcostperpersonwmp;
        }
        echo $totalcost - $discount;
        ######## CALCULATE NEW COST FOR HOTEL END ###########
    }

    public function getmasterdataAction() {

        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $objPackage = new Travel_Model_TblPackage();
        $AccoSysId = $this->getRequest()->getPost('AccoSysId');
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $roomnumber = $this->getRequest()->getPost('roomnumber');
        $adultpax = $this->getRequest()->getPost('adultpax');
        $childpax = $this->getRequest()->getPost('childpax');
        $totaltraveler = $this->getRequest()->getPost('totaltraveler');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $finalcost = $this->getRequest()->getPost('TPIntSysId');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $versionID = $this->getRequest()->getPost('versionID');
        $discount = $this->getRequest()->getPost('discount');
        $getalltpintID = $objPackage->GetSelectedHotelById($TPIntSysId);
        $getmasterID = $objPackage->GetMasterTravelPlanID($TPIntSysId);
        $totalcopyhotel = count($getalltpintID) + count($getmasterID);

        ######## UPDATE HOTEL DATA END ##########
        $itenaryid = $objPackage->GetItenaryIdOnly($tpsysID);
        $itenararray = array();
        for ($i = 0; $i < count($itenaryid); $i++) {
            $itenararray[] = "'" . $itenaryid[$i]['TPIntSysId'] . "'";
        }

        $implodeitenary = implode(",", $itenararray);
        ######## CALCULATE NEW COST FOR HOTEL ###########
        // $hoteldetails = array();
        $flightprice = 0;
        $totelhotelprice = 0;
        $totalhotelpriceperperson = 0;
        $totalactivitycost = 0;
        $totalactivitycostperperson = 0;
        $totalsscost = 0;
        $totalsscostpp = 0;
        for ($i = 0; $i < count($itenaryid); $i++) {
            $flightcost = $objPackage->GetFlightByItenary($itenaryid[$i]['TPIntSysId']);
            $flightprice = $flightprice + $flightcost['Cost'];
        }

        ################# Hotel Calculation ##############
        $masterarr = array();
        $getonlymasterID = $objPackage->GetOnlyMasterId($implodeitenary);
        for ($k = 0; $k < count($getonlymasterID); $k++) {
            if (!in_array($getonlymasterID[$k]['MasterIntSysId'], $masterarr)) {
                $masterarr[] = $getonlymasterID[$k]['MasterIntSysId'];
            }
        }


        ########### Get All TPIntSysID Which are associated with MasterID based on TPIntSysId ######

        for ($j = 0; $j < count($masterarr); $j++) {
            $allmsterID[] = $objPackage->GetAllTPIntSysIdByMasterID($masterarr[$j]);
        }

        $copyarray = array(); ### This is the main array which holds the club itinerary ID ########
        for ($k = 0; $k < count($allmsterID); $k++) {
            $othermastarr = $allmsterID[$k];
            for ($p = 0; $p < count($othermastarr); $p++) {
                $copyarray[] = $othermastarr[$p]['TPIntSysId'];
            }
        }

        $addedcost = array(); #### It is the Array which holds all the itinerary ID having cost calculated.
        $hoteldetails[] = $objPackage->GetHotelCostByVersion($versionID, $totaltraveler, $TPIntSysId);
        $allcopyitnID = $objPackage->GetAllTPIntSysIdByVersionID($versionID, $TPIntSysId);
        for ($k = 0; $k < count($allcopyitnID); $k++) {
            $addedcost[] = $allcopyitnID[$k]['TPIntSysId'];
        }
        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            if (!in_array($intsysId, $addedcost)) {
                $hoteldetails[] = $objPackage->GetHotelCostForCopyHotel($intsysId, $totaltraveler);
            }
            $allcopyitnID = $objPackage->GetAllTPIntSysIdByMasterID($intsysId);
            for ($k = 0; $k < count($allcopyitnID); $k++) {
                $addedcost[] = $allcopyitnID[$k]['TPIntSysId'];
            }
        }
        for ($m = 0; $m < count($hoteldetails); $m++) {
            $otherhotelarr = $hoteldetails[$m];

            if (isset($otherhotelarr['totalprice'])) {
                $totelhotelprice = round($totelhotelprice + $otherhotelarr['totalprice']);
            }
            if (isset($otherhotelarr['perperson'])) {
                $totalhotelpriceperperson = round($totalhotelpriceperperson + $otherhotelarr['perperson']);
            }
        }
        // echo '<pre>';
        //  print_r($hoteldetails);



        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $getactivitycost[] = $objPackage->GetActivityCostByIten($intsysId, $roominfojson, $adultpax, $childpax, $totaltraveler);
            $totalactivitycost = $totalactivitycost + $getactivitycost[$i]['totalcost'];
            $totalactivitycostperperson = $totalactivitycostperperson + $getactivitycost[$i]['costperperson'];
        }


        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $sscost[] = $objPackage->GetSightSeeingCostByIten(@$intsysId, $roominfojson, $adultpax, $childpax, $totaltraveler);
            $totalsscost = $totalsscost + $sscost[$i]['totalcost'];
            $totalsscostpp = $totalsscostpp + $sscost[$i]['costperperson'];
        }
        $totalinsurancecost = 0;
        ########### Calculate Cost For Travel Insurance #########  
        for ($i = 0; $i < count($itenaryid); $i++) {
            $intsysId = $itenaryid[$i]['TPIntSysId'];
            $insurancecost = $objPackage->GetInsuranceCost($intsysId);
            $totalinsurancecost = $totalinsurancecost + $insurancecost['NetPaid'];
        }



        ########### Get Fixed Costing Data #####################

        $gettransportcost = $objPackage->GetFixedTrnsportCost($tpsysID);

        $totaltransportperpersoncost = 0;
        $totaltransportcost = 0;
        for ($i = 0; $i < count($gettransportcost); $i++) {

            $totaltransportcost = $totaltransportcost + $gettransportcost[$i]['TotalPrice'];
            $totaltransportperpersoncost = $totaltransportperpersoncost + $gettransportcost[$i]['CostPerson'];
        }
        $getmarketwiserate = $objPackage->GetMarketWiseRate($tpsysID);

        if ($getmarketwiserate[0]['MarkType'] == 'FixedAmount') {
            $totalcost = $totelhotelprice + $flightprice + $totalactivitycost + $totalsscost + $totaltransportcost + $totalinsurancecost + $getmarketwiserate[0]['MarkPercent'];
            $flightppprice = $flightprice / $totaltraveler;
            $totalcostperperson = $totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost + $getmarketwiserate[0]['MarkPercent'];
        }
        if ($getmarketwiserate[0]['MarkType'] == 'FixedPercnt') {
            $nettotalcostwithmarkuppercent = $totelhotelprice + $flightprice + $totalactivitycost + $totalsscost + $totaltransportcost + $totalinsurancecost + $getmarketwiserate[0]['MarkPercent'];
            $nettotalcostwithmarkup = ($nettotalcostwithmarkuppercent * $getmarketwiserate[0]['ExcludedPercent']) / 100;
            $totalcost = $nettotalcostwithmarkuppercent + $nettotalcostwithmarkup;
            //      $totalcost =  $nettotalcostwithmarkup+$totalcostwomp;       
            $flightppprice = $flightprice / $totaltraveler;
            $totalcostperpersonwomp = $totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost;
            $totalcostperpersonwmp = ($totalhotelpriceperperson + $flightppprice + $totalactivitycostperperson + $totalsscostpp + $totaltransportperpersoncost) * ($getmarketwiserate[0]['MarkPercent']) / 100;
            $totalcostperperson = $totalcostperpersonwomp + $totalcostperpersonwmp;
        }
        echo $totalcost - $discount;
        ######## CALCULATE NEW COST FOR HOTEL END ###########
    }

    public function updateOptionalActivityAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $versionID = $this->getRequest()->getPost('versionID');
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $adult = $this->getRequest()->getPost('adult');
        $child = $this->getRequest()->getPost('child');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $txt = $this->getRequest()->getPost('txt');
        $totaltraveler = $adult + $child;
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->UpdateOptionalActivity($versionID, $tpintsysID, $tpsysID, $adult, $child, $totaltraveler, $roominfojson, $txt);
    }

    public function changeFlightAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $InvsystemID = $this->getRequest()->getPost('InvsystemID');
        $VersionId = $this->getRequest()->getPost('VersionId');
        $TPIntSysId = $this->getRequest()->getPost('TPIntSysId');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $objPackage = new Travel_Model_TblPackage();

        $data = array(
            'IsSelectedOnPkg' => '0'
        );
        $where = array('TPIntSysId = ? ' => $TPIntSysId);
        $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Air', $data, $where);

        $updatedata = array(
            'IsSelectedOnPkg' => '1'
        );
        $updatedwhere = array('VersionId = ? ' => $VersionId);
        $objPackage->updateData('TB_Agency_Customer_TravelPlan_Air', $updatedata, $updatedwhere);

        $getroomdetails = $objPackage->getroominfo($tpsysID);
        $roominfoarray = json_decode($getroomdetails[0]['RoomInfoJson'], 1);
        $adultcount = 0;
        $childcount = 0;
        for ($k = 1; $k <= count($roominfoarray); $k++) {
            $adultcount = $adultcount + $roominfoarray[$k]['Adult'];
            $childcount = $childcount + $roominfoarray[$k]['Child'];
        }
        $totaltraveler = $adultcount + $childcount;
        $objPackage->UpdateHotelSelection('', '', '', $tpsysID, 'PKG', $getroomdetails[0]['RoomInfoJson'], $adultcount, $childcount, $totaltraveler, '');
    }

    public function updateOptionalActivityByoAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $versionID = $this->getRequest()->getPost('versionID');
        //$markup = $_REQUEST['markup'];

        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $adult = $this->getRequest()->getPost('adult');
        $child = $this->getRequest()->getPost('child');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $txt = $this->getRequest()->getPost('txt');
        $catID = $this->getRequest()->getPost('catID');
        $totaltraveler = $adult + $child;
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->UpdateOptionalBYOActivity($versionID, $tpintsysID, $tpsysID, $adult, $child, $totaltraveler, $roominfojson, $txt, $catID);
    }

    public function changePackageFlightAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $objPackage = new Travel_Model_TblPackage();
        $tpintsysId = $this->_request->getParam('tpintsysId');
        $invitemsysID = $this->_request->getParam('InvnItemSysId');
        $sourceplaceID = $this->_request->getParam('sourceplaceID');
        $getapiflight = $objPackage->GetFlightFromAPI($tpintsysId, $invitemsysID, $sourceplaceID);
        $totalselectedhotel = count($getapiflight);
        /*
          //die;
          // $strApiEndPointUrl = TBO_FLIGHT_URL;
          $getFlightDetailsURL = 'http://api.tektravels.com/BookingEngineService_Air/AirService.svc/rest/Search/';
          $tokenId = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();

          $datah = array(
          'EndUserIp' => $_SERVER['REMOTE_ADDR'],
          'TokenId' => $tokenId,
          "AdultCount" => $getapiflight[0]['AdultPax'],
          "ChildCount" => $getapiflight[0]['ChildPax'],
          "InfantCount" => $getapiflight[0]['InfentPax'],
          "JourneyType" => $getapiflight[0]['JourneyType'],
          "PreferredAirlines" => ["I5","9W"],
          "Segments" => [array('Origin' => $getapiflight[0]['SourceAirportCode'], 'Destination' => $getapiflight[0]['DestAirportCode'],
          'FlightCabinClass' => "1", "PreferredDepartureTime" => '2017-01-22T00:00:00',"PreferredArrivalTime" => '2017-01-22T19:00:00')],


          );

          $data_stringh = json_encode($datah);
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $getFlightDetailsURL);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
          //curl_setopt($ch, CURLOPT_HEADER, true);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/json',
          'Content-Length: ' . strlen($data_stringh)
          ));
          $outputH = curl_exec($ch);
          // print_r($outputH);
          $response = json_decode($outputH,true);
          echo '<pre>';
          print_r($response['Response']['Results'][0]);
          die;
          if($response['Response']['ResponseStatus'] != '1') {
          $this->view->ErrorCode    = $response['Response']['Error']['ErrorCode'];
          $this->view->ErrorMessage = $response['Response']['Error']['ErrorMessage'];
          } else if($response['Response']['ResponseStatus'] == '1') {
          $this->view->arrFlightResults = $response['Response']['Results'][0];
          $this->view->TraceId          = $response['Response']['TraceId'];
          }
         */
    }

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

    public function updateOptionalSightSeeingAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $versionID = $this->getRequest()->getPost('versionID');
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $adult = $this->getRequest()->getPost('adult');
        $child = $this->getRequest()->getPost('child');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $txt = $this->getRequest()->getPost('txt');
        $totaltraveler = $adult + $child;
        $objPackage = new Travel_Model_TblPackage();
        $objPackage->UpdateOptionalSS($versionID, $tpintsysID, $tpsysID, $adult, $child, $totaltraveler, $roominfojson, $txt);
    }

    public function removeinsuranceAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $objPackage = new Travel_Model_TblPackage();
        $getData = $this->getRequest()->getPost();
        $tpsysID = $getData['tpsysID'];
        $companyID = $getData['companysysID'];
        $itineraryID = $getData['itineraryID'];
        $data = array(
            'IsSelected' => '0'
        );
        $where = array('Insurer = ? ' => $companyID, 'TPIntSysId = ? ' => $itineraryID);
        $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Insurance', $data, $where);
        $getroomdetails = $objPackage->getroominfo($tpsysID);
        $roominfoarray = json_decode($getroomdetails[0]['RoomInfoJson'], 1);
        $adultcount = 0;
        $childcount = 0;
        for ($k = 1; $k <= count($roominfoarray); $k++) {
            $adultcount = $adultcount + $roominfoarray[$k]['Adult'];
            $childcount = $childcount + $roominfoarray[$k]['Child'];
        }
        $totaltraveler = $adultcount + $childcount;
        $objPackage->UpdateHotelSelection('', '', '', $tpsysID, 'PKG', $getroomdetails[0]['RoomInfoJson'], $adultcount, $childcount, $totaltraveler, '');
    }

    public function saveinsumemberAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        $tpsysID = $getData['tpID'];
        $companyID = $getData['companyID'];
        $objPackage = new Travel_Model_TblPackage();
        $insuranceitinerary = $objPackage->GetInsuranceItinerary($tpsysID);
        $getroomdetails = $objPackage->getroominfo($tpsysID);
        $roominfoarray = json_decode($getroomdetails[0]['RoomInfoJson'], 1);
        $tpitineraryID = $insuranceitinerary['TPIntSysId'];
        $totaltraveler = $getData['totaltraveler'];
        $suminsured = $getData['suminsured'];
        $premiumprice = $getData['premiumprice'];
        $pricewithtax = $getData['pricewithtax'];
        $masterpolicy = $objPackage->GetMasterPolicySysID($companyID);
        $mastepolicyID = $masterpolicy['MasterPolicySysId'];
        $custpolicyID = $objPackage->GetCustomerPolicyId($mastepolicyID, $tpitineraryID);

        $updateddata = array(
            "IsMarkForDelete" => "1"
        );
        $updatedwhere = array('CustPolicySysId = ? ' => $custpolicyID['CustPolicySysId']);
        $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_InsuMember', $updateddata, $updatedwhere);

        $agebandnum = array();
        $agearray = array("ageband1" => "6-40", "ageband2" => "40-60", "ageband3" => "61-70");
        $ageslab1 = array();
        $ageslab2 = array();
        $ageslab3 = array();
        for ($p = 1; $p <= $totaltraveler; $p++) {
            $agegroup = 'ageband' . $p;
            if ($agegroup) {
                $ageband = $getData[$agegroup];
                $agebandnum[] = $ageband;
            }
            $travelerage = 'travelerage_' . $p;
            if ($getData[$travelerage] >= 6 && $getData[$travelerage] <= 40) {
                $ageslab1[] = $getData[$travelerage];
            }
            if ($getData[$travelerage] >= 41 && $getData[$travelerage] <= 60) {
                $ageslab2[] = $getData[$travelerage];
            }
            if ($getData[$travelerage] >= 61 && $getData[$travelerage] <= 70) {
                $ageslab3[] = $getData[$travelerage];
            }
        }
        if (isset($agebandnum[0])) {
            if ($agebandnum[0] != count($ageslab1)) {
                $response = array('status' => 'Fail', 'msg' => 'Traveler Age Does not match');
                echo json_encode($response);
                exit;
            }
        }
        if (isset($agebandnum[1])) {
            if ($agebandnum[1] != count($ageslab2)) {
                $response = array('status' => 'Fail', 'msg' => 'Traveler Age Does not match');
                echo json_encode($response);
                exit;
            }
        }
        if (isset($agebandnum[2])) {
            if ($agebandnum[2] != count($ageslab3)) {
                $response = array('status' => 'Fail', 'msg' => 'Traveler Age Does not match');
                echo json_encode($response);
                exit;
            }
        }



        for ($k = 1; $k <= $totaltraveler; $k++) {
            $salutation = 'salutation_' . $k;
            $fname = 'fname_' . $k;
            $lname = 'lname_' . $k;
            $dob = 'dob_' . $k;
            $fulladdress = 'fulladdress_' . $k;
            $search_going_from = 'search_going_from_' . $k;
            $going_to_city = explode("__", $getData[$search_going_from]);
            $cityID = $going_to_city[0];
            $explodedate = explode("/", $getData[$dob]);
            $insdob = $explodedate[2] . '-' . $explodedate[1] . '-' . $explodedate[0];
            $email = 'email_' . $k;
            $pincode = 'pincode_' . $k;
            $passport = 'passport_' . $k;
            $nominee = 'nominee_' . $k;
            $createddate = date("Y-m-d");
            $data = array(
                "CustPolicySysId" => $custpolicyID['CustPolicySysId'],
                "Salutation" => $getData[$salutation],
                "Seq" => $k,
                "FirstName" => $getData[$fname],
                "LastName" => $getData[$lname],
                "FullAddress" => $getData[$fulladdress],
                "DOB" => $insdob,
                "Email" => $getData[$email],
                "CitySysId" => $cityID,
                "PinCode" => $getData[$pincode],
                "IDType" => "PASSPORT",
                "IDNumber" => $getData[$passport],
                "Nominee" => $getData[$nominee],
                "CreateDate" => $createddate,
                "UpdateDate" => $createddate,
                "ActivationDate" => $createddate,
                "ApprovalDate" => $createddate,
                "IsVarified" => 1,
                "IsActive" => 1,
                "IsMarkForDelete" => 0,
                "IsApproved" => 1
            );
            $objPackage->insertData('TB_Agency_Customer_TravelPlan_InsuMember', $data);
            //$lastID = $objPackage->lastInsertId();
            $customersysID = $getData['customersysID'];
            $intLoggedinUserAgencySysId = $getData['agencysysID'];
            $agentsysID = $getData['agentID'];
            $objGest = new Travel_Model_Tbltbbcuser();
            $checkCustomerMMMBRrecordChanged = $objGest->getCustomerAndMembersDetailsAll('', trim($getData[$email]), trim($getData[$salutation]), '', trim($getData[$fname]), trim($getData[$lname]), $intLoggedinUserAgencySysId);
            if (count($checkCustomerMMMBRrecordChanged) == 0) {
                $memberdata = array(
                    "AgencySysId" => $intLoggedinUserAgencySysId,
                    "CustomerSysId" => $customersysID,
                    "EmailId" => $getData[$email],
                    "Title" => $getData[$salutation],
                    "Logo" => '',
                    "IsfromSM" => '0',
                    "SMTypeId" => 0,
                    "Contacts" => 0,
                    "SMId" => 0,
                    "UserId" => 0,
                    "IsEmployee" => 0,
                    "FirstName" => $getData[$fname],
                    "LastName" => $getData[$lname],
                    "UserName" => $getData[$fname] . '' . $getData[$lname],
                    "Designation" => '',
                    "Password" => '',
                    "RandStr" => '',
                    "PasswordExpiryDate" => $createddate,
                    "IsPswExpire" => '0',
                    "OtherEmail" => '',
                    "SecondaryEmail" => '',
                    "LastLoginTime" => $createddate,
                    "IsLogInNow" => '0',
                    "RandomCode" => '',
                    "Gender" => '',
                    "UserNickName" => '',
                    "UserPicPath" => '',
                    "ContactNo1" => '0',
                    "ContactNo2" => '0',
                    "HomePhone" => '0',
                    "StateOrZoneSysId" => 0,
                    "CountrySysId" => 0,
                    "SecondaryAddress" => '',
                    "Fax" => '',
                    "MacIp" => '',
                    "SpeakingLangSysId" => '',
                    "Signature" => '',
                    "SecondaryPhone" => '',
                    "UserDetails" => '',
                    "Address" => '',
                    "CreatedByUserSysId" => $agentsysID,
                    "DOB" => $insdob,
                    "UpdateDate" => $createddate,
                    "RegisterDate" => $createddate,
                    "JoinDate" => $createddate,
                    "ExitDate" => $createddate,
                    "CitySysId" => $cityID,
                    "PinCode" => $getData[$pincode],
                    "IsActive" => 1,
                    "IsMarkForDelete" => 0,
                    "IsApproved" => 1
                );

                $objPackage->insertData('TB_Agency_Customer_Members', $memberdata);
            }
        }
        // if($lastID){
        $curr_date = date('Y-m-d');
        $latestpolicynumber = $objPackage->GetLatestPolicyNum($mastepolicyID);
        $childpolicyID = $latestpolicynumber['ChildPolicyId'];
        $data = array(
            'PolicyNo' => $latestpolicynumber['ChildPolicyId'],
            'MemberId' => $latestpolicynumber['ChildPolicyId'],
            'TandC' => 1,
            'CurrencyType' => 1,
            'SumInsured' => $suminsured,
            'Priminum' => $premiumprice,
            'PremiumWithTax' => $pricewithtax,
            'NetPaid' => $pricewithtax,
            'ActivationDate' => $curr_date,
            'ApprovalDate' => $curr_date,
            'IsOptionalInsurance' => 1,
            'IsSelected' => 1,
            'IsVarified' => 1,
            'IsActive' => '1',
            'IsMarkForDelete' => '0',
            'IsApproved' => '1',
            'GeoLocation' => 'Worldwide Excl. US/Canada',
            'Insurer' => $companyID
        );

        $where = array('CustPolicySysId = ? ' => $custpolicyID['CustPolicySysId']);
        $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Insurance', $data, $where);
        $adultcount = 0;
        $childcount = 0;
        for ($k = 1; $k <= count($roominfoarray); $k++) {
            $adultcount = $adultcount + $roominfoarray[$k]['Adult'];
            $childcount = $childcount + $roominfoarray[$k]['Child'];
        }
        $totaltraveler = $adultcount + $childcount;
        $objPackage->UpdateHotelSelection('', '', '', $tpsysID, 'PKG', $getroomdetails[0]['RoomInfoJson'], $adultcount, $childcount, $totaltraveler, '');
    }

    public function addCustomerActivityDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
    }

    public function addCustomerSsDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
    }

    public function getinsurancequoteAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $objPackage = new Travel_Model_TblPackage();
        $ageband1 = $this->_request->getParam('ageband1');
        $ageband2 = $this->_request->getParam('ageband2');
        $ageband3 = $this->_request->getParam('ageband3');
        $totaltraveler = $this->_request->getParam('totaltraveler');
        $totaldays = $this->_request->getParam('totaldays');
        $pkgstartdate = $this->_request->getParam('pkgstartdate');
        $pkgenddate = $this->_request->getParam('pkgenddate');
        $agencysysID = $this->_request->getParam('agencysysID');
        $agentID = $this->_request->getParam('agentID');
        $destinationplaces = $this->_request->getParam('destinationplaces');
        $tpsysID = $this->_request->getParam('tpsysID');
        $endpointurl = INSURANCE_URL;
        $imgpath = '/../public/upload/insurer/';
        $suminsured = $this->_request->getParam('suminsured');
        $apiData = array(
            'traveldestination' => 'Worldwide',
            'suminsured' => $suminsured,
            'age_band_0_40' => $ageband1,
            'age_band_41_60' => $ageband2,
            'age_band_61_70' => $ageband3,
            'travellers' => $totaltraveler,
            'trip_start_date' => $pkgstartdate,
            'trip_end_date' => $pkgenddate,
            'noofdays' => $totaltraveler,
            'AgencySysId' => $agencysysID,
            'UserSysId' => $agentID,
        );
        try {
            $curl = curl_init($endpointurl);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiData));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            $premium_response = curl_exec($curl);
            curl_close($curl);
            $this->view->premium_response = $premium_response; // send response to the view page
        } catch (Exception $error) {
            $this->view->error_msg = $error->getMessage();
            die;
        }
        $premiumarr = json_decode($premium_response, 1);
        $itinerarydetail = $objPackage->GetInsuranceItinerary($tpsysID);
        $tpitineraryID = $itinerarydetail['TPIntSysId'];
        $getselectedmasterpolicyID = $objPackage->GetSelectedPolicyIdByCustomer($tpitineraryID);
        $custinsurerID = array();
        for ($k = 0; $k < count($getselectedmasterpolicyID); $k++) {
            $custinsurerID[] = trim($getselectedmasterpolicyID[$k]['Insurer']);
        }
        ?>
        <div class="modal-body">
            <div class="modal-header">
                <h3 class="no-margin no-padding">Select Insurer</h3>
            </div>
            <div class="col-md-12 no-padding">
                <div class="form-group form-group1 border-bottom" style="padding-top:15px;">
                    <label class="col-md-3 col-sm-3 no-padding" style="line-height:34px;">Sum Insured : </label>
                    <select style="width:200px; border: 1px solid #cccccc; border-radius: 4px; box-shadow: none; box-sizing: border-box; display: block; overflow: hidden; padding: 6px 4px; position: relative; width: 100%; z-index: 1;" id="suminusred" name="suminusred" class="selectize-inputnew col-md-12 col-sm-12" placeholder="Select">
                        <option value="50000" onclick="return ViewInsuranceOption('50000');" <?php if ($suminsured == "50000") { ?>selected="selected" <?php } ?>>50,000</option>
                        <option value="100000" onclick="return ViewInsuranceOption('100000');" <?php if ($suminsured == "100000") { ?>selected="selected" <?php } ?>>1,00,000</option>
                    </select>
                    <div class="clearfix"></div>
                </div>
                <?php
                for ($i = 0; $i < count($premiumarr); $i++) {
                    if (in_array($premiumarr[$i]['CompSysId'], $custinsurerID)) {
                        $premiumprice = $premiumarr[$i]['premium'];
                        $premiumpricewithtax = $premiumarr[$i]['premiumWithTax'];
                        $copmsysID = $premiumarr[$i]['CompSysId'];
                        $getcustselected = $objPackage->GetSelectedInsurer($copmsysID, $tpitineraryID);
                        $policyID = $getcustselected['PolicyNo'];
                        ?>
                        <div class="clear" style="padding-top:20px;">
                            <div class="col-md-3 col-sm-3 no-padding"> <img alt="insuranceimage" src="<?php echo $imgpath; ?>/<?php echo $premiumarr[$i]['logo']; ?>" style="max-width:80%;"> </div>
                            <div class="col-md-3 col-sm-3 text-center"> <strong class="orange"><i class="fa fa-rupee"></i>
                                    <?php echo $premiumarr[$i]['premiumWithTax']; ?></strong> </div>
                            <div class="col-md-3 col-sm-3 no-padding text-center">
                                <button data-target="#myModa1insuranceDetail" onclick="getpolicydetals('<?php echo $premiumarr[$i]['CompSysId'] ?>', 'Worldwide', '<?php echo $premiumarr[$i]['premiumWithTax'] ?>');" data-toggle="modal" class="btn btn-default btn-sm"><i class="fa fa-arrows"></i> Details</button>
                            </div>
                            <div class="col-md-3 col-sm-3 text-right">
                                <?php
                                if ($policyID) {
                                    ?>
                                    <button type="button" class="btn btn-warning" data-toggle="modal" onclick="removeinsurance('<?php echo $copmsysID; ?>', '<?php echo $tpitineraryID; ?>', '<?php echo $tpsysID; ?>');">Remove</button>
                                <?php } else { ?>
                                    <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#memberdetail" onclick="showtravelerform('<?php echo $premiumarr[$i]['CompSysId'] ?>', '<?php echo $premiumarr[$i]['logo'] ?>', '<?php echo $premiumarr[$i]['name'] ?>', '<?php echo $premiumarr[$i]['premiumWithTax']; ?>', '<?php echo $premiumprice; ?>');">Select</button>
                                <?php } ?>
                            </div>
                        </div>
                        <div class="clear"></div>

                    </div>
                    <?php
                }
            }
            ?>
        </div>

        <div class="clear"></div>

        <div class="modal-footer" style="margin-top:12px;">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>

        <?php
    }

    public function viewHotelDetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        if (!$this->_request->isXmlHttpRequest()) {
            $this->view->layoutType = 'browser';
            $AccomSysId = base64_decode($this->getRequest()->getParam('hotelid'));
        } else {
            $AccomSysId = $this->getRequest()->getParam('hotelid');
        }


        $objAccom = new Travel_Model_TblICAccomdation();
        $objAccImg = new Travel_Model_TblAccomoImg();
        $accomoDetailArr = $objAccom->getAccomodation($AccomSysId);
        $this->view->accomoDetailsArr = $accomoDetailArr;
        //        echo '<pre>'; print_r($accomoDetails);
        $accImgArr = $objAccImg->getAccomoImage($AccomSysId);
        $this->view->accImgArr = $accImgArr;
    }

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

    public function viewPnrFormAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $packageId = $this->getRequest()->getParam('pid') ? $this->_HtmlPurifier->filter($this->getRequest()->getParam('pid')) : '';
        $type = $this->getRequest()->getParam('type') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('type'))) : '';

        $packageId = base64_decode($packageId);
        if (isset($packageId) && !empty($packageId)) {
            $objPackage = new Travel_Model_TblPackage();
            $flexiPackageList = $objPackage->getCustPackageList($packageId);
            $this->view->type = 'viewPnrUpdateForm';
            $this->view->InvertryType = $type;
            $this->view->id = base64_encode($packageId);
            $this->view->flexiPackageList = $flexiPackageList;
            $this->render('ajax-html');
        }
    }

    public function viewUpdateConfirmationFormAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $packageId = $this->getRequest()->getParam('pid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('pid'))) : '';
        $aid = $this->getRequest()->getParam('aid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('aid'))) : '';
        $tpid = $this->getRequest()->getParam('tpid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('tpid'))) : '';
        $seqid = $this->getRequest()->getParam('seqid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('seqid'))) : '';
        $vid = $this->getRequest()->getParam('vid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('vid'))) : '';
        $eventType = $this->getRequest()->getParam('type') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('type'))) : '';
        if (isset($packageId) && !empty($packageId)) {
            $objPackage = new Travel_Model_TblPackage();
            $flexiPackageList = $objPackage->getCustPackageList($packageId);
            $this->_crmcusttravelplanFullfillment = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
            //echo "<pre>";print_r($accomDetails);echo "</pre>";die;
            //$objHotel = new Travel_Model_TblHotel();
            //$hotelDetails=$objHotel->getHotelDetailsById($aid);
            $fromdate = $this->getRequest()->getParam('fromdate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('fromdate'))) : '';
            $todate = $this->getRequest()->getParam('todate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('todate'))) : '';
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $supplierOnCallDetails = $supplierOnCallObj->ChkRecordExist($packageId, $aid);
            if ($eventType == 'room') {
                $accomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $vid, $aid);
                $custTravelAcoomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $vid, $aid);
                $this->view->type = 'viewHotelConfirmationUpdateForm';
                $this->view->accomDetails = $accomDetails;
                $this->view->custTravelAcoomDetails = $custTravelAcoomDetails;
            }
            if ($eventType == 'roomreadymade') {
                $accomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $vid, $aid);
                $custTravelAcoomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $vid, $aid);
                $this->view->type = 'viewReadymadeHotelConfirmationUpdateForm';
                $this->view->accomDetails = $accomDetails;
                $this->view->custTravelAcoomDetails = $custTravelAcoomDetails;
            }
            if ($eventType == 'activity') {
                $this->view->type = 'viewActivityConfirmationUpdateForm';
                $activityDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenaryEventIds($tpid, $vid, $aid);
                //echo "<pre>";print_r($activityDetails);echo "</pre>";die;
                $this->view->dataDetails = $activityDetails;
            }
            if ($eventType == 'sightseeing') {
                $this->view->type = 'viewSightseeingConfirmationUpdateForm';
                $sightseeingDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenarySSIds($tpid, $vid, $aid);
                //echo "<pre>";print_r($sightseeingDetails);echo "</pre>";die;
                $this->view->dataDetails = $sightseeingDetails;
            }
            if ($eventType == 'activityreadymade') {
                $this->view->type = 'viewReadymadeActivityConfirmationUpdateForm';
                $activityDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenaryEventIds($tpid, $vid, $aid);
                //echo "<pre>";print_r($activityDetails);echo "</pre>";die;
                $this->view->dataDetails = $activityDetails;
            }
            if ($eventType == 'sightseeingreadymade') {
                $this->view->type = 'viewReadymadeSightseeingConfirmationUpdateForm';
                $sightseeingDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenarySSIds($tpid, $vid, $aid);
                //echo "<pre>";print_r($sightseeingDetails);echo "</pre>";die;
                $this->view->dataDetails = $sightseeingDetails;
            }

            $this->view->supplierOnCallDetails = $supplierOnCallDetails;
            $this->view->InvertryType = $eventType;
            $this->view->id = base64_encode($packageId);
            $this->view->aid = base64_encode($aid);
            $this->view->vid = base64_encode($vid);
            $this->view->tpid = base64_encode($tpid);
            $this->view->seqid = base64_encode($seqid);
            $this->view->flexiPackageList = $flexiPackageList;
            //$this->view->hotelDetails=$hotelDetails;
            $this->view->fromdate = $fromdate;
            $this->view->todate = $todate;

            $this->render('ajax-html');
        }
    }

    public function viewChangeSupplierFormAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $packageId = $this->getRequest()->getParam('pid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('pid'))) : '';
        $tpid = $this->getRequest()->getParam('tpid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('tpid'))) : '';
        $type = $this->getRequest()->getParam('type') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('type'))) : '';
        $AccomSysId = $this->getRequest()->getParam('hid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('hid'))) : '';
        $seqid = $this->getRequest()->getParam('seqid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('seqid'))) : '';
        $ActivityId = $this->getRequest()->getParam('aid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('aid'))) : '';
        $VersionId = $this->getRequest()->getParam('vid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('vid'))) : '';
        $DestinationSysId = $this->getRequest()->getParam('did') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('did'))) : '';
        $invid = $this->getRequest()->getParam('invid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('invid'))) : '';
        if (isset($packageId) && !empty($packageId)) {
            $this->_crmcusttravelplanFullfillment = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
            $data = '';
            if ($type == 'seat') {
                $this->view->type = 'viewChangeFlightSupplierForm';
            } else if ($type == 'room') {
                $fromdate = $this->getRequest()->getParam('fromdate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('fromdate'))) : '';
                $todate = $this->getRequest()->getParam('todate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('todate'))) : '';
                $cityId = $DestinationSysId;
                $objSupplier = new Travel_Model_TblSupplier();
                $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
                $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
                $SupplierList = $objSupplier->getSuppliersContactListPack($cityId, $AgencySysId);
                $SupplierServicesArrDB = $objSupplier->getSupplierServices(); //Get Supplier Services
                $custTravelAcoomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $VersionId, $ActivityId);
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                //echo "<pre>";print_r($flexiPackageList);die;
                $crmcustomerObj = new Travel_Model_CRM_Customer();
                $getCustomerDetails = $crmcustomerObj->GetAgencyCustomerById(trim($flexiPackageList['CustomerSysId']));
                $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById(trim($flexiPackageList['AgencySysId']));
                $crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
                $getAgentDetail = $crmcusttravelplan->getAgentDetails(trim($flexiPackageList['AgentSysId']));

                $this->view->getCustomerDetails = $getCustomerDetails;
                $this->view->getAgencyDetail = $getAgencyDetail;
                $this->view->getAgentDetail = $getAgentDetail;
                $this->view->flexiPackageList = $flexiPackageList;
                $this->view->arrSupplierServices = $SupplierServicesArrDB;
                $this->view->SupplierList = $SupplierList;
                $this->view->custTravelAcoomDetails = $custTravelAcoomDetails;
                $this->view->pid = $packageId;
                $this->view->aid = $ActivityId;
                $this->view->tpid = $tpid;
                $this->view->invid = $invid;
                $this->view->fromdate = $fromdate;
                $this->view->todate = $todate;
                $this->view->type = 'viewChangeHotelSupplierForm';
            } else if ($type == 'activity') {
                $this->view->type = 'viewChangeActivitySupplierForm';
                $data = $this->_crmcusttravelplanFullfillment->getCustPackageActivityListBySeqWithId($packageId, $seqid, $ActivityId);
            } else if ($type == 'sightseeing') {
                $this->view->type = 'viewChangeSightSeeingSupplierForm';
                $data = $this->_crmcusttravelplanFullfillment->getCustPackageSightseenListBySeqWithId($packageId, $seqid, $ActivityId);
            } else {
                $data = array();
            }
            //echo "<pre>";print_r($data);

            $this->view->aid = $ActivityId;
            $this->view->vid = $VersionId;
            $this->view->eventType = $type;
            /* else if($type=='sightseeing'){			
              $objPackage = new Travel_Model_TblPackage();
              $data = $objPackage->getCustPackageSightseenListBySeqWithId($packageId,$seqid,$ActivityId);
              $this->view->type='viewChangeSightSeeingSupplierForm';
              } */

            $this->view->id = $packageId;
            $this->view->data = $data;
            $this->render('ajax-html');
        }
    }

    public function viewEnquireFormAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $packageId = $this->getRequest()->getParam('pid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('pid'))) : '';
        $tpid = $this->getRequest()->getParam('tpid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('tpid'))) : '';
        $eventType = $this->getRequest()->getParam('type') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('type'))) : '';
        $sid = $this->getRequest()->getParam('sid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('sid'))) : '';
        $aid = $this->getRequest()->getParam('aid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('aid'))) : '';
        $invid = $this->getRequest()->getParam('invid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('invid'))) : '';
        $vid = $this->getRequest()->getParam('vid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('vid'))) : '';

        $suppId = $this->getRequest()->getParam('suppId') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('suppId'))) : '';
        if (isset($packageId) && !empty($packageId)) {
            $objPackage = new Travel_Model_TblPackage();
            $this->_crmcusttravelplanFullfillment = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
            $pkgSupplierDetails = array();
            $checkSupplierOnCallRecordExist = array();
            if ($eventType == 'hotel') {
                $fromdate = $this->getRequest()->getParam('fromdate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('fromdate'))) : '';
                $todate = $this->getRequest()->getParam('todate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('todate'))) : '';
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                $objSupplier = new Travel_Model_TblSupplier();
                $objHotel = new Travel_Model_TblHotel();
                $hotelDetails = $objHotel->getHotelDetailsById($aid);

                //echo "<pre>";print_r($hotelDetails);echo "</pre>";
                if ((int) $suppId > 0) {
                    $objSupplier->SupplierSysId = $suppId;
                    $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                    $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                    $checkSupplierOnCallRecordExist = $supplierOnCallObj->ChkRecordExist($packageId, $aid);
                }
                //echo "<pre>";print_r($checkSupplierOnCallRecordExist);echo "</pre>";
                $crmcustomerObj = new Travel_Model_CRM_Customer();
                $getCustomerDetails = $crmcustomerObj->GetAgencyCustomerById(trim($flexiPackageList['CustomerSysId']));
                $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById(trim($flexiPackageList['AgencySysId']));
                $crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
                $getAgentDetail = $crmcusttravelplan->getAgentDetails(trim($flexiPackageList['AgentSysId']));
                $custTravelAcoomDetails = $this->_crmcusttravelplanFullfillment->GetCustomerItenaryAccomDetailsFullfill($tpid, $vid, $aid);
                //echo "<pre>";print_r($custTravrlAcoomDetails);echo "</pre>";
                $this->view->type = 'viewHotelEnquireForm';
                $this->view->pkgSupplierDetails = $pkgSupplierDetails;
                $this->view->checkSupplierOnCallRecordExist = $checkSupplierOnCallRecordExist;
                $this->view->custTravelAcoomDetails = $custTravelAcoomDetails;

                $this->view->hotelDetails = $hotelDetails;
                $this->view->getCustomerDetails = $getCustomerDetails;
                $this->view->getAgencyDetail = $getAgencyDetail;
                $this->view->getAgentDetail = $getAgentDetail;
                $this->view->pid = $packageId;
                $this->view->aid = $aid;
                $this->view->tpid = $tpid;
                $this->view->invid = $invid;
                $this->view->fromdate = $fromdate;
                $this->view->todate = $todate;
            } else if ($eventType == 'activity') {
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                $objSupplier = new Travel_Model_TblSupplier();
                $activityDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenaryEventIds($tpid, $vid, $aid);

                //echo "<pre>";print_r($activityDetails);echo "</pre>";
                if ((int) $suppId > 0) {
                    $objSupplier->SupplierSysId = $suppId;
                    $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                    $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                    $checkSupplierOnCallRecordExist = $supplierOnCallObj->ChkRecordExist($packageId, $aid);
                }
                //echo "<pre>";print_r($checkSupplierOnCallRecordExist);echo "</pre>";
                $this->view->type = 'viewActivityEnquireForm';
                $this->view->pkgSupplierDetails = $pkgSupplierDetails;
                $this->view->checkSupplierOnCallRecordExist = $checkSupplierOnCallRecordExist;

                $this->view->activityDetails = $activityDetails;
                $this->view->pid = $packageId;
                $this->view->aid = $aid;
                $this->view->tpid = $tpid;
                $this->view->invid = $invid;
            } else if ($eventType == 'sightseeing') {
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                $objSupplier = new Travel_Model_TblSupplier();
                $sightseeingDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenarySSIds($tpid, $vid, $aid);

                //echo "<pre>";print_r($hotelDetails);echo "</pre>";
                if ((int) $suppId > 0) {
                    $objSupplier->SupplierSysId = $suppId;
                    $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                    $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                    $checkSupplierOnCallRecordExist = $supplierOnCallObj->ChkRecordExist($packageId, $aid);
                }
                //echo "<pre>";print_r($checkSupplierOnCallRecordExist);echo "</pre>";
                $this->view->type = 'viewSightseeingEnquireForm';
                $this->view->pkgSupplierDetails = $pkgSupplierDetails;
                $this->view->checkSupplierOnCallRecordExist = $checkSupplierOnCallRecordExist;

                $this->view->sightseeingDetails = $sightseeingDetails;
                $this->view->pid = $packageId;
                $this->view->aid = $aid;
                $this->view->tpid = $tpid;
                $this->view->invid = $invid;
            } else if ($eventType == 'privatetransport') {
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                $objSupplier = new Travel_Model_TblSupplier();
                $transportDetails = $this->_crmcusttravelplanFullfillment->GetCustTravelPlanItenaryTransDetails($tpid, $sid, $aid);

                //echo "<pre>";print_r($transportDetails);echo "</pre>";
                if ((int) $suppId > 0) {
                    $objSupplier->SupplierSysId = $suppId;
                    $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                    $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                    $checkSupplierOnCallRecordExist = $supplierOnCallObj->ChkRecordExist($packageId, $aid);
                }
                //echo "<pre>";print_r($checkSupplierOnCallRecordExist);echo "</pre>";
                $this->view->type = 'viewPrivateTransportEnquireForm';
                $this->view->pkgSupplierDetails = $pkgSupplierDetails;
                $this->view->checkSupplierOnCallRecordExist = $checkSupplierOnCallRecordExist;

                $this->view->transportDetails = $transportDetails;
                $this->view->pid = $packageId;
                $this->view->aid = $aid;
                $this->view->vid = $vid;
                $this->view->tpid = $tpid;
                $this->view->seqid = $sid;
                $this->view->invid = $invid;
            } else {
                $flexiPackageList = $objPackage->getCustPackageList($packageId);
                $this->view->type = 'viewEnquireForm';
            }

            $this->view->id = base64_encode($packageId);
            $this->view->flexiPackageList = $flexiPackageList;
            $this->render('ajax-html');
        }
    }

    public function viewUpdateVoucherFormAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $packageId = $this->getRequest()->getParam('pid') ? $this->_HtmlPurifier->filter($this->getRequest()->getParam('pid')) : '';
        $TPIntSysId = $this->getRequest()->getParam('tpid') ? $this->_HtmlPurifier->filter($this->getRequest()->getParam('tpid')) : '';
        $aid = $this->getRequest()->getParam('aid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('aid'))) : '';
        $vid = $this->getRequest()->getParam('vid') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('vid'))) : '';
        $type = $this->getRequest()->getParam('type') ? $this->_HtmlPurifier->filter($this->getRequest()->getParam('type')) : '';
        $packageId = base64_decode($packageId);
        $data = '';
        if (isset($packageId) && !empty($packageId)) {
            $objPackage = new Travel_Model_TblPackage();
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $supplierOnCallDetails = $supplierOnCallObj->ChkRecordExist($packageId, $aid, base64_decode($TPIntSysId));
            //$data = $objPackage->getCustPackageList($packageId);
            if ($type == 'activity') {
                $data = $objPackage->getCustomerTravelPlanEventsByIdFullfillment($aid, $vid);
            }
            if ($type == 'sightseeing') {
                $data = $objPackage->getCustomerTravelPlanSSByIdFullfillment($aid, $vid);
            }
            if ($type == 'publictransport') {
                $data = $objPackage->getPublicTransportDetailsByIdFullfillment($packageId, $aid);
            }
            if ($type == 'privatetransport') {
                $data = $objPackage->getPublicTransportDetailsByIdFullfillment($packageId, $aid);
            }
            if ($type == 'otherservice') {
                $data = $objPackage->getCustomerTravelPlanOSByIdFullfillment($packageId, $aid);
            }
            //echo "<pre>";print_r($data);die;
            $this->view->type = 'viewUpdateVoucherForm';
            $this->view->eventType = base64_encode($type);
            $this->view->id = base64_encode($packageId);
            $this->view->aid = base64_encode($aid);
            $this->view->vid = base64_encode($vid);
            $this->view->tpid = $TPIntSysId;
            $this->view->data = $data;
            $this->view->supplierOnCallDetails = $supplierOnCallDetails;
            $this->render('ajax-html');
        }
    }

    public function updateHotelDetailsAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $supplierArray = $this->getRequest()->getParam('supplierArray') ? $this->_HtmlPurifier->filterArray($this->getRequest()->getParam('supplierArray')) : '';
        $emailText = $this->_HtmlPurifier->filter($this->getRequest()->getParam('enquiryEmail'));
        $type = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('type')));
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $tpid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('tpid')));
        $aid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('aid')));
        $price = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('price')));
        $InvnItemSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('invid')));

        $allData = json_decode($this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('Hdetails'))), 1);
        //echo "<pre>";print_r($allData);
        if (!empty($supplierArray)) {
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
            $AgentSysId = $sessionLogin_user->intLoggedinUserId;
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
            for ($i = 0; $i < count($supplierArray); $i++) {
                //send email to supplier
                $objSupplier = new Travel_Model_TblSupplier();
                $suppId = $supplierArray[$i];
                //echo "<pre>";print_r($hotelDetails);echo "</pre>";
                if ((int) $suppId > 0) {
                    $objPackage = new Travel_Model_TblPackage();
                    $flexiPackageList = $objPackage->getCustPackageList($TPSysId);
                    $roominfojson = json_decode($flexiPackageList['RoomInfoJson'], true);
                    //echo "<pre>";print_r($roominfojson);die;
                    //send of send email
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
                    // render view
                    $html->assign('type', 'sendHotelDynamicEnquiryDetail');
                    if ((int) $suppId > 0) {
                        $objSupplier = new Travel_Model_TblSupplier();
                        $objSupplier->SupplierSysId = $suppId;
                        $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                    }
                    $html->assign('agencyDetails', $getAgencyDetail);
                    $html->assign('agentDetails', $getAgentDetail);
                    $html->assign('supplierDetails', $pkgSupplierDetails);
                    $html->assign('roominfojson', $roominfojson);

                    //echo "<pre>";print_r($getAgentDetail);
                    $html->assign('data', $allData);
                    $html->assign('emailText', $emailText);
                    $bodyText = $html->render('ajax-html.phtml');
                    $emailId = trim($pkgSupplierDetails[0]['EmailId']);
                    //$emailId='amit.k@catpl.co.in';
                    $fromName = $this->fromName;
                    $fromEmail = $this->fromEmail;
                    $subject = 'Package Hotel Enquiry Details-' . $TPSysId;
                    $emailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                    $emailData_Agent = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($getAgentDetail['EmailId'])), 'bodyHtml' => $bodyText, 'bodyText' => '');

                    try {
                        $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                        $arrEmailStatistics = array(
                            "TPSysId" => $TPSysId,
                            "TypeSysId" => 1, // 1 For Email 2 For SMS
                            "AgencySysId" => $AgencySysId,
                            "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                            "Title" => $bodyText,
                            "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                            "Status" => 0,
                            "RefSysId" => "",
                            "RefSysStatus" => "",
                            "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                        );
                        $this->mailSentByElastice($emailData, $arrEmailStatistics, 0, 0);
                        $this->mailSentByElastice($emailData_Agent, $arrEmailStatistics, 0, 0);
                        //insert data for sent email
                        $dataArray = array(
                            "TPSysId" => $TPSysId,
                            "TPIntSysId" => 1, // 1 For Email 2 For SMS
                            "AgencySysId" => $AgencySysId,
                            "SupplierSysId" => isset($suppId) ? $suppId : 0,
                            "InvnItemSysId" => $InvnItemSysId,
                            "ItemSysId" => $InvnItemSysId,
                            "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                            "EmailTextFromAgent" => $emailText,
                            "FromName" => $fromName,
                            "FromEmail" => $fromEmail,
                            "EmailTo" => $emailId,
                            "EmailSubject" => $subject,
                            "IsReplyFromSupplier" => 0,
                            "IsQueryConfirmed" => 0,
                            "EmailQueryType" => 2, // 2 for hotel
                            "PlanType" => 5, // for package
                            "IsActive" => 1,
                            "IsMarkForDelete" => 0,
                            "StatusSysId" => 0,
                            "CreatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss'),
                            "UpdatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                        );
                        //print_r($dataArray);die;
                        try {
                            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                            $insertEmailData = $supplierOnCallObj->insertData('TB_Agency_Customer_SupplierEmail_Fullfillment', $dataArray);
                            $response = array('status' => true);
                        } catch (Exception $err) {
                            print_r($err, true);
                            $response = array('status' => false);
                        }
                        //echo 'Email has sent to customer';
                    } catch (Exception $err) {
                        print_r($err, true);
                        $response = array('status' => false);
                    }
                }
                //#end of send email to supplier
            }
        }

        echo json_encode($response);
        exit;
    }

    //update status for activity/sighseeing created by Er Amit Kumar Dubey on 04-july-2017 at 5:10 PM
    public function updateItenaryStatusAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $TPIntSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('iid')));
        $eventType = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('eventType')));
        $aid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('aid')));
        $vid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('vid')));
        $statusId = $this->_HtmlPurifier->filter($this->getRequest()->getParam('sid'));
        $suppId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('suppId')));
        $callSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('callSysId')));
        if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
            //$where = "TPSysId = ". $TPSysId;
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid, $TPIntSysId);
            $date = date('Y-m-d H:i:s');
            if (!empty($checkRecordExist)) {
                $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                $userArray = array(
                    'StatusSysId' => $statusId,
                    'UpdatedOn' => $date,
                );
                $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
            } else {
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                //echo "<pre>";print_r($flexiPackageItenList);	
                $TPIntSysId = $TPIntSysId ? $TPIntSysId : $flexiPackageItenList[0]['TPIntSysId'];
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'TPIntSysId' => $TPIntSysId,
                    'SupplierSysId' => $suppId,
                    'ItemSysId' => $aid,
                    'StatusSysId' => $statusId,
                    'CreatedOn' => $date,
                    'UpdatedOn' => $date,
                    'IsActive' => 1,
                    'AgencySysId' => $agencysysID,
                    'IsSupAvalOnCall' => '',
                    'OnCallSupRate' => 0,
                    'OnCallSupRooms' => 0,
                    'OnCallSupRateFrom' => $date,
                    'OnCallSupRateTo' => $date,
                    'OnCallSupRateValidTill' => $date,
                    'OnCallSupRemarks' => '',
                    'IsMarkForDel' => 0
                );
                $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
            }
            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => ''));
        exit;
    }

    //update status for activity/sighseeing created by Er Amit Kumar Dubey on 04-july-2017 at 5:20 PM
    public function updateEventVoucherAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $TPIntSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('tpid')));
        $aid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('aid')));
        $vid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('vid')));
        $voucher = $this->_HtmlPurifier->filter($this->getRequest()->getParam('voucherNumber'));
        $updateremarks = $this->_HtmlPurifier->filter($this->getRequest()->getParam('updateremarks'));
        $eventType = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('eventType')));
        $title = '';
        $statusId = 57;
        if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
            //$where = "TPSysId = ". $TPSysId;

            if ($eventType == 'activity') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelItenaryEventsFullfillment();
                $where = "TPActivitySysId = " . $aid . " AND VersionId=" . $vid;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'XRefVoucherNo' => $voucher,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelItenaryEvents($userArray, $where);
            }
            if ($eventType == 'sightseeing') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelItenarySightSeeingFullfillment();
                $where = "SSSysId = " . $aid . " AND VersionId=" . $vid;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'XRefVoucherNo' => $voucher,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelSightSeeing($userArray, $where);
            }
            if ($eventType == 'publictransport') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelPlanFixedFullfillment();
                $where = "FixTransSysId = " . $aid . " AND TPSysId=" . $TPSysId;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'XRefVoucherNo' => $voucher,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelPlanFixedTrans($userArray, $where);
            }
            if ($eventType == 'privatetransport') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelPlanFixedFullfillment();
                $where = "FixTransSysId = " . $aid . " AND TPSysId=" . $TPSysId;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'XRefVoucherNo' => $voucher,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelPlanFixedTrans($userArray, $where);
            }
            if ($eventType == 'otherservice') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelOtherServicesFullfillment();
                $where = "OtherSrvSysId = " . $aid . " AND TPIntSysId=" . $TPSysId . " AND VersionId = " . $vid;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'XRefVoucherNo' => $voucher,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelPlanOtherService($userArray, $where);
            }

            //update status
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid, $TPIntSysId);
            $date = date('Y-m-d H:i:s');
            if (!empty($checkRecordExist)) {
                $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                $userArray = array(
                    'StatusSysId' => $statusId,
                    'OnCallSupRemarks' => $updateremarks,
                    'UpdatedOn' => $date,
                );
                $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
            } else {
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                //echo "<pre>";print_r($flexiPackageItenList);	
                $TPIntSysId = isset($TPIntSysId) ? $TPIntSysId : $flexiPackageItenList[0]['TPIntSysId'];
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'TPIntSysId' => $TPIntSysId,
                    'SupplierSysId' => isset($suppId) ? $suppId : 0,
                    'ItemSysId' => $aid,
                    'StatusSysId' => $statusId,
                    'CreatedOn' => $date,
                    'UpdatedOn' => $date,
                    'IsActive' => 1,
                    'AgencySysId' => $agencysysID,
                    'IsSupAvalOnCall' => '',
                    'OnCallSupRate' => 0,
                    'OnCallSupRooms' => 0,
                    'OnCallSupRateFrom' => $date,
                    'OnCallSupRateTo' => $date,
                    'OnCallSupRateValidTill' => $date,
                    'OnCallSupRemarks' => $updateremarks,
                    'IsMarkForDel' => 0
                );
                $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
            }
            $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
            $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
            //print_r($statusArray);
            $title = trim(stripslashes($statusArray));
            //# update status 			



            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => $title));
        exit;
    }

    //update supplier id for activity/sighseeing created by Er Amit Kumar Dubey on 04-july-2017 at 06:39 PM
    public function updateEventSupplierAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $aid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('aid')));
        $vid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('vid')));
        $sid = $this->_HtmlPurifier->filter($this->getRequest()->getParam('sid'));
        $eventType = $this->_HtmlPurifier->filter($this->getRequest()->getParam('eventType'));
        if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
            //$where = "TPSysId = ". $TPSysId;

            if (trim($eventType) == 'activity') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelItenaryEvents();
                $where = "TPActivitySysId = " . $aid . " AND VersionId=" . $vid;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'SupplierSysId' => $sid,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelItenaryEvents($userArray, $where);
            }
            if ($eventType == 'sightseeing') {
                $eventsObj = new Travel_Model_CRM_CustomerTravelItenarySightSeeing();
                $where = "SSSysId = " . $aid . " AND VersionId=" . $vid;
                $date = date('Y-m-d H:i:s');
                $userArray = array(
                    'SupplierSysId' => $sid,
                    'UpdateDate' => $date,
                );
                $Rcord = $eventsObj->UpdateTravelSightSeeing($userArray, $where);
            }
            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => ''));
        exit;
    }

    //update hotel confirmation  created by Er Amit Kumar Dubey on 06-july-2017 at 4:29 PM
    public function updateHotelConfirmationAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($getData);
            //echo "<pre>";print_r($_FILES);
            //exit;
            $TPSysId = $this->_HtmlPurifier->filter(base64_decode($getData['id']));
            $aid = $this->_HtmlPurifier->filter(base64_decode($getData['aid']));
            $tpid = $this->_HtmlPurifier->filter(base64_decode($getData['tpid']));
            $seqid = $this->_HtmlPurifier->filter(base64_decode($getData['seqid']));
            $HconfirmNo = $this->_HtmlPurifier->filter($getData['hotelconfirmationnumber']);
            $hotelbookingconfirmed = isset($getData['hotelbookingconfirmed']) ? $this->_HtmlPurifier->filter($getData['hotelbookingconfirmed']) : 0;
            $SconfirmNo = '';
            $hotelsupplierpickuptotalcost = isset($getData['hotelsupplierpickuptotalcost']) ? $this->_HtmlPurifier->filter($getData['hotelsupplierpickuptotalcost']) : '';
            $hotelsupplierpickupfinalcost = isset($getData['hotelsupplierpickupfinalcost']) ? $this->_HtmlPurifier->filter($getData['hotelsupplierpickupfinalcost']) : '';
            $hotelremarks = $this->_HtmlPurifier->filter($getData['hotelremarks']);
            $emailText = $this->_HtmlPurifier->filter(@$getData['emailText']);
            $is_hotelbookingconfirmed = $this->_HtmlPurifier->filter($getData['is_hotelbookingconfirmed']);
            $pickupndrop = $this->_HtmlPurifier->filter($getData['pickupndrop']);
            $hotelSupplier = isset($getData['hotelSupplier']) ? $this->_HtmlPurifier->filter($getData['hotelSupplier']) : '';
            $hotelSupplierSysId = isset($getData['hotelSupplierSysId']) ? $this->_HtmlPurifier->filter($getData['hotelSupplierSysId']) : '';

            $eventType = isset($getData['eventType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['eventType'])) : '';
            $title = '';
            if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
                //update booking info
                $ObjAccom = new Travel_Model_CRM_CustomerTravelPlanAccomFullfillment();
                $where = "TPIntSysId = " . $tpid . " AND SeqId=" . $seqid . " AND AccoSysId=" . $aid;
                if ($is_hotelbookingconfirmed == 'false') {
                    //$HconfirmNo='';
                }
                $date = date('Y-m-d H:i:s');
                if ($hotelbookingconfirmed == 1) {
                    $statusId = 57;
                } else {
                    $statusId = 60;
                }
                if ($eventType == 'roomreadymade') {

                    $hotelcustomerremark = isset($getData['hotelcustomerremark']) ? $this->_HtmlPurifier->filter($getData['hotelcustomerremark']) : '';
                    $InternalRemark = $hotelremarks;
                    $pickupndrop = $this->_HtmlPurifier->filter($getData['pickupndrop']);
                    $vehiclepickuplocation_going_from = isset($getData['vehiclepickuplocation_going_from']) ? $this->_HtmlPurifier->filter($getData['vehiclepickuplocation_going_from']) : '';
                    $pickuplocation = isset($getData['pickuplocation']) ? $this->_HtmlPurifier->filter($getData['pickuplocation']) : '';
                    $pickupotherlocation = isset($getData['pickupotherlocation']) ? $this->_HtmlPurifier->filter($getData['pickupotherlocation']) : '';
                    $pickupremark = isset($getData['pickupremark']) ? $this->_HtmlPurifier->filter($getData['pickupremark']) : '';
                    $hoteltitle = isset($getData['hoteltitle']) ? $this->_HtmlPurifier->filter($getData['hoteltitle']) : '';
                    $hotelcontactname = isset($getData['hotelcontactname']) ? $this->_HtmlPurifier->filter($getData['hotelcontactname']) : '';
                    $hotelprimarycontact = isset($getData['hotelprimarycontact']) ? $this->_HtmlPurifier->filter($getData['hotelprimarycontact']) : '';
                    $hoteladdress = isset($getData['hoteladdress']) ? $this->_HtmlPurifier->filter($getData['hoteladdress']) : '';
                    if ($vehiclepickuplocation_going_from != '') {
                        $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                        $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];
                    }
                    $userArray = array(
                        'AccoBookingId' => $HconfirmNo,
                        'CustomerRemark' => $hotelcustomerremark,
                        'InternalRemark' => $InternalRemark,
                        'HotelName' => addslashes($hoteltitle),
                        'HotelPrimaryContact' => $hotelprimarycontact,
                        'HotelContactName' => $hotelcontactname,
                        'HotelAddress' => $hoteladdress,
                        'IsPickUp' => $pickupndrop,
                        'PickUpCitySysId' => $vehiclepickuplocation_going_from,
                        'PickUpLocation' => $pickuplocation,
                        'PickUpOtherLocationName' => $pickupotherlocation,
                        'PickUpRemarks' => $pickupremark,
                        'XRefBookingId' => $SconfirmNo,
                        'IsHotelConfirmed' => $hotelbookingconfirmed,
                        'StatusSysId' => $statusId,
                        'UpdateDate' => $date,
                    );
                } else {
                    $userArray = array(
                        'AccoBookingId' => $HconfirmNo,
                        'XRefBookingId' => $SconfirmNo,
                        'SupplierPickUpTotalCost' => $hotelsupplierpickuptotalcost,
                        'SupplierPickUpFinalCost' => $hotelsupplierpickupfinalcost,
                        'IsHotelConfirmed' => $hotelbookingconfirmed,
                        'StatusSysId' => $statusId,
                        'UpdateDate' => $date,
                    );
                }

                //echo "<pre>";print_r($userArray);
                $Rcord = $ObjAccom->UpdateTravelPlanAccom($userArray, $where);
                //#end of update booking info
                //update status
                $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
                //echo "<pre>";print_r($checkRecordExist);

                $date = date('Y-m-d H:i:s');
                if (!empty($checkRecordExist)) {
                    $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                    $userArray = array(
                        'StatusSysId' => $statusId,
                        'SupplierSysId' => isset($hotelSupplierSysId) ? $hotelSupplierSysId : 0,
                        'OnCallSupRemarks' => $hotelremarks,
                        'EmailText' => $emailText,
                        'UpdatedOn' => $date,
                    );
                    $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
                } else {
                    $objPackage = new Travel_Model_TblPackage();
                    $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                    //echo "<pre>";print_r($flexiPackageItenList);	
                    $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                    $userArray = array(
                        'TPSysId' => $TPSysId,
                        'TPIntSysId' => $TPIntSysId,
                        'SupplierSysId' => isset($hotelSupplierSysId) ? $hotelSupplierSysId : 0,
                        'ItemSysId' => $aid,
                        'IsSupAvalOnCall' => 0,
                        'OnCallSupRateValidTill' => '',
                        'OnCallSupRemarks' => '',
                        'StatusSysId' => $statusId,
                        'CreatedOn' => $date,
                        'UpdatedOn' => $date,
                        'IsActive' => 1,
                        'AgencySysId' => $agencysysID,
                        'IsSupAvalOnCall' => '',
                        'OnCallSupRate' => 0,
                        'OnCallSupRooms' => 0,
                        'OnCallSupRateFrom' => $date,
                        'OnCallSupRateTo' => $date,
                        'OnCallSupRateValidTill' => $date,
                        'OnCallSupRemarks' => $hotelremarks,
                        //'EmailText' => $emailText,
                        'IsMarkForDel' => 0
                    );
                    //echo "<pre>";print_r($userArray);
                    $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
                }
                $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
                //echo $statusId;
                $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
                //print_r($statusArray);
                $title = $statusArray;
                //# update status 

                $msg = "success";
            } else {
                $msg = "failed";
            }
        }
        echo json_encode(array('status' => $msg, 'title' => stripslashes($title), 'aid' => stripslashes($aid)));
        exit;
    }

    //update status for activity/sighseeing created by Er Amit Kumar Dubey on 04-july-2017 at 5:10 PM
    public function updateAllItenStsForReadyMadeAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $data = json_decode($this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('allItenary'))), 1);
        $emailText = $this->_HtmlPurifier->filter($this->getRequest()->getParam('bookEnquiryEmail'));
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('hotelTPSysId')));
        //echo "<pre>";print_r($allData);die;
        $emailId = $this->_HtmlPurifier->filter($this->getRequest()->getParam('readymadeSupplierEmailId'));
        $readymadeSupplierName = $this->_HtmlPurifier->filter($this->getRequest()->getParam('readymadeSupplierName'));
        $hotelbookingconfirmed = $this->getRequest()->getParam('hotelbookingconfirmed') ? $this->_HtmlPurifier->filter($this->getRequest()->getParam('hotelbookingconfirmed')) : '';
        $BookingOnHoldDate = (null !== $this->getRequest()->getParam('BookingOnHoldDate')) ? $this->getRequest()->getParam('BookingOnHoldDate') : '';

        $title = '';
        $bodyText = $this->getRequest()->getParam('details');
        if (isset($data) && !empty($data) && count($data) > 0) {
            //$where = "TPSysId = ". $TPSysId;
            //echo "<pre>";print_r($data);die;
            $statusId = 55;
            $date = date('Y-m-d H:i:s');
            if (!empty($data)) {/*
              $supplierOnCallObj=new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
              $objPackage  = new Travel_Model_TblPackage();
              $flexiPackageItenList = $objPackage->getCustPackageItenList(base64_decode($data[0]['TPSysId']));
              foreach($data as $key=>$value){
              $TPSysId=base64_decode($value['TPSysId']);
              $TPIntSysId=isset($value['TPIntSysId'])?base64_decode($value['TPIntSysId']):0;
              $aid=base64_decode($value['aid']);
              //save /update data in supplier call table for all itenary
              $checkRecordExist=$supplierOnCallObj->ChkRecordExist($TPSysId,$aid);
              if(count($checkRecordExist)>0){
              $where = "ReqSupplierOnCall = ". $checkRecordExist[0]['ReqSupplierOnCall'];
              $userArray = array(
              'StatusSysId' => $statusId,
              'UpdatedOn' => $date,
              );
              $Rcord  = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray,$where);
              }else{
              $TPIntSysId=isset($TPIntSysId)?$TPIntSysId:$flexiPackageItenList[0]['TPIntSysId'];
              $userArray = array(
              'TPSysId'=>$TPSysId,
              'TPIntSysId'=>$TPIntSysId,
              'SupplierSysId'=>isset($suppId)?$suppId:0,
              'ItemSysId'=>$aid,
              'StatusSysId' => $statusId,
              'CreatedOn' => $date,
              'UpdatedOn' => $date,
              'IsActive' => 1,
              'AgencySysId' =>$agencysysID,
              'IsSupAvalOnCall' => '',
              'OnCallSupRate' => 0,
              'OnCallSupRooms' => 0,
              'OnCallSupRateFrom' => $date,
              'OnCallSupRateTo' => $date,
              'OnCallSupRateValidTill'=>$date,
              'OnCallSupRemarks'=>'',
              'IsMarkForDel' => 0
              );
              $Rcord  = $supplierOnCallObj->addReqSupplierOnCall($userArray);
              }
              //#end of save/update supplier call

              }
             */
            }

            $objPackage = new Travel_Model_TblPackage();
            $flexiPackageList = $objPackage->getCustPackageList($TPSysId);
            //echo "<pre>";print_r($flexiPackageList['DestinationPlaces']);
            $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
            $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
            $title = $statusArray;

            //send email to supplier
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($agencysysID);
            $agentDetails = $this->_crmcustomerObj->getAgentDetailById($AgentSysId);
            $sessionLogin_agnet_details = new Zend_Session_Namespace('sessionLogin_user');
            //print_r($agentDetails);die;
            $agentemail = trim($sessionLogin_agnet_details->EmailId);
            $cc = $agentemail;
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
            // render view
            $html->assign('type', 'sendReadymadeEnquiryDetail');
            $html->assign('emailText', $emailText);
            $html->assign('readymadeSupplierName', $readymadeSupplierName);
            $html->assign('agentDetails', $agentDetails);
            $html->assign('agencyDetails', $getAgencyDetail);
            $bodyText = $html->render('ajax-html.phtml');
            $emailId = trim($emailId);
            $AgencyName = trim($getAgencyDetail['DisplayName']) ? $getAgencyDetail['DisplayName'] : $getAgencyDetail['Title'];
            //$content = '/<div class="some-class"><\/div>/':
            //echo "<pre>";print_r($matches[0][0]);die;
            if ($hotelbookingconfirmed == 1) { //1 for booking confirmation
                preg_match_all("/<span class=\"packagebookingintimation\">([^`]*?)<\/span>/", $bodyText, $matches1);
                preg_match_all("/<span class=\"packagebookinghold\">([^`]*?)<\/span>/", $bodyText, $matches2);
                $bodyText = str_replace($matches1[0][0], '', $bodyText);
                $bodyText = str_replace($matches2[0][0], '', $bodyText);
                $subject = "Booking Confirmation request from " . $AgencyName;
            } else if ($hotelbookingconfirmed == 2) { //2 for booking negotiation
                preg_match_all("/<span class=\"packagebookingconfirmed\">([^`]*?)<\/span>/", $bodyText, $matches1);
                preg_match_all("/<span class=\"packagebookinghold\">([^`]*?)<\/span>/", $bodyText, $matches2);
                $bodyText = str_replace($matches1[0][0], '', $bodyText);
                $bodyText = str_replace($matches2[0][0], '', $bodyText);

                $subject = "Booking detail for  " . trim(stripslashes($flexiPackageList['DestinationPlaces'])) . " – Rates required from " . $AgencyName;
            } else if ($hotelbookingconfirmed == 0) { // 0 for booking on hold
                $fullfillmentObj = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
                $whereFullfillmentData = "TPSysId = " . $TPSysId;

                $BookingOnHoldDateRes = '';
                if ($BookingOnHoldDate) {
                    $BookingOnHoldDate_exp_date = explode(" ", $BookingOnHoldDate);
                    $BookingOnHoldDate_exp_date_data = explode("/", $BookingOnHoldDate_exp_date[0]);
                    if ($BookingOnHoldDate_exp_date[0] != '') {
                        $BookingOnHoldDateRes = $BookingOnHoldDate_exp_date_data[2] . "-" . $BookingOnHoldDate_exp_date_data[1] . "-" . $BookingOnHoldDate_exp_date_data[0] . " " . $BookingOnHoldDate_exp_date[1];
                        $userArray = array(
                            'BookingOnHoldDate' => $BookingOnHoldDateRes,
                            'UpdatedDate' => $date
                        );

                        $Rcord = $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray, $whereFullfillmentData);
                    }
                }

                preg_match_all("/<span class=\"packagebookingconfirmed\">([^`]*?)<\/span>/", $bodyText, $matches1);
                preg_match_all("/<span class=\"packagebookingintimation\">([^`]*?)<\/span>/", $bodyText, $matches2);
                preg_match_all("/<span class=\"onholddate\">([^`]*?)<\/span>/", $bodyText, $matches3);
                $bodyText = str_replace($matches1[0][0], '', $bodyText);
                $bodyText = str_replace($matches2[0][0], '', $bodyText);
                $bodyText = str_replace($matches3[0][0], $BookingOnHoldDate, $bodyText);
                $subject = "Rate holding request from " . $AgencyName;
            } else {
                $subject = "Package Enquiry Details";
            }
            $emailId = 'amit@catpl.co.in';
            $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => $subject . '-' . $TPSysId, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
            try {
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => base64_decode($data[0]['TPSysId']),
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $agencysysID,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                $this->mailSentByElastice($emailData, $arrEmailStatistics);
                //echo 'Email has sent to customer';
            } catch (Exception $err) {
                print_r($err, true);
            }
            //#end of send email
            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => $title));
        exit;
    }

    //add/update pax information created by Er Amit Kumar Dubey on 10-july-2017 at 12:53 PM
    public function updateRelationAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $mid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('mid')));
        $cid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('cid')));
        $salutation = $this->_HtmlPurifier->filter($this->getRequest()->getParam('salutation'));
        $paxtype = $this->_HtmlPurifier->filter($this->getRequest()->getParam('paxtype'));
        $firstName = $this->_HtmlPurifier->filter($this->getRequest()->getParam('firstname'));
        $emailid = $this->_HtmlPurifier->filter($this->getRequest()->getParam('emailid'));
        $lastName = $this->_HtmlPurifier->filter($this->getRequest()->getParam('lastname'));
        $dob = $this->_HtmlPurifier->filter($this->getRequest()->getParam('dob'));
        $dob = explode('/', $dob);
        $dob = $dob[2] . "-" . $dob[1] . "-" . $dob[0];
        $passportnumber = $this->_HtmlPurifier->filter($this->getRequest()->getParam('passportnumber'));
        if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
            $date = date('Y-m-d H:i:s');
            $this->_travelPaxObj = new Travel_Model_CRM_CustomerTravelPlanPax();
            $arrCustMemUpdate = array(
                'Relation' => trim($paxtype),
                'FirstName' => trim($firstName),
                'LastName' => trim($lastName),
                'Title' => trim($salutation),
                'PassportNo' => trim($passportnumber),
                'DOB' => trim($dob),
                'UpdateDate' => $date,
            );
            $whereMember = "MemberSysId = " . $mid;
            //echo "<pre>";print_r($arrCustMemUpdate);die;
            $this->_agencycustomermemberObj = new Travel_Model_CRM_CustomerMember();
            $MemberSysId = $this->_agencycustomermemberObj->updateCustomerMember($arrCustMemUpdate, $whereMember);
            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => ''));
        exit;
    }

    public function readymadeVoucherAction() {
        $this->view->layout()->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $objPackage = new Travel_Model_TblPackage();
        $flexiPackageList = $objPackage->getCustPackageList($TPSysId);
        if ($AgencySysId != $flexiPackageList['AgencySysId']) {
            //$this->_redirect('publicpackage/pagenotfound');
            //exit;
        }
        //print_r($flexiPackageList);
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
        $agencyObj = new Travel_Model_TblAgency();
        $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
        $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);

        //echo "<pre>".print_r($getAgentDetail);die;
        $flexiPackageList['agencyDetails'] = $getAgencyDetail;
        $flexiPackageList['agentDetails'] = $getAgentDetail;
        $this->view->flexiPackageList = $flexiPackageList;
        $this->view->flexiPackageItenList = $flexiPackageItenList;
    }

    public function readymadeInvoiceAction() {
        $this->view->layout()->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $objPackage = new Travel_Model_TblPackage();
        $flexiPackageList = $objPackage->getCustPackageList($TPSysId);
        if ($AgencySysId != $flexiPackageList['AgencySysId']) {
            //$this->_redirect('publicpackage/pagenotfound');
            //exit;
        }
        //print_r($flexiPackageList);
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
        $agencyObj = new Travel_Model_TblAgency();
        $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
        $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);

        //echo "<pre>".print_r($getAgentDetail);die;
        $flexiPackageList['agencyDetails'] = $getAgencyDetail;
        $flexiPackageList['agentDetails'] = $getAgentDetail;
        $this->view->flexiPackageList = $flexiPackageList;
        $this->view->flexiPackageItenList = $flexiPackageItenList;
    }

    public function updateOptionalSightSeeingDynamicCustomerAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $sightseeingID = $this->getRequest()->getPost('sightseeingID');
        $tpintsysID = @$this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $itenArr = $this->getRequest()->getPost('itenArr');
        $txt = $this->getRequest()->getPost('txt');
        $catID = $this->getRequest()->getPost('catID');
        $tourID = $this->_request->getParam('tourID');
        $viewType = $this->getRequest()->getPost('viewType');
        $tripStartdate = $this->_request->getParam('tripstartdate');
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', $tripStartdate)));
        $mID = $this->getRequest()->getPost('mID');
        $IsB2BAgent = $this->getRequest()->getPost('IsB2BAgent');
        $MarketPlaceId = ($IsB2BAgent == 1) ? 2 : 1;
        if ($viewType == 'pkgView') {
            $seqence = $this->getRequest()->getPost('seqence');
            $objPackage = new Travel_Model_TblPackage();
            $getitnIDs = $objPackage->GetItnBySeq($seqence, $tpsysID);
            foreach ($getitnIDs as $getitnID) {
                $tpintsysID[] = $getitnID['TPIntSysId'];
            }
        }
        $this->_crmcusttravelplan->UpdateOptionalSSBYO($sightseeingID, $tpintsysID, $tpsysID, $roominfojson, $txt, $itenArr, $catID, $tourID, $mID, $tripstartdate, $MarketPlaceId);
    }

    public function updateOptionalActivityDynamicCustomerAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $actID = $this->getRequest()->getPost('actID');
        $tpintsysID = @$this->getRequest()->getPost('tpintsysID');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $itenArr = $this->getRequest()->getPost('itenArr');
        $txt = $this->getRequest()->getPost('txt');
        $catID = $this->getRequest()->getPost('catID');
        $tourID = $this->_request->getParam('tourID');
        $viewType = $this->getRequest()->getPost('viewType');
        $IsB2BAgent = $this->getRequest()->getPost('IsB2BAgent');
        $MarketPlaceId = ($IsB2BAgent == 1) ? 2 : 1;
        $tripStartdate = $this->_request->getParam('tripstartdate');
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', $tripStartdate)));
        $mID = $this->getRequest()->getPost('mID');
        if ($viewType == 'pkgView') {
            $seqence = $this->getRequest()->getPost('seqence');
            $objPackage = new Travel_Model_TblPackage();
            $getitnIDs = $objPackage->GetItnBySeq($seqence, $tpsysID);
            foreach ($getitnIDs as $getitnID) {
                $tpintsysID[] = $getitnID['TPIntSysId'];
            }
        }
        $this->_crmcusttravelplan->UpdateOptionalBYOActivity($actID, $tpintsysID, $tpsysID, $roominfojson, $txt, $itenArr, $catID, $tourID, $mID, $tripstartdate, $MarketPlaceId);
    }

    public function changeHotelByoAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        //        print_r($_REQUEST); 
        //        $AccoSysId = $this->getRequest()->getPost('AccoSysId');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        //$travelPlanDetails=$this->_crmcusttravelplan->GetTravelPlanType($tpsysID);
        $catID = $this->getRequest()->getPost('catID');
        $itenArr = $this->getRequest()->getPost('itenArr');
        $tourID = $this->_request->getParam('tourID');
        $tripStartdate = $this->_request->getParam('tripstartdate');
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', $tripStartdate)));
        $tpintsysID = @$this->getRequest()->getPost('TPIntSysId');
        $InvnItemSysId = $this->getRequest()->getPost('InvnItemSysId');
        $IsB2BAgent = $this->getRequest()->getPost('IsB2BAgent');
        $MarketPlaceId = ($IsB2BAgent == 1) ? 2 : 1;
        $mID = $this->getRequest()->getPost('mID');
        $viewType = $this->getRequest()->getPost('viewType');
        if ($viewType == 'pkgView') {
            $seqence = $this->getRequest()->getPost('seqence');
            $objPackage = new Travel_Model_TblPackage();
            $getitnIDs = $objPackage->GetItnBySeq($seqence, $tpsysID);
            foreach ($getitnIDs as $getitnID) {
                $tpintsysID[] = $getitnID['TPIntSysId'];
            }
            //        $tpintsysID = $getitnID[1]['TPIntSysId'];
        }
        $this->_crmcusttravelplan->UpdateHotelSelectionBYO($tpintsysID, $tpsysID, $roominfojson, $catID, $itenArr, $tourID, $InvnItemSysId, $mID, $tripstartdate, $MarketPlaceId);
    }

    public function updatetranstypeAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->getRequest()->getPost('tpsysID');
        $roominfojson = $this->getRequest()->getPost('roominfojson');
        $checkedvals = $this->getRequest()->getPost('checkedVals');
        $catID = $this->getRequest()->getPost('catID');
        $transtype = $this->getRequest()->getPost('transtype');
        $tpintsysID = $this->getRequest()->getPost('tpintsysID');
        $itenArr = $this->getRequest()->getPost('itenArr');
        $tourID = $this->_request->getParam('tourID');
        $viewType = $this->getRequest()->getPost('viewType');
        $mID = $this->getRequest()->getPost('mID');
        $tripStartdate = $this->_request->getParam('tripstartdate');
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', $tripStartdate)));
        $IsB2BAgent = $this->getRequest()->getPost('IsB2BAgent');
        $MarketPlaceId = ($IsB2BAgent == 1) ? 2 : 1;
        if ($viewType == 'pkgView') {
            //        $seqence = $this->getRequest()->getPost('seqence');
            $travelpanitenaryArr = json_decode(base64_decode($itenArr), 1);
            $tpintsysID = $travelpanitenaryArr[$seqence];
        }
        $this->_crmcusttravelplan->UpdateTransportType($tpsysID, $roominfojson, $checkedvals, $catID, $transtype, $tpintsysID, $itenArr, $tourID, $mID, $tripstartdate, $MarketPlaceId);
    }

    public function addIncludedServiceAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $objPackage = new Travel_Model_TblPackage();
        $front->setParam('noViewRenderer', true);
        $tpsysID = $this->_request->getParam('tpsysID');
        $checkedvals = $this->_request->getParam('checkedVals');
        $catID = $this->_request->getParam('catID');
        $itenArr = $this->getRequest()->getPost('itenArr');
        $roominfojsonE = $this->_request->getParam('roominfojson');
        $tourID = $this->_request->getParam('tourID');
        $mID = $this->getRequest()->getPost('mID');
        $tripStartdate = $this->_request->getParam('tripstartdate');
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', $tripStartdate)));
        $IsB2BAgent = $this->getRequest()->getPost('IsB2BAgent');
        $MarketPlaceId = ($IsB2BAgent == 1) ? 2 : 1;

        //        echo '<pre>';print_r($_REQUEST);echo '</pre>';
        //        $viewType = $this->getRequest()->getPost('viewType');
        //        if($viewType == 'pkgView'){
        //        $seqence = $this->getRequest()->getPost('seqence');
        //        $travelpanitenaryArr = json_decode(base64_decode($itenArr),1);
        //        $tpintsysID = $travelpanitenaryArr[$seqence];
        //        }
        $updatedData1 = array(
            'IsCostInclInTP' => 0,
        );
        $whereclause1 = array('TPIntSysId = ? ' => $tpsysID, 'IsOptionalServices != ?' => 1);
        $updateservicedetails = $objPackage->updateData('TB_Agency_Customer_TravelPlan_OtherServices', $updatedData1, $whereclause1);
        for ($j = 0; $j < count($checkedvals); $j++) {
            $updatedData = array(
                'IsCostInclInTP' => 1,
            );
            $whereclause = array('TPIntSysId = ? ' => $tpsysID, 'OtherSrvSysId = ? ' => @$checkedvals[$j]);
            $updateprice = $objPackage->updateData('TB_Agency_Customer_TravelPlan_OtherServices', $updatedData, $whereclause);
        }

        $roominfo = base64_decode($roominfojsonE);
        echo Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfo, $tpsysID, $catID, $tourID, $mID, $tripstartdate, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);
        //       echo $this->_crmcusttravelplan->UpdateBYOPackagePrice($tpsysID, $roominfojsonE, $itenArr,$catID,$tourID,$mID);
    }

    public function changePackageHotelByoReadymadeAction() {
        /* Disable Layout */
        // ini_set('display_errors',0);
        $this->_helper->layout->disableLayout();
        $tpintsysId = $this->_request->getParam('itnID');
        $tpintsysId = $this->_request->getParam('itnID');
        $tpsysID = $this->_request->getParam('tpsysID');
        $this->view->tourID = $this->_request->getParam('tourID');
    }

    public function getcardetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $tpsysID = $this->_request->getParam('tpsysID');
        if ($tpsysID > 0) {
            $this->view->tpsysID = $tpsysID;
            $this->view->transtype = $this->_request->getParam('transtype');
            $this->view->tpintsysID = $this->_request->getParam('tpintsysID');
            $this->view->pkgprice = $this->_request->getParam('pkgprice');
            $this->view->roominfojson = $this->_request->getParam('roominfojson');
            $this->view->itenArr = $this->getRequest()->getPost('itenArr');
            $this->view->catID = $this->_request->getParam('catID');
            $this->view->tourID = $tourID = $this->_request->getParam('tourID');
            $this->view->markuptype = $this->_request->getParam('markuptype');
            $this->view->markupvalue = $this->_request->getParam('markupvalue');
            $this->view->mID = $this->_request->getParam('mID');
            $this->view->getallcartype = $this->_crmcusttravelplan->GetAllCarDetails($tpsysID, $tourID);
            $this->view->getselectedprice = $this->_crmcusttravelplan->GetSelectedCarVehiclePrice($tpsysID, $tourID);
        }
    }

    public function gettraindetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $tpsysID = $this->_request->getParam('tpsysID');
        if ($tpsysID > 0) {
            $this->view->tpsysID = $tpsysID;
            $this->view->transtype = $this->_request->getParam('transtype');
            $this->view->tpintsysID = $this->_request->getParam('tpintsysID');
            $this->view->pkgprice = $this->_request->getParam('pkgprice');
            $this->view->tourID = $this->_request->getParam('tourID');
            $this->view->getalltraintype = $this->_crmcusttravelplan->GetVehicleDetailsByDay($tpsysID, 'train');
            $this->view->getselectedprice = $this->_crmcusttravelplan->GetSelectedVehiclePrice($tpsysID, 'train');
        }
    }

    public function getbusdetailsAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $tpsysID = $this->_request->getParam('tpsysID');
        if ($tpsysID > 0) {
            $this->view->tpsysID = $tpsysID;
            $this->view->transtype = $this->_request->getParam('transtype');
            $this->view->tpintsysID = $this->_request->getParam('tpintsysID');
            $this->view->pkgprice = $this->_request->getParam('pkgprice');
            $this->view->tourID = $this->_request->getParam('tourID');
            $this->view->getallbustype = $this->_crmcusttravelplan->GetVehicleDetailsByDay($tpsysID, 'bus');
            $this->view->getselectedprice = $this->_crmcusttravelplan->GetSelectedVehiclePrice($tpsysID, 'bus');
        }
    }

    public function getallserviceAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        $tpsysID = $this->_request->getParam('tpsysID');
        if ($tpsysID > 0) {
            $this->view->tpsysID = $tpsysID;
            $this->view->catID = $this->_request->getParam('catID');
            $this->view->tourID = $this->_request->getParam('tourID');
            $this->view->totalprice = $this->_request->getParam('totalprice');
            $this->view->roominfojson = $this->_request->getParam('roominfojson');
            $this->view->mID = $this->_request->getParam('mID');
            $this->view->itenArr = $this->getRequest()->getPost('itenArr');
            $this->view->getallservice = $this->_crmcusttravelplan->GetAllService($tpsysID);
            $this->view->getselectedprice = $this->_crmcusttravelplan->GetSelectedOtherService($tpsysID);
        }
    }

    //update status for hotel/activity/sighseeing created by Er Amit Kumar Dubey on 08-august-2017 at 03:49 PM
    public function updateItenStsForDynamicAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $type = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('type')));
        $TPSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('pid')));
        $tpid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('tpid')));
        $aid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('aid')));
        $price = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('price')));
        $InvnItemSysId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('invid')));
        $hotelrateoffered = $this->_HtmlPurifier->filter($this->getRequest()->getParam('hotelrateoffered'));
        $isrequesttobook = $this->_HtmlPurifier->filter($this->getRequest()->getParam('isrequesttobook'));
        $isrequesttohold = $this->_HtmlPurifier->filter($this->getRequest()->getParam('isrequesttohold'));

        $suppId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('suppId')));
        $sid = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('sid')));
        $emailText = $this->_HtmlPurifier->filter($this->getRequest()->getParam('emailText'));
        $suppId = ($suppId != '') ? $suppId : $sid;
        $allData = json_decode($this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('Hdetails'))), 1);
        $roominfojson = $allData['roominfojson'];
        $departuredate = '';
        $returndate = '';
        $price = 0;
        if (!empty($roominfojson)) {
            $departuredate = $this->getRequest()->getParam('fromdate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('fromdate'))) : '';
            $returndate = $this->getRequest()->getParam('todate') ? base64_decode($this->_HtmlPurifier->filter($this->getRequest()->getParam('todate'))) : '';

            //$departuredate=explode('/',$roominfojson[1]['departuredate']);
            //$departuredate=$departuredate[2].'-'.$departuredate[1].'-'.$departuredate[0];
            //$returndate=explode('/',$roominfojson[1]['returndate']);
            //$returndate=$returndate[2].'-'.$returndate[1].'-'.$returndate[0];
        }
        //echo "<pre>";print_r($allData);die;
        $emailId = $this->_HtmlPurifier->filter($this->getRequest()->getParam('emailId'));
        $title = '';
        $pkgSupplierDetails = array();
        if (isset($type) && !empty($type) && trim($type) == 'hotel') {
            //$where = "TPSysId = ". $TPSysId;
            //echo "<pre>";print_r($data);die;
            $date = date('Y-m-d H:i:s');
            $objAccomHotel = new Travel_Model_CRM_CustomerTravelPlan();
            $hotelPriceDetails = $objAccomHotel->getHotelDetailsByAccomIdFullfillment($aid, $tpid);
            //print_r($hotelPriceDetails);die;
            $price = $hotelPriceDetails[0]['NetCost'];
            //update status
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
            $statusId = 55;
            $date = date('Y-m-d H:i:s');
            $AccomdataArray = array(
                'RateOffered' => $hotelrateoffered,
                'IsRequestToBook' => $isrequesttobook ? $isrequesttobook : 0,
                'IsRequestToHold' => $isrequesttohold ? $isrequesttohold : 0,
                'UpdateDate' => $date,
            );
            $whereAccom = "TPIntSysId = " . $tpid . " AND AccoSysId = " . $aid . " AND InvnItemSysId = " . $InvnItemSysId;
            $updateAccomData = $supplierOnCallObj->updateData('TB_Agency_Customer_TravelPlan_Accom_Fullfillment', $AccomdataArray, $whereAccom);
            if (!empty($checkRecordExist)) {
                $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                $userArray = array(
                    'StatusSysId' => $statusId,
                    'EmailText' => $emailText,
                    'UpdatedOn' => $date,
                );
                $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
            } else {
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                //echo "<pre>";print_r($flexiPackageItenList);	
                $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'TPIntSysId' => $TPIntSysId,
                    'SupplierSysId' => isset($suppId) ? $suppId : 0,
                    'ItemSysId' => $aid,
                    'StatusSysId' => $statusId,
                    'IsSupAvalOnCall' => 0,
                    'OnCallSupRateFrom' => $departuredate,
                    'OnCallSupRateValidTill' => '',
                    'OnCallSupRemarks' => '',
                    'OnCallSupRateTo' => $returndate,
                    'OnCallSupRate' => $price,
                    'InvnItemSysId' => $InvnItemSysId,
                    'OnCallSupRooms' => count($roominfojson),
                    'CreatedOn' => $date,
                    'UpdatedOn' => $date,
                    'IsActive' => 1,
                    'AgencySysId' => $AgencySysId,
                    'IsMarkForDel' => 0,
                    'EmailText' => $emailText
                );
                //print_r($userArray);
                $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
            }
            $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
            $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
            //print_r($statusArray);
            $title = $statusArray;
            //# update status 
            //send email to supplier
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
            $sessionLogin_agnet_details = new Zend_Session_Namespace('sessionLogin_user');
            $cc = trim($getAgentDetail['EmailId']);
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
            // render view
            $html->assign('type', 'sendHotelDynamicEnquiryDetail');
            $html->assign('enquiryType', $type);
            if ((int) $suppId > 0) {
                $objSupplier = new Travel_Model_TblSupplier();
                $objSupplier->SupplierSysId = $suppId;
                $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
            }
            $html->assign('agencyDetails', $getAgencyDetail);
            $html->assign('agentDetails', $getAgentDetail);
            $html->assign('supplierDetails', $pkgSupplierDetails);
            //echo "<pre>";print_r($getAgentDetail);
            $html->assign('data', $allData);
            $html->assign('emailText', $emailText);
            $bodyText = $html->render('ajax-html.phtml');
            $emailId = trim($emailId);
            //$emailId='amit.k@catpl.co.in';
            $fromName = $this->fromName;
            $fromEmail = $this->fromEmail;
            $subject = 'Package Hotel Enquiry Details-' . $TPSysId;
            $emailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
            $emailData_Agent = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($getAgentDetail['EmailId'])), 'bodyHtml' => $bodyText, 'bodyText' => '');

            try {
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => $TPSysId,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                $this->mailSentByElastice($emailData, $arrEmailStatistics);
                $this->mailSentByElastice($emailData_Agent, $arrEmailStatistics, 0, 0);
                //insert data for sent email
                $dataArray = array(
                    "TPSysId" => $TPSysId,
                    "TPIntSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "SupplierSysId" => isset($suppId) ? $suppId : 0,
                    "InvnItemSysId" => $InvnItemSysId,
                    "ItemSysId" => $InvnItemSysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "EmailTextFromAgent" => $emailText,
                    "FromName" => $fromName,
                    "FromEmail" => $fromEmail,
                    "EmailTo" => $emailId,
                    "EmailSubject" => $subject,
                    "IsReplyFromSupplier" => 0,
                    "IsQueryConfirmed" => 0,
                    "EmailQueryType" => 2, // 2 for hotel
                    "PlanType" => 5, // for package
                    "IsActive" => 1,
                    "IsMarkForDelete" => 0,
                    "StatusSysId" => 0,
                    "CreatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss'),
                    "UpdatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                //print_r($dataArray);
                try {
                    $insertEmailData = $supplierOnCallObj->insertData('TB_Agency_Customer_SupplierEmail_Fullfillment', $dataArray);
                } catch (Exception $err) {
                    print_r($err, true);
                }
                //echo 'Email has sent to customer';
            } catch (Exception $err) {
                print_r($err, true);
            }
            //#end of send email
            $msg = "success";
        } else if (isset($type) && !empty($type) && trim($type) == 'activity') {
            $date = date('Y-m-d H:i:s');
            $price = 0;
            //update status
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
            $statusId = 55;
            $date = date('Y-m-d H:i:s');
            if (!empty($checkRecordExist)) {
                $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                $userArray = array(
                    'StatusSysId' => $statusId,
                    'EmailText' => $emailText,
                    'UpdatedOn' => $date,
                );
                $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
            } else {
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                //echo "<pre>";print_r($flexiPackageItenList);	
                $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'TPIntSysId' => $TPIntSysId,
                    'SupplierSysId' => isset($suppId) ? $suppId : 0,
                    'ItemSysId' => $aid,
                    'StatusSysId' => $statusId,
                    'IsSupAvalOnCall' => 0,
                    'OnCallSupRateFrom' => $departuredate,
                    'OnCallSupRateValidTill' => '',
                    'OnCallSupRemarks' => '',
                    'OnCallSupRateTo' => $returndate,
                    'OnCallSupRate' => $price,
                    'InvnItemSysId' => $InvnItemSysId,
                    'OnCallSupRooms' => count($roominfojson),
                    'CreatedOn' => $date,
                    'UpdatedOn' => $date,
                    'IsActive' => 1,
                    'AgencySysId' => $AgencySysId,
                    'IsMarkForDel' => 0,
                    'EmailText' => $emailText
                );
                //print_r($userArray);
                $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
            }
            $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
            $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
            //print_r($statusArray);
            $title = $statusArray;
            //# update status 
            //send email to supplier
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
            $sessionLogin_agnet_details = new Zend_Session_Namespace('sessionLogin_user');
            $cc = trim($getAgentDetail['EmailId']);
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
            // render view
            $html->assign('type', 'sendActivityDynamicEnquiryDetail');
            $html->assign('enquiryType', $type);
            if ((int) $suppId > 0) {
                $objSupplier = new Travel_Model_TblSupplier();
                $objSupplier->SupplierSysId = $suppId;
                $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
            }
            $html->assign('agencyDetails', $getAgencyDetail);
            $html->assign('agentDetails', $getAgentDetail);
            $html->assign('supplierDetails', $pkgSupplierDetails);
            //echo "<pre>";print_r($allData);
            $html->assign('data', $allData);
            $html->assign('emailText', $emailText);
            $bodyText = $html->render('ajax-html.phtml');
            $emailId = trim($emailId);
            //$emailId='amit.k@catpl.co.in';
            $fromName = $this->fromName;
            $fromEmail = $this->fromEmail;
            $subject = 'Package Activity Enquiry Details-' . $TPSysId;
            $emailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');

            try {
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => $TPSysId,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                $this->mailSentByElastice($emailData, $arrEmailStatistics);
                //insert data for sent email
                $dataArray = array(
                    "TPSysId" => $TPSysId,
                    "TPIntSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "SupplierSysId" => isset($suppId) ? $suppId : 0,
                    "InvnItemSysId" => $InvnItemSysId,
                    "ItemSysId" => $InvnItemSysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "EmailTextFromAgent" => $emailText,
                    "FromName" => $fromName,
                    "FromEmail" => $fromEmail,
                    "EmailTo" => $emailId,
                    "EmailSubject" => $subject,
                    "IsReplyFromSupplier" => 0,
                    "IsQueryConfirmed" => 0,
                    "EmailQueryType" => 8, // 8 for activity
                    "PlanType" => 5, // for package
                    "IsActive" => 1,
                    "IsMarkForDelete" => 0,
                    "StatusSysId" => 0,
                    "CreatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss'),
                    "UpdatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                //print_r($dataArray);
                try {
                    $insertEmailData = $supplierOnCallObj->insertData('TB_Agency_Customer_SupplierEmail_Fullfillment', $dataArray);
                } catch (Exception $err) {
                    print_r($err, true);
                }
                //echo 'Email has sent to customer';
            } catch (Exception $err) {
                print_r($err, true);
            }
            //#end of send email
            $msg = "success";
        } else if (isset($type) && !empty($type) && trim($type) == 'sightseeing') {
            $date = date('Y-m-d H:i:s');
            $price = 0;
            //update status
            $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
            $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
            $statusId = 55;
            $date = date('Y-m-d H:i:s');
            if (!empty($checkRecordExist)) {
                $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                $userArray = array(
                    'StatusSysId' => $statusId,
                    'EmailText' => $emailText,
                    'UpdatedOn' => $date,
                );
                $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
            } else {
                $objPackage = new Travel_Model_TblPackage();
                $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                //echo "<pre>";print_r($flexiPackageItenList);	
                $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'TPIntSysId' => $TPIntSysId,
                    'SupplierSysId' => isset($suppId) ? $suppId : 0,
                    'ItemSysId' => $aid,
                    'StatusSysId' => $statusId,
                    'IsSupAvalOnCall' => 0,
                    'OnCallSupRateFrom' => $departuredate,
                    'OnCallSupRateValidTill' => '',
                    'OnCallSupRemarks' => '',
                    'OnCallSupRateTo' => $returndate,
                    'OnCallSupRate' => $price,
                    'InvnItemSysId' => $InvnItemSysId,
                    'OnCallSupRooms' => count($roominfojson),
                    'CreatedOn' => $date,
                    'UpdatedOn' => $date,
                    'IsActive' => 1,
                    'AgencySysId' => $AgencySysId,
                    'IsMarkForDel' => 0,
                    'EmailText' => $emailText
                );
                //print_r($userArray);
                $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
            }
            $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
            $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
            //print_r($statusArray);
            $title = $statusArray;
            //# update status 
            //send email to supplier
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
            $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
            $sessionLogin_agnet_details = new Zend_Session_Namespace('sessionLogin_user');
            $cc = trim($getAgentDetail['EmailId']);
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
            // render view
            $html->assign('type', 'sendSightseeingDynamicEnquiryDetail');
            $html->assign('enquiryType', $type);
            if ((int) $suppId > 0) {
                $objSupplier = new Travel_Model_TblSupplier();
                $objSupplier->SupplierSysId = $suppId;
                $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
            }
            $html->assign('agencyDetails', $getAgencyDetail);
            $html->assign('agentDetails', $getAgentDetail);
            $html->assign('supplierDetails', $pkgSupplierDetails);
            //echo "<pre>";print_r($allData);
            $html->assign('data', $allData);
            $html->assign('emailText', $emailText);
            $bodyText = $html->render('ajax-html.phtml');
            $emailId = trim($emailId);
            //$emailId='amit.k@catpl.co.in';
            $fromName = $this->fromName;
            $fromEmail = $this->fromEmail;
            $subject = 'Package SightSeeing Enquiry Details-' . $TPSysId;
            $emailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');

            try {
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => $TPSysId,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                $this->mailSentByElastice($emailData, $arrEmailStatistics);
                //insert data for sent email
                $dataArray = array(
                    "TPSysId" => $TPSysId,
                    "TPIntSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $AgencySysId,
                    "SupplierSysId" => isset($suppId) ? $suppId : 0,
                    "InvnItemSysId" => $InvnItemSysId,
                    "ItemSysId" => $InvnItemSysId,
                    "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                    "EmailTextFromAgent" => $emailText,
                    "FromName" => $fromName,
                    "FromEmail" => $fromEmail,
                    "EmailTo" => $emailId,
                    "EmailSubject" => $subject,
                    "IsReplyFromSupplier" => 0,
                    "IsQueryConfirmed" => 0,
                    "EmailQueryType" => 9, // 9 for sightseeing
                    "PlanType" => 5, // for package
                    "IsActive" => 1,
                    "IsMarkForDelete" => 0,
                    "StatusSysId" => 0,
                    "CreatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss'),
                    "UpdatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                //print_r($dataArray);
                try {
                    $insertEmailData = $supplierOnCallObj->insertData('TB_Agency_Customer_SupplierEmail_Fullfillment', $dataArray);
                } catch (Exception $err) {
                    print_r($err, true);
                }
                //echo 'Email has sent to customer';
            } catch (Exception $err) {
                print_r($err, true);
            }
            //#end of send email
            $msg = "success";
        } else {
            $msg = "failed";
        }
        echo json_encode(array('status' => $msg, 'title' => $title));
        exit;
    }

    public function downloadCustomerFinalPackageAction() {
        $TPSysId = base64_decode($this->getRequest()->getParam('id'));

        /*       	$fdata = file_get_contents("data/package-b2b-" . $TPSysId.".txt");
          $record=json_decode($fdata,true);
          $html = new Zend_View();
          $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
          // render view
          $html->assign('type', 'downloadWordForB2BAgent');
          $html->assign('data', $record);
         */
        $existLeadDetail = $this->_crmcusttravelplan->CheckCustomerWithLeadId($TPSysId);
        $downloadCount = $existLeadDetail[0]['DownloadCount'] + 1;
        $where = "TPSysId = " . $TPSysId;
        $updatetravelplan = array(
            'DownloadCount' => $downloadCount,
            'StatusType' => 59,
            'UpdateDate' => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
        );
        $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplan, $where);
        //echo $bodyText = $html->render('download-word-document.phtml');
        //	echo "<pre>".print_r($record);
        //	echo "<pre>".print_r($bodyText);
        exit;
    }

    public function saveCustomerFinalPackageAction() {
        $queryHtml = urldecode($this->getRequest()->getParam('queryHtml'));
        $TPSysId = $this->getRequest()->getParam('id');
        $existLeadDetail = $this->_crmcusttravelplan->CheckCustomerWithLeadId($TPSysId);
        $downloadCount = $existLeadDetail[0]['DownloadCount'] + 1;
        $where = "TPSysId = " . $TPSysId;
        $updatetravelplan = array(
            'DownloadCount' => $downloadCount,
            'StatusType' => 59,
            'UpdateDate' => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
        );
        $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplan, $where);
        /* 			$fileName = "package-b2b-".$TPSysId. ".txt";
          $fp = fopen("data/" . $fileName, 'w');
          $data = date("Y-m-d H:i:s") . " - " . $queryHtml;
          fwrite($fp, $queryHtml);
          fclose($fp);




          $fdata = file_get_contents("data/package-b2b-" . $TPSysId.".txt");
          $record=json_decode($fdata,true);
          $html = new Zend_View();
          $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
          // render view
          $html->assign('type', 'downloadWordForB2BAgent');
          $html->assign('data', $record);
          $bodyText = $html->render('download-word-document.phtml');
         */



        echo json_encode(array('status' => 'success', 'TPSysId' => $updatetravelPlan));
        //#end write word html 
        exit;
    }

    public function updateTravelPlanAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        if ($this->getRequest()->isPost()) {
            $catID = $this->getRequest()->getPost('catID');
            $tourID = $this->getRequest()->getPost('tourID');
            $mID = $this->getRequest()->getPost('mID');
            $PackSpecType = $this->getRequest()->getPost('PackSpecType');
            $tpsysID = $this->getRequest()->getPost('packid');
            //            echo '<pre>ppp'; print_r($_REQUEST); echo '</pre>';die;
            if ($PackSpecType == 3) {
                $objDynamicPackage = new Travel_Model_DynamicPackage('Customer');
                $travelplanArray = $objDynamicPackage->getDynamicPackageDetail($tpsysID);
                $marketPlace = 1;
                if (isset($travelplanArray['IsB2BProposal']) && $travelplanArray['IsB2BProposal'] == 1) {
                    $marketPlace = 2;
                }
                Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->updateCalculatedCostInTravelPlan($travelplanArray, $tpsysID, $catID, $tourID, $mID, 'Customer', $marketPlace);
            }
        }
    }

    public function cronForAllTodoEmailAction() {
        $this->_crmcustomertodoObj = new Travel_Model_CRM_AgencyCustomerTodo();
        $tblAgencyStaffObj = new Travel_Model_TblAgencyStaff();
        $AgencyList = $tblAgencyStaffObj->getAgencyList(1); //1 for fetch only b2c agency list
        //$AgentList=$tblAgencyStaffObj->getAgencyUserList();
        $runningTime = (NULL !== $this->getRequest()->getParam('crontime')) ? trim($this->getRequest()->getParam('crontime')) : '';
        $sentemail = (NULL !== $this->getRequest()->getParam('sentemail')) ? trim($this->getRequest()->getParam('sentemail')) : 1;
        $AgencyAgentComb['Details'] = array();

        if (!empty($AgencyList)) {
            $g = 0;
            foreach ($AgencyList as $key1 => $value1) {
                $AgentList = $tblAgencyStaffObj->getAgencyUserList($value1['AgencySysId'], 1); //1 for fetch only b2c agent list
                //echo "<pre>";print_r($AgentList);
                if (!empty($AgentList)) {
                    $h = 0;
                    //echo '=================Start Agency : '.trim($value1['PrimaryEmail'])." Start=================<br/>";
                    foreach ($AgentList as $key => $value) {
                        $AgentSysId = $value['UserSysId'];
                        $AgencySysId = $value['AgencySysId'];
                        $AgentDetails['FirstName'] = trim(stripslashes($value['FirstName']));
                        $AgentDetails['LastName'] = trim(stripslashes($value['LastName']));
                        $agentemail = trim(stripslashes($value['EmailId']));
                        $allAgentsTodo = $this->_crmcustomertodoObj->GetAllPendingTodoEmail($AgentSysId);
                        //echo "<pre>";print_r($allAgentsTodo);

                        if (!empty($allAgentsTodo)) {
                            $AgencyAgentComb[$AgencySysId][$h] = $allAgentsTodo;

                            $html = new Zend_View();
                            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
                            // for($i=0;$i<count($allAgentsTodo);$i++){
                            //print_r($allAgentsTodo[$i]);
                            $html->assign('type', 'sendPendingTodoEmail');
                            $html->assign('data', $allAgentsTodo);
                            $html->assign('userType', 'AGENT');
                            $html->assign('runningTime', $runningTime);
                            $html->assign('AgentDetails', $AgentDetails);
                            echo $bodyText = $html->render('ajax-html.phtml');

                            $emailId = trim($agentemail);
                            //$emailId = "prashant@catpl.co.in";
                            $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => 'CRM - ' . $AgentDetails['FirstName'] . ' Follow up and to do list for today!', 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                            try {
                                // Added By Pardeep Panchal For Email Count...
                                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                                $arrEmailStatistics = array(
                                    "TPSysId" => '',
                                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                                    "AgencySysId" => $AgencySysId,
                                    "AgentSysId" => $AgentSysId,
                                    "Title" => $bodyText,
                                    "Source" => $arrEmailStatisticsType[2], // 1 For Fresh Proposals
                                    "Status" => 0,
                                    "RefSysId" => "",
                                    "RefSysStatus" => "",
                                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                                );

                                // Added By Pardeep Panchal For Email Count Ends...

                                if ($sentemail == 1) {
                                    //$this->mailSentByElastice($emailData,$arrEmailStatistics);
                                    echo 'Email has sent to Agent : ' . $emailId . "<br/>";
                                } else {
                                    echo 'Email Not sent to Agent : ' . $emailId . "<br/>";
                                }
                            } catch (Exception $err) {
                                print_r($err, true);
                            }
                            //}
                        } else {
                            $html = new Zend_View();
                            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
                            // for($i=0;$i<count($allAgentsTodo);$i++){
                            //print_r($allAgentsTodo[$i]);
                            $html->assign('type', 'sendPendingTodoEmail');
                            $html->assign('data', array());
                            $html->assign('userType', 'AGENT');
                            $html->assign('runningTime', $runningTime);
                            $html->assign('AgentDetails', $AgentDetails);
                            echo $bodyText = $html->render('ajax-html.phtml');

                            $emailId = trim($agentemail);
                            //$emailId = "prashant@catpl.co.in";
                            $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => 'CRM - ' . $AgentDetails['FirstName'] . ' Follow up and to do list for today!', 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                            try {
                                // Added By Pardeep Panchal For Email Count...
                                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                                $arrEmailStatistics = array(
                                    "TPSysId" => '',
                                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                                    "AgencySysId" => $AgencySysId,
                                    "AgentSysId" => $AgentSysId,
                                    "Title" => $bodyText,
                                    "Source" => $arrEmailStatisticsType[2], // 1 For Fresh Proposals
                                    "Status" => 0,
                                    "RefSysId" => "",
                                    "RefSysStatus" => "",
                                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                                );

                                // Added By Pardeep Panchal For Email Count Ends...

                                if ($sentemail == 1) {
                                    //$this->mailSentByElastice($emailData,$arrEmailStatistics);
                                    echo 'Email has sent to Agent without todo : ' . $emailId . "<br/>";
                                } else {
                                    echo 'Email Not sent to Agent without todo: ' . $emailId . "<br/>";
                                }
                            } catch (Exception $err) {
                                print_r($err, true);
                            }
                            //}
                        }
                        $h++;
                    }

                    //send email for agency
                    //echo "<pre>";print_r($AgencyAgentComb[$value1['AgencySysId']]);
                    if (isset($AgencyAgentComb[$value1['AgencySysId']]) && count($AgencyAgentComb[$value1['AgencySysId']]) > 0 && count($AgentList) > 0) {
                        $g++;
                        $AgencyEmailData = array();
                        foreach ($AgencyAgentComb[$value1['AgencySysId']] as $key3 => $value3) {
                            foreach ($value3 as $key4 => $value4) {
                                $AgencyEmailData[] = $value4;
                            }
                        }
                        $AgencyDetails['FirstName'] = trim(stripslashes($value1['Title'])) ? trim(stripslashes($value1['Title'])) : trim(stripslashes($value1['DisplayName']));
                        $AgencyDetails['LastName'] = '';
                        //echo "<pre>";print_r($AgencyEmailData);
                        $html = new Zend_View();
                        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');

                        //echo "<pre>";print_r($value2);
                        $html->assign('type', 'sendPendingTodoEmail');
                        $html->assign('userType', 'AGENCY');
                        $html->assign('runningTime', $runningTime);
                        $html->assign('data', $AgencyEmailData);
                        $html->assign('AgentDetails', $AgencyDetails);
                        echo $bodyText = $html->render('ajax-html.phtml');
                        $emailId = trim($value1['PrimaryEmail']);
                        //$emailId = "prashant@catpl.co.in";
                        $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => 'CRM - ' . trim($value1['PrimaryContactName']) . ' Overall Follow up and to do list for today!', 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                        try {
                            // Added By Pardeep Panchal For Email Count...
                            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                            $arrEmailStatistics = array(
                                "TPSysId" => '',
                                "TypeSysId" => 1, // 1 For Email 2 For SMS
                                "AgencySysId" => $AgencySysId,
                                "AgentSysId" => $AgentSysId,
                                "Title" => $bodyText,
                                "Source" => $arrEmailStatisticsType[2], // 1 For Fresh Proposals
                                "Status" => 0,
                                "RefSysId" => "",
                                "RefSysStatus" => "",
                                "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                            );

                            // Added By Pardeep Panchal For Email Count Ends...


                            if ($sentemail == 1) {
                                //$this->mailSentByElastice($emailData,$arrEmailStatistics);
                                echo 'Email has sent to Agency : ' . $emailId . "<br/>";
                            } else {
                                echo 'Email Not sent to Agency : ' . $emailId . "<br/>";
                            }
                            //echo 'Email has sent to Agency : '.$emailId."<br/>";
                            echo $g . '==>===============End Agency : ' . $emailId . " Completed=================<br/>";
                        } catch (Exception $err) {
                            print_r($err, true);
                        }
                    } else {

                        $AgencyDetails['FirstName'] = trim(stripslashes($value1['Title'])) ? trim(stripslashes($value1['Title'])) : trim(stripslashes($value1['DisplayName']));
                        $AgencyDetails['LastName'] = '';
                        //echo "<pre>";print_r($AgencyEmailData);
                        $html = new Zend_View();
                        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');

                        //echo "<pre>";print_r($value2);
                        $html->assign('type', 'sendPendingTodoEmail');
                        $html->assign('userType', 'AGENCY');
                        $html->assign('runningTime', $runningTime);
                        $html->assign('data', array());
                        $html->assign('AgentDetails', $AgencyDetails);
                        echo $bodyText = $html->render('ajax-html.phtml');
                        $emailId = trim($value1['PrimaryEmail']);
                        //$emailId = "prashant@catpl.co.in";
                        $emailData = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => 'CRM - ' . trim($value1['PrimaryContactName']) . ' Overall Follow up and to do list for today!', 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                        try {
                            // Added By Pardeep Panchal For Email Count...
                            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                            $arrEmailStatistics = array(
                                "TPSysId" => '',
                                "TypeSysId" => 1, // 1 For Email 2 For SMS
                                "AgencySysId" => $AgencySysId,
                                "AgentSysId" => $AgentSysId,
                                "Title" => $bodyText,
                                "Source" => $arrEmailStatisticsType[2], // 1 For Fresh Proposals
                                "Status" => 0,
                                "RefSysId" => "",
                                "RefSysStatus" => "",
                                "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                            );

                            // Added By Pardeep Panchal For Email Count Ends...


                            if ($sentemail == 1) {
                                //$this->mailSentByElastice($emailData,$arrEmailStatistics);
                                echo 'Email has sent to Agency : ' . $emailId . "<br/>";
                            } else {
                                echo 'Email Not sent to Agency : ' . $emailId . "<br/>";
                            }
                            //echo 'Email has sent to Agency : '.$emailId."<br/>";
                            echo $g . '==>===============End Agency : ' . $emailId . " Completed=================<br/>";
                        } catch (Exception $err) {
                            print_r($err, true);
                        }
                        //
                    }

                    //#end 
                }
            }
            //echo "<pre>"; print_r($AgencyAgentComb);
        }
        die;
    }

    public function updateDynamicPackageRateAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        //        echo '<pre>'; print_r($getData['tripstartdate']); echo '</pre>';
        $objPackage = new Travel_Model_TblPackage();
        $TPSysId = $getData['tpID'];
        $planDetails = $this->_crmcusttravelplan->GetCustomerTravelPlanByTPID($TPSysId);
        $packageId = trim($planDetails[0]['TPId']);
        $mID = trim($planDetails[0]['SharedMealPlanType']);
        $catID = trim($planDetails[0]['EconomyMask']);
        $tourID = trim($planDetails[0]['TourType']);
        $MpType = '';
        $tripstartdate = date("Y-m-d", strtotime(str_replace('/', '-', @$getData['pkgCheckInDate'])));
        $CustomerSysId = (NULL != $planDetails[0]['CustomerSysId'] && !empty($planDetails[0]['CustomerSysId'])) ? base64_decode($planDetails[0]['CustomerSysId']) : '';

        $customerDetails = array();
        if (isset($CustomerSysId) && $CustomerSysId > 0) {
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById(trim($CustomerSysId));
        }
        $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
        $IsB2BProposal = isset($planDetails[0]['IsB2BProposal']) ? $planDetails[0]['IsB2BProposal'] : 0;
        if ($IsB2BProposal == 1) {
            $MarketPlaceId = 2;
        } else {
            $MarketPlaceId = 1;
        }
        $TotAdultCount = 0;
        $TotChildCount = 0;
        $TotInfantCount = 0;
        $RoomInfoJson = json_decode($planDetails[0]['RoomInfoJson'], true);
        $k = 1;
        foreach ($RoomInfoJson as $res) {
            $TotAdultCount += $res['Adult'];
            $TotChildCount += $res['Child'];
            $TotInfantCount += $res['Infant'];
            $roomjson[$k]['Adult'] = $res['Adult'];
            if ($roomjson[$k]['Adult'] == 3) {
                $roomjson[$k]['AdultBedType'] = '';
            }
            $roomjson[$k]['Child'] = $res['Child'];
            $roomjson[$k]['Infant'] = $res['Infant'];
            for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                $roomjson[$k]['ChildAge_' . $j] = $res['ChildAge_' . $j];
                $roomjson[$k]['ChildBedType_' . $j] = $res['ChildBedType_' . $j];
            }
            $k++;
        }
        /* for($k=1;$k<=$getData['roomlp'];$k++) { 
          $roomjson[$k]['Adult'] = $this->_request->getParam('adult_' . $k);
          if ($roomjson[$k]['Adult'] == 3) {
          $roomjson[$k]['AdultBedType'] = $this->_request->getParam('adultcl_extrabed_' . $k . '_3');
          }
          $roomjson[$k]['Child'] = $this->_request->getParam('child_' . $k);
          $roomjson[$k]['Infant'] = $this->_request->getParam('infant_' . $k);
          for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
          $roomjson[$k]['ChildAge_' . $j] = $this->_request->getParam('child_age_' . $k . '_' . $j);
          $roomjson[$k]['ChildBedType_' . $j] = $this->_request->getParam('child_extrabed_' . $k . '_' . $j);
          }
          } */
        $roominfojson = json_encode($roomjson);
        $totaltraveler = $TotAdultCount + $TotChildCount;
        $this->currentDate = Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss');
        //get travelplan details
        //echo "<pre>";print_r($planDetails);die;
        //echo $roominfojson.",", $packageId.",", $catID.",", $tourID.",", $mID.",", $tripstartdate;
        $getpkgprice = Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePriceArray($roominfojson, $packageId, $catID, $tourID, $mID, $tripstartdate, 'Agent', 'Calculate', NULL, $MarketPlaceId);
        //echo "<pre>";print_r($getpkgprice);die;
        //update for hotels
        $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($TPSysId); // get itenary
        $TPIntSysIdsArr = array_column($travelplanIetnaryData, 'TPIntSysId');
        $TPIntSysIds = implode(', ', $TPIntSysIdsArr);
        $tplanitenaryaccomdata = $this->_crmcusttravelplan->GetTravelPlanCustomerItenaryAccomCopy($TPIntSysIds); // get accom by itenary id
        //echo "<pre>";print_r($getpkgprice);die;

        if (!empty($tplanitenaryaccomdata)) {
            $where = "TPIntSysId IN(" . $TPIntSysIds . ")";
            $data['CreateDate'] = $this->currentDate;
            $data['UpdateDate'] = $this->currentDate;
            $data['IsActive'] = 0;
            $data['IsMarkForDel'] = 1;
            $this->_crmcusttravelplanItenaryAccom = new Travel_Model_CRM_CustomerTravelPlanAccom();
            $this->_crmcusttravelplanItenaryAccom->UpdateTravelPlanAccom($data, $where); // add accom with new itenary ids

            $i = 0;
            foreach ($tplanitenaryaccomdata as $tplanitenaryaccom) {
                $totalhotelprice = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getTotalCostOfHotelByTravelers($getpkgprice['hotelDetails'][$i], $roominfojson);
                $travelitenaryaccomArray = $tplanitenaryaccom;
                unset($travelitenaryaccomArray['VersionId']);
                $travelitenaryaccomArray['TotalCostSO'] = $getpkgprice['hotelDetails'][$i]['TotalCostSO'] ? $getpkgprice['hotelDetails'][$i]['TotalCostSO'] : 0;
                $travelitenaryaccomArray['TotalCostDO'] = $getpkgprice['hotelDetails'][$i]['TotalCostDO'] ? $getpkgprice['hotelDetails'][$i]['TotalCostDO'] : 0;
                $travelitenaryaccomArray['TotalCostExtraBed'] = $getpkgprice['hotelDetails'][$i]['TotalCostExtraBed'] ? $getpkgprice['hotelDetails'][$i]['TotalCostExtraBed'] : 0;
                $travelitenaryaccomArray['TotalCostWithoutBed'] = $getpkgprice['hotelDetails'][$i]['TotalCostWithoutBed'] ? $getpkgprice['hotelDetails'][$i]['TotalCostWithoutBed'] : 0;
                $travelitenaryaccomArray['TotalCost'] = $totalhotelprice ? $totalhotelprice : 0;
                $travelitenaryaccomArray['Discounts'] = $getpkgprice['hotelDetails'][$i]['Discounts'] ? $getpkgprice['hotelDetails'][$i]['Discounts'] : 0;
                $travelitenaryaccomArray['NetCost'] = $totalhotelprice;
                $travelitenaryaccomArray['Taxes'] = $getpkgprice['hotelDetails'][$i]['Taxes'] ? $getpkgprice['hotelDetails'][$i]['Taxes'] : 0;
                $travelitenaryaccomArray['CreateDate'] = $this->currentDate;
                $travelitenaryaccomArray['UpdateDate'] = $this->currentDate;
                //echo "<pre>";print_r($travelitenaryaccomArray);echo "</pre>";
                $this->_crmcusttravelplanItenaryAccom->addCustomerTravelPlanAccom($travelitenaryaccomArray); // add accom with new itenary ids
                //$this->_crmcusttravelplanItenaryAccom->UpdateTravelPlanAccom($travelitenaryaccomArray,$where); // add accom with new itenary ids
                /* 					$existingtpintID = $tplanitenaryaccom['TPIntSysId'];
                  $existingVersionID = $tplanitenaryaccom['VersionId'];
                  $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);
                  $travelitenaryaccomArray = $getpkgprice['hotelDetails'][$i];
                  $travelitenaryaccomArray['SeqId'] = ($travelitenaryaccomArray['Sequence'])?$travelitenaryaccomArray['Sequence']:1;
                  unset($travelitenaryaccomArray['TPIntSysId']);
                  unset($travelitenaryaccomArray['Sequence']);
                  unset($travelitenaryaccomArray['NetSOccupCost']);
                  unset($travelitenaryaccomArray['NetDOccupCost']);
                  unset($travelitenaryaccomArray['NetExtraBedCost']);
                  unset($travelitenaryaccomArray['NetExtraWOBedCost']);
                  unset($travelitenaryaccomArray['EconomyType']);

                  $travelitenaryaccomArray['CreateDate'] = $this->currentDate;
                  $travelitenaryaccomArray['UpdateDate'] = $this->currentDate;
                  echo $where = "TPIntSysId = ". $existingtpintID." AND VersionId = ". $existingVersionID;
                  echo "<pre>";print_r($travelitenaryaccomArray);
                  $this->_crmcusttravelplanItenaryAccom = new Travel_Model_CRM_CustomerTravelPlanAccom();
                  $this->_crmcusttravelplanItenaryAccom->UpdateTravelPlanAccom($travelitenaryaccomArray,$where); // add accom with new itenary ids
                 */     //$this->_crmcusttravelplanItenaryAccom->UpdateTravelPlanAccom($travelitenaryaccomArray,$where); // add accom with new itenary ids
                $i++;
            }
        }
        //#end of update for hotels
        //update for activity
        $tpitenrayEvents = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryEvents($TPIntSysIds); // get accom by itenary id
        if (!empty($tpitenrayEvents)) {
            $i = 0;
            foreach ($tpitenrayEvents as $tpitenrayEvent) {
                $existingtpintID = $tpitenrayEvent['TPIntSysId'];
                $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);
                $tpitenrayevntsArray = $getpkgprice['activityDetails'][$i];
                unset($tpitenrayevntsArray['TPIntSysId']);
                unset($tpitenrayevntsArray['TotalCostNativeAdult']);
                unset($tpitenrayevntsArray['TotalCostNativeChild']);
                $tpitenrayevntsArray['Markup'] = ($getpkgprice['activityDetails'][$i]['Markup']) ? $getpkgprice['activityDetails'][$i]['Markup'] : 0;
                $tpitenrayevntsArray['Cost'] = ($getpkgprice['activityDetails'][$i]['TotalCostNativeAdult']) ? $getpkgprice['activityDetails'][$i]['TotalCostNativeAdult'] : 0;
                $tpitenrayevntsArray['KidsCost'] = ($getpkgprice['activityDetails'][$i]['TotalCostNativeChild']) ? $getpkgprice['activityDetails'][$i]['TotalCostNativeChild'] : 0;
                $tpitenrayevntsArray['CreateDate'] = $this->currentDate;
                $tpitenrayevntsArray['UpdateDate'] = $this->currentDate;
                $where = "TPIntSysId = " . $existingtpintID;
                $this->_crmcustomertravelItenaryEvents = new Travel_Model_CRM_CustomerTravelItenaryEvents();
                $this->_crmcustomertravelItenaryEvents->UpdateTravelItenaryEvents($tpitenrayevntsArray, $where); // add accom with new itenary ids
                $i++;
            }
        }
        //#end of update for activity
        //update for sightseeing
        $tpitenarysightseeing = $this->_crmcusttravelplan->GetCustomerTravelPlanSightSeeing($TPIntSysIds); // get sightseeing by itenary ids
        if (!empty($tpitenarysightseeing)) {
            $i = 0;
            foreach ($tpitenarysightseeing as $tpitenarysightseen) {
                $existingtpintID = $tpitenarysightseen['InvnItemSysId'];
                $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);
                $tpitenraysightseeingArray = $getpkgprice['sightSeeingDetails'][$i];
                unset($tpitenraysightseeingArray['InvnItemSysId']);
                unset($tpitenraysightseeingArray['Sequence']);
                unset($tpitenraysightseeingArray['TotalCostNativeAdult']);
                unset($tpitenraysightseeingArray['TotalCostNativeChild']);
                $tpitenrayevntsArray['SeqId'] = $getpkgprice['sightSeeingDetails'][$i]['Sequence'] ? $getpkgprice['sightSeeingDetails'][$i]['Sequence'] : 1;
                $tpitenraysightseeingArray['Markup'] = ($getpkgprice['sightSeeingDetails'][$i]['Markup']) ? $getpkgprice['sightSeeingDetails'][$i]['Markup'] : 0;
                $tpitenraysightseeingArray['CreateDate'] = $this->currentDate;
                $tpitenraysightseeingArray['UpdateDate'] = $this->currentDate;
                $where = "InvnItemSysId = " . $existingtpintID;
                $this->_crmcustomertravelSightSeeing = new Travel_Model_CRM_CustomerTravelItenarySightSeeing();
                $this->_crmcustomertravelSightSeeing->UpdateTravelSightSeeing($tpitenraysightseeingArray, $where); // add accom with new itenary ids
                $i++;
            }
        }
        //#end of update for sightseeing
        //update for other services
        $tpitenaryotherSevices = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServices($TPSysId); // get sightseeing by itenary ids
        if (!empty($tpitenarysightseeing)) {
            $i = 0;
            foreach ($tpitenaryotherSevices as $tpitenaryotherSevice) {
                $existingtpintSysID = $tpitenaryotherSevice['TPIntSysId'];
                $existingtpintID = $tpitenaryotherSevice['OtherSrvSysId'];
                $tpitenaryotherSeviceArray = $getpkgprice['otherServicesDetails'][$i];
                //$tpitenaryotherSeviceArray['CreateDate'] = $this->currentDate;
                $tpitenaryotherSeviceArray['UpdateDate'] = $this->currentDate;
                $where = "OtherSrvSysId = " . $existingtpintID . " AND TPIntSysId=" . $existingtpintSysID;
                $this->_crmcustomertravelOtherService = new Travel_Model_CRM_CustomerTravelOtherServices();
                $this->_crmcustomertravelOtherService->UpdateTravelPlanOtherService($tpitenaryotherSeviceArray, $where); // add accom with new itenary ids
                $i++;
            }
        }
        //#end of update for other services
        //update for transport
        //echo "<pre>";print_r($getpkgprice);
        //echo "hhhhhhhhh";
        //echo $TPIntSysIds;
        $tpitenaryotherTransports = $this->_crmcusttravelplan->GetTravelPlanItenaryFixedTransport($TPIntSysIds); // get transport by itenary ids
        //echo "<pre>";print_r($tpitenaryotherTransports);die;
        if (!empty($tpitenaryotherTransports)) {
            /* $where = "TPIntSysId IN(". $TPIntSysIds.")";
              $data['CreateDate'] = $this->currentDate;
              $data['UpdateDate'] = $this->currentDate;
              $data['IsActive'] = 0;
              $data['IsMarkForDel'] = 1;
              $this->_crmcusttravelplanFixed = new Travel_Model_CRM_CustomerTravelPlanFixed();
              $this->_crmcusttravelplanFixed->UpdateTravelPlanFixedTrans($data,$where); // add accom with new itenary ids */
            $i = 0;
            //calculate price with markup
            /* if($planDetails[0]['GSTSharedMode']==1){
              $gstTaxType=5;
              }
              if($planDetails[0]['GSTSharedMode']==2){
              $gstTaxType=18;
              }

              $IsB2BProposal=isset($planDetails[0]['IsB2BProposal'])?$planDetails[0]['IsB2BProposal']:0;
              if($IsB2BProposal==1){
              $MarketPlaceId = 2;
              }else{
              $MarketPlaceId = 1;
              }
              $marketwiseratebyo = $this->_crmcusttravelplan->GetMarketWiseRateBYOReadyMade($TPSysId,@$catID,$tourID,$mID,$MarketPlaceId);
              $markuptypeCustomise = ($marketwiseratebyo['MarkType'] == 1) ? 'FixedAmount' : 'FixedPercnt';
              $markupvalue=$marketwiseratebyo['MarkPercent']; */
            //#end calculate price with markup
            foreach ($tpitenaryotherTransports as $tpitenaryotherTransport) {


                $tpitenaryotherTransportArray = $getpkgprice['transportDetails'][$i];
                //calculate price with markup
                /* $pricediff = $tpitenaryotherTransportArray['TotalPrice']; //- $selectedprice;
                  $totalMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->calculateMarkUp($pricediff, $markuptypeCustomise, $markupvalue); // defined in costsheet
                  $finalcostWM = $pricediff + $totalMarkUp;
                  if ($gstTaxType == 18) {
                  $taxAmt = $totalMarkUp;
                  } else {
                  $taxAmt = $finalcostWM;
                  }
                  $perVehiclePrice = $finalcostWMNT = round($finalcostWM + (($taxAmt * $gstTaxType) / 100));
                  if ($pricediff == "0") {
                  $perVehiclePrice = 0;
                  } */
                //#end calculate price with markup
                $existingtpintSysID = $tpitenaryotherTransport['TPIntSysId'];
                $existingtpSysID = $tpitenaryotherTransport['TPSysId'];
                $existingtpintID = $tpitenaryotherTransport['FixTransSysId'];
                $tpitenaryotherTransportArray['VehicleQty'] = $tpitenaryotherTransport['VehicleQty'];
                //$tpitenaryotherTransportArray['TotalPrice'] = $perVehiclePrice;
                unset($tpitenaryotherTransportArray['TPSysId']);
                unset($tpitenaryotherTransportArray['TPIntSysId']);
                unset($tpitenaryotherTransportArray['FixTransSysId']);
                //$tpitenaryotherTransportArray['CreateDate'] = $this->currentDate;
                $tpitenaryotherTransportArray['UpdateDate'] = $this->currentDate;
                $where = "FixTransSysId = " . $existingtpintID . " AND TPIntSysId=" . $existingtpintSysID . " AND TPSysId=" . $existingtpSysID;
                $this->_crmcustomertravelOtherService = new Travel_Model_CRM_CustomerTravelPlanFixed();
                $this->_crmcustomertravelOtherService->UpdateTravelPlanFixedTrans($tpitenaryotherTransportArray, $where); // add accom with new itenary ids
                $i++;
            }
        }
        $msg = array('status' => 'success');
        //#end of update for transport
        echo json_encode($msg);
        exit;
    }

    // for fullfillment agent view
    public function viewCustomerFullfillmentAction() {
        //                Zend_Session::destroy(); // to destroy package booking page session

        $this->_helper->layout->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;

        $intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $objCustTravelPlanFull = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
        $tpID = base64_decode($this->getRequest()->getParam('id'));
        $CustomerSysId = (NULL != $this->getRequest()->getParam('cid')) ? base64_decode($this->getRequest()->getParam('cid')) : '';
        $queryTPSysId = (NULL != $this->getRequest()->getParam('qId')) ? base64_decode($this->getRequest()->getParam('qId')) : '';
        if ($tpID > 0) {

            $flexiPackageListCheck = $objPackage->getCustPackageList($tpID);
        }
        if ($flexiPackageListCheck['AgencySysId'] != $intLoggedinUserAgencySysId) {
            echo "something went wrong.please try after some time";
            exit;
        }
        //echo "<pre>";print_r($flexiPackageList);die;
        $currencyarr = $objPackage->getCurrencyList();
        $this->view->currencyarr = $currencyarr;
        //copy data from customer tables to fullfillment ==> tables ,itenary,accom,events,sightseeing,otherservices

        $GetMealPlan = $objCustTravelPlanFull->GetMealPlan();
        $this->view->GetMealPlan = $GetMealPlan;
        $copydata = $objCustTravelPlanFull->copyCutomerToFullFillment($tpID);
        if ($copydata == true) {
            //fetch data from fullfillment tables
            //#end of fetch data from fullfillment
        }
        $flexiPackageList = $objCustTravelPlanFull->getCustPackageList($tpID);
        //#end of coy data
        //exit;
        // Added By Pardeep Panchal for Show T & C If Shared From GTX Network..............
        $strUrlData = ($this->getRequest()->getParam('data') != '') ? $this->getRequest()->getParam('data') : '';
        if ($strUrlData != '') {

            $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);
            //echo "<pre>";print_r($arrUrlData);exit;
            $packid = $arrUrlData['packid'];
            $this->view->isfromgtxnetwork = $isfromgtxnetwork = $arrUrlData['isfromgtxnetwork'];
            $intLoggedinUserAgencySysId = $arrUrlData['intLoggedinUserAgencySysId'];

            $objPackageSearch = new Gtxnetwork_Model_PackageSearch();
            $this->view->arrCustomizeTNCData = $arrCustomizeTNCData = $objPackageSearch->packageCustomizeTermsAndConditions($intLoggedinUserAgencySysId, $packid);
        }







        if ($tpID > 0) {

            $objSupplier = new Travel_Model_TblSupplier();
            $PkgSupplierDetails = $objSupplier->getSupplierList($flexiPackageList['SupplierSysId']);
            //echo "<pre>";print_r($flexiPackageList);die;
            $objSupplier->SupplierSysId = $flexiPackageList['SupplierSysId'];
            $packageSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $flexiPackageList['SupplierSysId']);
            $fullfillmentObj = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
            if (isset($flexiPackageList['DestinationCovered']) && !empty($flexiPackageList['DestinationCovered'])) {
                $cityobj = new Travel_Model_TblCity();
                $cityIds = trim($flexiPackageList['DestinationCovered']);
                $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                $this->view->otherlocationcity = $otherlocationcity;

                $fullfillmentData = $fullfillmentObj->ChkFullfillmentRecordExist($tpID);
                $this->view->fullfillmentData = $fullfillmentData;
            }

            $SourcingCostData = $fullfillmentObj->ChkFullfillmentRecordExist($tpID, '0');
            $this->view->SourcingCostData = $SourcingCostData;
            $SourcingCostSaleData = $fullfillmentObj->ChkFullfillmentRecordExistSales($tpID);
            $ArrSourcingCostSale = array();
            if ($SourcingCostSaleData) {
                foreach ($SourcingCostSaleData as $k => $val) {
                    $ArrSourcingCostSale[$val['TPIntSysId']][] = $val;
                }
            }
            $this->view->SourcingCostSaleData = $ArrSourcingCostSale;
            //echo "<pre>";print_r($ArrSourcingCostSale);die;
            $objCusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $getcustomerDetail = $objCustTravelPlanFull->GetTravelPlanDetailsofCustomer($tpID);
            if ($getcustomerDetail[0]['CustomerSysId'] == '' && $CustomerSysId != '') {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $fetchRecord = $this->_crmcustomerObj->GetAgencyCustomerById(trim($CustomerSysId));
                $getcustomerDetail[0]['CustomerSysId'] = $fetchRecord['CustomerSysId'];
                $getcustomerDetail[0]['EmailId'] = $fetchRecord['EmailId'];
                $getcustomerDetail[0]['Contacts'] = $fetchRecord['Contacts'];
                $getcustomerDetail[0]['FirstName'] = $fetchRecord['FirstName'];
                $getcustomerDetail[0]['Salutation'] = $fetchRecord['Title'];
                $getcustomerDetail[0]['LastName'] = $fetchRecord['LastName'];
                $getcustomerDetail[0]['IsB2BAgent'] = $fetchRecord['IsB2BAgent'];
                $getcustomerDetail[0]['countrycode'] = $fetchRecord['countrycode'];
            }
            //echo "<pre>";print_r($fetchRecord);die;
            $IsB2BProposal = isset($flexiPackageList['IsB2BProposal']) ? $flexiPackageList['IsB2BProposal'] : 0;
            if ($IsB2BProposal == 1) {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }

            if ($flexiPackageList['MasterTPSysId'] == '0') {
                $childpackarr = $objCustTravelPlanFull->GetVersionInfo($tpID);
            } else {
                $childpackarr = $objCustTravelPlanFull->GetVersionInfo($flexiPackageList['MasterTPSysId']);
            }

            //            echo '<pre>'; print_r($childpackarr); die;

            $packRates = array();
            $tppackRate = array();
            if ($flexiPackageList['PackSpecType'] != '3') {
                foreach ($childpackarr as $key => $proposal) {
                    $StartDateTime = (array) $proposal['StartDate'];
                    $TripDate = date("Y-m-d", strtotime($StartDateTime['date']));
                    //                $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripdate'])));
                    $packRates = $objPackage->getCustPackRate($proposal['TPSysId'], '', $TripDate);
                    $objCust = new Travel_Model_CRM_CustomerTravelPlan();
                    $tppackRate = $objCust->getCustTravelPackRate($proposal['TPSysId'], $TripDate);
                    $tppackRates = @$tppackRate[0];
                    $packRate = @$packRates[0];
                    $arrPkg['DiscountType'] = $proposal['DiscountType'];
                    $arrPkg['DiscountVal'] = $proposal['DiscountVal'];
                    $arrPkg['AdvBookingPercent'] = $proposal['AdvBookingPercent'];
                    //echo '<pre>'; print_r($proposal); echo '</pre>';
                    $strRoomInfoJson = $proposal['RoomInfoJson'];
                    //Package Cost.....   
                    $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetAgencyCustomerTravelPlanCost($proposal['TPSysId'], $strRoomInfoJson, $arrPkg, $packRate, $tppackRates);
                    $finalPackageCostWithDiscount = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageCostwithDiscount($arrPkg, $arrPkgCost['FinalCost']);
                    $finalPackageCostWithMarkupnTax = $finalPackageCostWithDiscount + $arrPkgCost['FinalMarkUp'] + $arrPkgCost['Tax'];
                    $taxdetailforagency = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax('', "P", 0);
                    $tax = (trim($taxdetailforagency['ServiceTaxPercentage']) > 0) ? trim(floatval($taxdetailforagency['ServiceTaxPercentage'])) : 0;
                    // $serviceTax = round(($proposal['MarkUp'] - $proposal['CustomDiscount']) * $tax / 100);
                    $gsttype = ($proposal['GSTSharedMode'] == 0) ? 1 : $proposal['GSTSharedMode'];
                    $GSTApplicableOn = $gsttype;
                    $packageCost = $finalPackageCostWithMarkupnTax;
                    $AgencyMarkUp = $arrPkgCost['FinalMarkUp'];
                    $AgencyExtraMarkUp = $proposal['MarkUp'];
                    $AgencyDiscount = $proposal['CustomDiscount'];
                    $intProductType = 9;
                    $intProductGeoType = 1; // 1 For Domestic, 2 For International

                    $arrInputData = array(
                        "GSTApplicableOn" => $GSTApplicableOn,
                        "intProductType" => $intProductType,
                        "intProductGeoType" => $intProductGeoType,
                        "Cost" => $packageCost,
                        "AgencyMarkUp" => $AgencyMarkUp,
                        "AgencyExtraMarkUp" => $AgencyExtraMarkUp,
                        "AgencyDiscount" => $AgencyDiscount
                    );
                    //print_r($arrInputData);
                    $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
                    $serviceTax = trim($arrGSTCalculations['GSTAmount']);

                    $finalPackageCostWith_extramarkupNdiscount = $finalPackageCostWithMarkupnTax + round($proposal['MarkUp']) + $serviceTax - round($proposal['CustomDiscount']);

                    $childpackarr[$key]['GrandTotal'] = $finalPackageCostWith_extramarkupNdiscount;
                }
            }
            $this->view->proposalList = $childpackarr;

            $packageTncList = $objPackage->getCustPackageTncList($tpID);
            $flexiPackageList['tncDetails'] = $packageTncList;

            //for agency details
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($flexiPackageList['AgencySysId']);
            $agencyObj = new Travel_Model_TblAgency();
            $getAgentDetail = $agencyObj->getAgencyUserDataById($flexiPackageList['AgentSysId']);
            //            echo "<pre>".print_r($flexiPackageList);die;
            $flexiPackageList['agencyDetails'] = $getAgencyDetail;
            $flexiPackageList['agentDetails'] = $getAgentDetail;
            $inclusionMastArray = $objPackage->getPackageInclusionList();
            //print_r($flexiPackageList['InclMask']);
            $inclusionArr = $objPackage->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
            $flexiPackageList['inclusionDetails'] = $inclusionArr;
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->PkgSupplierDetails = $PkgSupplierDetails;
            $this->view->packageSupplierDetails = $packageSupplierDetails;
            //echo "<pre>";print_r($packageSupplierDetails);die;


            $hotelarr = $objPackage->getCustomerFlexiPackageFinalHotels($flexiPackageList['TPSysId']); // for only hotel overview
            //echo "<pre>";print_r($hotelarr);die;
            $this->view->hotelarr = $hotelarr;

            $flexiPackageItenList = $objPackage->getCustPackageItenListFullfillment($tpID);
            $flexiPackageAllDetailsList = $objPackage->getCustPackageAllDetailsListFullFill($tpID);
            //echo "<pre>";print_r($flexiPackageAllDetailsList);die;
            $this->view->flexiPackageItenList = $flexiPackageItenList;
            $this->view->flexiPackageAllDetailsList = $flexiPackageAllDetailsList;
            $objCity = new Travel_Model_TblCity();
            if (!empty($flexiPackageItenList)) {
                $this->view->cityMainDetail = $objCity->getCityImagesDetailsById($flexiPackageItenList[0]['PlaceSysId'], 1, 1);
            }
            //Get Package Places 
            $flexiPackagePlaces = $objPackage->getCustomerPackagePlacesList($tpID);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;

            $tourID = $this->getRequest()->getParam('tID');
            $this->view->tourID = $tourID = !empty($tourID) ? $tourID : $flexiPackageList['TourType'];
            //Get Package Hotels

            $packType = $flexiPackageList['PackSpecType'];

            if ($flexiPackageList['PackSpecType'] == '3') { // only for dynamic proposal
                $gettransportoption = $objPackage->GetTransPortOption($tpID);
                $totaltransport = count(array_column($gettransportoption, 'total'));
                $this->view->totaltransportCount = $totaltransport;

                $catID = $this->getRequest()->getParam('cID');
                $mealID = $this->getRequest()->getParam('mID');
                $this->view->catID = $catID = !empty($catID) ? $catID : $flexiPackageList['EconomyMask']; // only for dynamic
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsList($tpID, @$catID, $packType);

                $getotherservices = $this->_crmcusttravelplan->GetOtherServices($tpID);
                $gettransportdata = $this->_crmcusttravelplan->GetAllTransportOption($tpID);
                $this->view->getotherservices = $getotherservices;
                $this->view->gettransportdata = $gettransportdata;
                $flexiPackageHotelListArr1 = $flexiPackageHotelMealPlanWiseListArr = array();
                for ($h = 0; $h < count(@$flexiPackageHotelsList); $h++) {
                    if ($flexiPackageHotelsList[$h]['IsSelectedOnPkg'] == '1') {
                        $flexiPackageHotelListArr1[] = $flexiPackageHotelsList[$h];
                        $flexiPackageHotelMealPlanWiseListArr[$flexiPackageHotelsList[$h]['MealPlanType']][] = $flexiPackageHotelsList[$h];
                    }
                }

                $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList);
                $totalNight = $totalDaysNightsArr['totalnights'];
                $PackageCostCalType = $flexiPackageList['PackageCostCalType'];
                if ($PackageCostCalType) {
                    $PossibleCombinationsOfMealPlanArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPossibleCombinationsOfMealPlan($flexiPackageHotelListArr1, $totalNight, $catID);
                    $this->view->possibleCombinationsOfMealPlanArr = $PossibleCombinationsOfMealPlanArr;
                }

                //                echo '<pre>';print_r($PossibleCombinationsOfMealPlanArr); print_r($flexiPackageHotelsList); die;
                //                $mIDArr = array_keys($PossibleCombinationsOfMealPlanArr); // need a column for this in database
                $this->view->mID = $mID = !empty($mealID) ? $mealID : $flexiPackageList['SharedMealPlanType'];
                $this->view->flexiPackageHotelsList = !empty($PackageCostCalType) ? $flexiPackageHotelMealPlanWiseListArr[$mID] : $flexiPackageHotelsList;

                $marketwiseratebyo = $this->_crmcusttravelplan->GetMarketWiseRateBYOReadyMade($tpID, @$catID, $tourID, $mID, $MarketPlaceId);

                $this->view->marketwiseratebyo = $marketwiseratebyo;
            } else { // condition for readymade package
                $flexiPackageHotelsList = $objPackage->getCustPackageHotelsListReadymade($tpID);
                $this->view->flexiPackageHotelsList = $flexiPackageHotelsList;
            }
            //        $flexiPackageList = $objPackage->getCustPackageList($packid);
            //            


            if ($flexiPackageList['PackSpecType'] == 2) {
                $resflexiPackageActivityOnlyHotel = $objPackage->getCustPackageActivityListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageActivityList = $resflexiPackageActivityOnlyHotel;
                $resflexiPackageSSOnlyHotel = $objPackage->getCustPackageSightseenListBySeq(@$flexiPackageList['TPSysId'], 2);
                $this->view->flexiPackageSightseenList = $resflexiPackageSSOnlyHotel;
            } else {
                //Get Package Activity
                $flexiPackageActivityList = $objPackage->getCustPackageActivityList($tpID);
                $this->view->flexiPackageActivityList = $flexiPackageActivityList;
                //Get Package Sightseen
                $flexiPackageSightseenList = $objPackage->getCustPackageSightseenList($tpID);
                $this->view->flexiPackageSightseenList = $flexiPackageSightseenList;
            }



            $getpacktypemask = $objPackage->GetMasterPackageList();
            $this->view->packtypemask = $getpacktypemask;

            //Get Package Flight
            //            $flexiPackageFlight = $objPackage->getCustPackageAir($tpID);
            //            $this->view->flexiPackageFlight = $flexiPackageFlight;
            ########## Code Added By Shobhit ##################
            $this->view->tpID = $tpID;
            $getcustomerDetail[0]['AgentName'] = trim($getAgentDetail['FirstName']) . ' ' . trim($getAgentDetail['LastName']);
            $getcustomerDetail[0]['AgentNo'] = $getAgentDetail['ContactNo1'];
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $getversiondetails = $this->_crmcusttravelplan->GetVersionInfo($tpID);
            $objAgency = new Travel_Model_TblAgency();
            $agencyData = $objAgency->getAgencyDataById($flexiPackageList['AgencySysId']);
            $this->view->getAgencyData = $agencyData;

            $objAgencyUser = new Travel_Model_CRM_AgencyUserInbox();
            $getChatHistoryDetail = array();
            $checkCustomerChatExist = (@$getcustomerDetail[0]['CustomerSysId'] > 0) ? $objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID, trim($flexiPackageList['AgentSysId'])) : array();
            // $checkCustomerChatExist = (count($checkCustomerChatExist)==0)?$objAgencyUser->CheckCustomerMsgCount(@$getcustomerDetail[0]['CustomerSysId'], $tpID):$checkCustomerChatExist;
            if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                $getChatHistoryDetail = $objAgencyUser->GetCustChatHistDetWithLead($tpID, $getcustomerDetail[0]['CustomerSysId'], 'ASC');
            }
            $getcustomerDetail['userChatExist'] = (count($checkCustomerChatExist) > 0) ? count($checkCustomerChatExist) : count($getChatHistoryDetail);
            //  $this-view->getCustomerDetails = $getcustomerDetail;
            //query for get customer chat history
            $chatSenderDetails = array();
            $objAgencyStaff = new Travel_Model_TblAgencyStaff();
            $agentDetail = $objAgencyStaff->getUserDetailsById($flexiPackageList['AgentSysId']);
            if ($getcustomerDetail['userChatExist'] > 0) {
                if (isset($getcustomerDetail[0]['CustomerSysId']) && !empty($getcustomerDetail[0]['CustomerSysId'])) {
                    $this->view->chatHistoryDetail = $getChatHistoryDetail;
                    $chatSenderDetails['TPSysId'] = $tpID;
                    $chatSenderDetails['AgencySysId'] = $intLoggedinUserAgencySysId;
                    $chatSenderDetails['CustomerSysId'] = $getcustomerDetail[0]['CustomerSysId'];
                    $chatSenderDetails['AgentSysId'] = $flexiPackageList['AgentSysId'];
                    $chatSenderDetails['EmailId'] = $agentDetail['EmailId'];
                    //print_r($agentDetail);
                }
            }
            //end of customer chat history
            $getcustomerDetail['AgencyDetails'] = $agencyData;
            $chatSenderDetails['AgencyDetails'] = $agencyData;
            //echo '<pre>'; print_r($getcustomerDetail);die;
            $this->view->getcustomerDetail = $getcustomerDetail;
            $this->view->getversionDetails = $getversiondetails;
            $this->view->chatSenderDetails = $chatSenderDetails;

            $termscond = $objPackage->getTermCond($tpID);
            $this->view->termc = $termscond;

            $rateList = array('arrPkgCost' => array('AdultPax' => $flexiPackageList['MinPax'], 'ChildPax' => 0, 'FinalCost' => $flexiPackageList['NetPrice'], 'FinalDiscount' => $flexiPackageList['DiscountVal'], 'FinalMarkUp' => 0));
            $popupArray = array();
            $popupArray['rateList'] = json_encode($rateList);

            $this->view->popupArray = $popupArray;
            //send email to agent when customer open proposal
            $isPlanViewed = $this->_crmcusttravelplan->GetTravelPlanType($tpID);
            if ($isPlanViewed['IsPlanViewed'] == 0 && $flexiPackageList['IsShared'] == 1 && $isAgentLoggedIn == 0) {
                
            }
            //#end
            $objHotel = new Travel_Model_TblHotel();
            $objHotel->orderByField = " TB_Master_Accom_AccomAminity.AminityId";
            $objHotel->orderBy = "";
            $arrAmenites = $objHotel->getMasterAccomAminities();
            $this->view->arrAmenites = $arrAmenites;
            $this->view->queryTPSysId = $queryTPSysId;
            $encydataForTnc = $this->getEnc($flexiPackageList['TPSysId'] . ":" . $flexiPackageList['AgencySysId'] . ":" . $flexiPackageList['CustomerSysId']);
            $this->view->encid = $encydataForTnc;
        }
        $this->view->intLoggedinUserAgencySysId = $intLoggedinUserAgencySysId;
    }

    public function sendConfirmationAction() {
        $this->view->layout()->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $intTPSysId = base64_decode($this->getRequest()->getParam('pid'));
            $intCustSysId = base64_decode($this->getRequest()->getParam('cid'));

            $TPIntSysId = $this->getRequest()->getParam('TPIntSysId');
            $VersionId = $this->getRequest()->getParam('VersionId');
            $objPkg = new Travel_Model_TblPackage();
            $objPkgBooking = new Travel_Model_TblPackageBooking();
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $objCust = new Travel_Model_CRM_CustomerTravelPlan();
            $objCustTravelPlanFull = new Travel_Model_CRM_CustomerTravelPlanFullfillment();

            //Customer Details    
            $getCustomerDetail = $crmcustomerObj->GetAgencyMmbrById($intCustSysId);
            $this->view->getCustomerDetail = $getCustomerDetail;

            $getBookingId = $objPkgBooking->getPackageBookingId($intCustSysId);
            $this->view->getBookingId = $getBookingId;

            $getMembersDetail = $objPkgBooking->GetCustomerMembersById($getCustomerDetail['AgencySysId'], $intCustSysId, $intTPSysId);

            $this->view->getMembersDetail = $getMembersDetail;

            $GetMealPlan = $objCustTravelPlanFull->GetMealPlan();
            $GetMealPlanArr = array();
            if ($GetMealPlan) {
                foreach ($GetMealPlan as $value) {
                    $GetMealPlanArr[$value['MealTypeId']] = $value['Title'];
                }
            }
            $this->view->GetMealPlan = $GetMealPlanArr;
            $currencyarr = $objPkg->getCurrencyList();
            $Getcurrencyarr = array();
            if ($currencyarr) {
                foreach ($currencyarr as $value) {
                    $Getcurrencyarr[$value['CurrencyType']] = $value['Symbol'];
                }
            }
            $this->view->currencyarr = $Getcurrencyarr;
            //echo "<pre>";print_r($getMembersDetail);die;

            if (!empty($intTPSysId)) {

                //Number of Passengers
                $flexiPackageList = $objPkg->getCustPackageList($intTPSysId);
                $hotelarr = $objPkg->getCustomerFlexiPackageFullfilmentHotels($flexiPackageList['TPSysId'], $TPIntSysId); // for only hotel overview
                $this->view->hotelarr = $hotelarr;
                $SourcingCostSaleData = $objCustTravelPlanFull->ChkFullfillmentRecordExistSales($flexiPackageList['TPSysId']);
                $ArrSourcingCostSale = array();
                if ($SourcingCostSaleData) {
                    foreach ($SourcingCostSaleData as $k => $val) {
                        $ArrSourcingCostSale[$val['TPIntSysId']][] = $val;
                    }
                }
                $this->view->SourcingCostSaleData = $ArrSourcingCostSale;
                //echo "<pre>";print_r($ArrSourcingCostSale);echo "</pre>";
                $crmcustomerObj = new Travel_Model_CRM_Customer();
                $AgencySysId = trim($flexiPackageList['AgencySysId']);
                $AgentSysId = trim($flexiPackageList['AgentSysId']);
                $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($AgencySysId);
                $agencyObj = new Travel_Model_TblAgency();
                $getAgentDetail = $objCust->getAgentDetails($AgentSysId);
                $packageTncList = $objPkg->getCustPackageTncList($intTPSysId);
                $flexiPackageList['tncDetails'] = $packageTncList;
                //echo "<pre>";print_r($packageTncList);die;
                $flexiPackageList['agencyDetails'] = $getAgencyDetail;
                $flexiPackageList['agentDetails'] = $getAgentDetail;
                /* $inclusionMastArray=$objPkg->getPackageInclusionList();
                  $inclusionArr = $objPkg->getMasking($flexiPackageList['InclMask'], $inclusionMastArray, 'InclId');
                  $flexiPackageList['inclusionDetails']=$inclusionArr; */
                //echo "<pre>";print_r($flexiPackageList['inclusionDetails']);die;
                $this->view->flexiPackageList = $flexiPackageList;
                $flexiPackageItenList = $objPkg->getCustPackageItenList($intTPSysId);
                $this->view->flexiPackageItenList = $flexiPackageItenList;
                $ArrFromRoomInfoJson = json_decode($hotelarr[0]['RoomMemInfoJson']);
                //echo '<pre>';print_r($hotelarr[0]);die;
                $arrPassanger = array();
                foreach ($ArrFromRoomInfoJson as $key => $arr) {
                    $arrPassanger['Room'] = $key;
                    @$arrPassanger['Adult'] += $arr->Adult;
                    @$arrPassanger['Child'] += $arr->Child;
                    @$arrPassanger['Infant'] += $arr->Infant;
                    if (@$arr->bedtype == 'withbed') {
                        $arrPassanger['ChildWithBed'] += $arr->Child;
                    }
                    if (@$arr->bedtype == 'withoutbed') {
                        @$arrPassanger['ChildWithOutBed'] += $arr->Child;
                    }
                }

                $flexiPackageAllDetailsList = $objPkg->getCustPackageAllDetailsListFullFill($flexiPackageList['TPSysId']);
                $this->view->flexiPackageAllDetailsList = $flexiPackageAllDetailsList;

                $arrPassanger['TotalPass'] = $arrPassanger['Adult'] + $arrPassanger['Child'] + @$arrPassanger['Infant'] + @$arrPassanger['ChildWithBed'] + @$arrPassanger['ChildWithOutBed'];
                $this->view->arrPassanger = $arrPassanger;
                //echo "<pre>";print_r($arrPassanger);echo "<pre>";
            }
        } else {
            die;
        }
    }

    /// Update Hotels data by SIBO
    public function updateHotesDataAction() {
        $this->view->layout()->disableLayout();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $sessionAgencyUser = new Zend_Session_Namespace('AgencyUser');
        $isAgentLoggedIn = (isset($sessionAgencyUser->user) && !empty($sessionAgencyUser->user)) ? 1 : 0;

        $intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            $fullfillmentObj = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
            //echo "<pre>";print_r($getData);die;
            $TPSysId = $getData['TPSysId'];
            $CustomerSysId = $getData['CustomerSysId'];
            $TPIntSysId = $getData['TPIntSysId'];
            $VersionId = $getData['VersionId'];
            $city_name = $getData['city_name'];
            $city_id = $getData['city_id'];
            $selected_hotel_id = isset($getData['selected_hotel_id']) ? $getData['selected_hotel_id'] : '';
            $hotel_name = isset($getData['hotel_name']) ? $getData['hotel_name'] : '';
            $noofnight = isset($getData['noofnight']) ? $getData['noofnight'] : '';
            $checkin = isset($getData['checkin']) ? $getData['checkin'] : '';
            $checkout = isset($getData['checkout']) ? $getData['checkout'] : '';
            $PickUpPoint = isset($getData['PickUpPoint']) ? $getData['PickUpPoint'] : '';
            $DropPoint = isset($getData['DropPoint']) ? $getData['DropPoint'] : '';
            $PickUpDateTime = isset($getData['PickUpDateTime']) ? $getData['PickUpDateTime'] : '';
            $DropDateTime = isset($getData['DropDateTime']) ? $getData['DropDateTime'] : '';
            $pickupdrop = isset($getData['pickupdrop']) ? $getData['pickupdrop'] : '0';
            $EarlyCheckIn = isset($getData['EarlyCheckIn']) ? $getData['EarlyCheckIn'] : '0';
            $StatusSysId = isset($getData['TPStatusSysId']) ? $getData['TPStatusSysId'] : '0';
            $ServiceName = isset($getData['ServiceName']) ? $getData['ServiceName'] : '0';
            $ServiceRemark = isset($getData['ServiceRemark']) ? $getData['ServiceRemark'] : '0';
            $notes = isset($getData['notes']) ? $getData['notes'] : '0';
            $termscondition = isset($getData['termscondition']) ? $getData['termscondition'] : '0';

            $dataCustomer = array(
                'CustomerSysId' => $CustomerSysId,
                'UpdateDate' => date('Y-m-d H:i:s'),
            );
            $whereCus = array('TPSysId = ?' => $TPSysId);
            $this->_crmcusttravelplan->UpdateCustomerTravelPlanFullfillment($dataCustomer, $whereCus);
            $Sequence = $fullfillmentObj->SequenceTravelPlanItenaryFullfillment($TPSysId);
            //echo '<pre>'; print_r($Sequence['Sequence']);
            $room_type = isset($getData['room_type']) ? $getData['room_type'] : '';
            $hidden_room_type_id = isset($getData['hidden_room_type_id']) ? $getData['hidden_room_type_id'] : '';

            if (!empty($city_id)) {
                $count = 1;
                foreach ($city_id as $key => $val) {

                    if ($checkin[$key]) {
                        $FromDate = explode('/', $checkin[$key]);
                        $FromDate = $FromDate[2] . '-' . $FromDate[1] . '-' . $FromDate[0];
                    }
                    if ($checkout[$key]) {
                        $ToDate = explode('/', $checkout[$key]);
                        $ToDate = $ToDate[2] . '-' . $ToDate[1] . '-' . $ToDate[0];
                    }

                    if (!empty($PickUpDateTime[$key])) {
                        $PickUp = explode(" ", $PickUpDateTime[$key]);
                        $ArrPickUp = explode('/', $PickUp[0]);
                        $PickUpDTime = $ArrPickUp[2] . '-' . $ArrPickUp[1] . '-' . $ArrPickUp[0] . ' ' . $PickUp[1];
                    }
                    if (!empty($DropDateTime[$key])) {
                        $Drop = explode(" ", $DropDateTime[$key]);
                        $ArrDrop = explode('/', $Drop[0]);
                        $DropDTime = $ArrDrop[2] . '-' . $ArrDrop[1] . '-' . $ArrDrop[0] . ' ' . $Drop[1];
                    }
                    /*  Create room json */
                    $roomjson = array();
                    $totaladult = 0;
                    $totalchild = 0;
                    $totalInfant = 0;
                    if (!empty($room_type[$count])) {
                        $m = 0;
                        for ($k = 1; $k <= count($room_type[$count]); $k++) {
                            $roomjson[$k]['Adult'] = $this->_request->getParam('adult_' . $count . '_' . $k);
                            if ($roomjson[$k]['Adult'] == 3) {
                                $roomjson[$k]['AdultBedType'] = $this->_request->getParam('adultcl_extrabed_' . $count . '_' . $k);
                            }
                            $totaladult = +$roomjson[$k]['Adult'];
                            $roomjson[$k]['Child'] = $this->_request->getParam('child_' . $count . '_' . $k);
                            $totalchild = +$roomjson[$k]['Child'];
                            $roomjson[$k]['Infant'] = $this->_request->getParam('infant_' . $count . '_' . $k);
                            $totalInfant = +$roomjson[$k]['Infant'];
                            for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                                $roomjson[$k]['ChildAge_' . $j] = $this->_request->getParam('child_age_' . $count . '_' . $k . '_' . $j);
                                $roomjson[$k]['ChildBedType_' . $j] = $this->_request->getParam('child_extrabed_' . $count . '_' . $k . '_' . $j);
                            }
                            $roomjson[$k]['departuredate'] = $checkin[$key];
                            $roomjson[$k]['returndate'] = $checkout[$key];
                            $roomjson[$k]['RoomType'] = $room_type[$count][$m];
                            $roomjson[$k]['hidden_room_type_id'] = $hidden_room_type_id[$count][$m];
                            $roomjson[$k]['MealPlan'] = $this->_request->getParam('MealPlan_' . $count . '_' . $k);
                            $m++;
                        }
                    }
                    //echo '<pre>';print_r($roomjson);
                    $totalSourceCost = isset($getData['Cost']) ? $getData['Cost'] : '';
                    $igst = isset($getData['IGST']) ? $getData['IGST'] : '';
                    $sgst = isset($getData['SGST']) ? $getData['SGST'] : '';
                    $cgst = isset($getData['CGST']) ? $getData['CGST'] : '';
                    $FullGST = isset($getData['FullGST']) ? $getData['FullGST'] : '';
                    $FullGSTType = isset($getData['FullGSTType']) ? $getData['FullGSTType'] : '';
                    $FullGSTSlab = isset($getData['FullGSTSlab']) ? $getData['FullGSTSlab'] : '';
                    $FullCost = isset($getData['FullCost']) ? $getData['FullCost'] : '';
                    $FullTotalCost = isset($getData['TotalCost']) ? $getData['TotalCost'] : '';
                    $TYPE = isset($getData['TYPE']) ? $getData['TYPE'] : 0;
                    $ShareCurrency = isset($getData['ShareCurrency']) ? $getData['ShareCurrency'] : 0;
                    $supplier_sys_id = isset($getData['hidden_selected_supplier_sys_id']) ? $getData['hidden_selected_supplier_sys_id'] : 0;

                    if (!empty($TPIntSysId[$key])) {
                        /* update section */
                        $data = array(
                            'RoomMemInfoJson' => json_encode($roomjson),
                            'AccoSysId' => $selected_hotel_id[$key],
                            'Title' => $hotel_name[$key],
                            'FromDate' => $FromDate,
                            'ToDate' => $ToDate,
                            'XRefCityId' => $city_id[$key],
                            'TotalNights' => $noofnight[$key],
                            'IsEarlyCheckIn' => $EarlyCheckIn[$key],
                            'StatusSysId' => $StatusSysId[$key],
                            'SupplierSysId' => $supplier_sys_id[$key],
                            'UpdateDate' => date('Y-m-d H:i:s'),
                        );
                        $data['PickUpLocation'] = $PickUpPoint[$key];
                        $data['DropLocation'] = $DropPoint[$key];
                        $data['PickUpDateTime'] = isset($PickUpDTime) ? $PickUpDTime : '';
                        $data['DropDateTime'] = isset($DropDTime) ? $DropDTime : '';
                        $data['Notes'] = isset($notes[$key]) ? $notes[$key] : '';
                        $data['TermsConditions'] = isset($termscondition[$key]) ? $termscondition[$key] : '';
                        //echo '<pre>'; print_r($data);
                        $where = array('TPIntSysId = ?' => $TPIntSysId[$key], 'VersionId = ?' => $VersionId[$key]);
                        $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Accom_Fullfillment', $data, $where);
                        $ServiceArr = array();
                        $ServiceArr['ServiceName'] = isset($ServiceName[$count]) ? $ServiceName[$count] : '';
                        $ServiceArr['ServiceRemark'] = isset($ServiceRemark[$count]) ? $ServiceRemark[$count] : '';
                        $dataCity = array(
                            'Cities' => $city_name[$key],
                            'CitySysId' => $city_id[$key],
                            'ExtraServices' => json_encode($ServiceArr),
                            'UpdateDate' => date('Y-m-d H:i:s'),
                        );
                        $dataPlace = array(
                            'PlaceSysId' => $city_id[$key],
                            'UpdateDate' => date('Y-m-d H:i:s'),
                        );
                        $whereCity = array('TPIntSysId = ?' => $TPIntSysId[$key], 'TPSysId = ?' => $TPSysId);
                        $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Itenary_Fullfillment', $dataCity, $whereCity);
                        $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Itenary_Places_Fullfillment', $dataPlace, $whereCity);
                        //$this->_crmcusttravelplan->UpdateCustomerTravelPlanFullfillment($data, $where);

                        /*                         * ********************************************** Manage Sourcing cost********************************************* */

                        $SupplierData = array(
                            'SupplierSysId' => $supplier_sys_id[$key]
                        );
                        $whereSupp = "TPSysId = " . $TPSysId;
                        $date = date('Y-m-d H:i:s');
                        $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Fullfillment', $SupplierData, $whereSupp);
                        if ($ShareCurrency[$count]) {
                            foreach ($ShareCurrency[$count] as $keys => $value) {
                                $checkRecordExist = $fullfillmentObj->ChkFullfillmentRecordExist($TPSysId, $TYPE[$count][$keys], $TPIntSysId[$key], $VersionId[$key]);
                                //echo "<pre>";print_r($checkRecordExist);
                                if (!empty($checkRecordExist)) {
                                    $where = array('TPSysId = ?' => $TPSysId, 'IsSalesPrice = ?' => $TYPE[$count][$keys], 'TPIntSysId = ?' => $TPIntSysId[$key], 'VersionId = ?' => $VersionId[$key]);
                                    $userArray = array(
                                        'CurrencyType' => $ShareCurrency[$count][$keys],
                                        'SourceCost' => $totalSourceCost[$count][$keys] ? $totalSourceCost[$count][$keys] : 0,
                                        'IGST' => $igst[$count][$keys] ? $igst[$count][$keys] : 0,
                                        'SGST' => $sgst[$count][$keys] ? $sgst[$count][$keys] : 0,
                                        'CGST' => $cgst[$count][$keys] ? $cgst[$count][$keys] : 0,
                                        'IsGSTIncluded' => $FullGST[$count][$keys] ? $FullGST[$count][$keys] : 0,
                                        'GSTType' => $FullGSTType[$count][$keys] ? $FullGSTType[$count][$keys] : 0,
                                        'GSTSlab' => $FullGSTSlab[$count][$keys] ? $FullGSTSlab[$count][$keys] : 0,
                                        'Cost' => $FullCost[$count][$keys] ? $FullCost[$count][$keys] : 0,
                                        'TotalCost' => $FullTotalCost[$count][$keys] ? $FullTotalCost[$count][$keys] : 0,
                                        'IsSalesPrice' => $TYPE[$count][$keys] ? $TYPE[$count][$keys] : 0,
                                        'TPIntSysId' => $TPIntSysId[$key] ? $TPIntSysId[$key] : 0,
                                        'VersionId' => $VersionId[$key] ? $VersionId[$key] : 0,
                                        'UpdatedDate' => $date,
                                    );
                                    //echo '<pre>'; print_r($userArray);die;
                                    $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray, $where);
                                } else {
                                    $userArray = array(
                                        'TPSysId' => $TPSysId,
                                        'CurrencyType' => $ShareCurrency[$count][$keys],
                                        'SourceCost' => $totalSourceCost[$count][$keys] ? $totalSourceCost[$count][$keys] : 0,
                                        'IGST' => $igst[$count][$keys] ? $igst[$count][$keys] : 0,
                                        'SGST' => $sgst[$count][$keys] ? $sgst[$count][$keys] : 0,
                                        'CGST' => $cgst[$count][$keys] ? $cgst[$count][$keys] : 0,
                                        'IsGSTIncluded' => $FullGST[$count][$keys] ? $FullGST[$count][$keys] : 0,
                                        'GSTType' => $FullGSTType[$count][$keys] ? $FullGSTType[$count][$keys] : 0,
                                        'GSTSlab' => $FullGSTSlab[$count][$keys] ? $FullGSTSlab[$count][$keys] : 0,
                                        'Cost' => $FullCost[$count][$keys] ? $FullCost[$count][$keys] : 0,
                                        'TotalCost' => $FullTotalCost[$count][$keys] ? $FullTotalCost[$count][$keys] : 0,
                                        'IsSalesPrice' => $TYPE[$count][$keys] ? $TYPE[$count][$keys] : 0,
                                        'TPIntSysId' => $TPIntSysId[$key] ? $TPIntSysId[$key] : 0,
                                        'VersionId' => $VersionId[$key] ? $VersionId[$key] : 0,
                                        'CreatedDate' => $date,
                                        'UpdatedDate' => $date
                                    );
                                    $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray);
                                }
                                //echo "<pre>";print_r($value);
                            }
                        }
                    } else { /* Insert Section */
                        $Sequence = ($Sequence['Sequence'] + 1);
                        $ServiceArr = array();
                        $ServiceArr['ServiceName'] = isset($ServiceName[$count]) ? $ServiceName[$count] : '';
                        $ServiceArr['ServiceRemark'] = isset($ServiceRemark[$count]) ? $ServiceRemark[$count] : '';
                        $dataItenary = array(
                            'TPSysId' => $TPSysId,
                            'Sequence' => $Sequence,
                            'AgencySysId' => $intLoggedinUserAgencySysId,
                            'Title' => '0',
                            'Cities' => $city_name[$key],
                            'CitySysId' => $city_id[$key],
                            'ExtraServices' => json_encode($ServiceArr),
                            'UpdateDate' => date('Y-m-d H:i:s'),
                            'CreateDate' => date('Y-m-d H:i:s'),
                            'IsMarkForDel' => 0,
                            'IsActive' => 1
                        );
                        $TravelPlan_ItenaryId = $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Itenary_Fullfillment', $dataItenary);
                        //echo '<pre>'; print_r($TravelPlan_ItenaryId);
                        $dataPlace = array(
                            'TPIntSysId' => $TravelPlan_ItenaryId,
                            'Sequence' => $Sequence,
                            'TPSysId' => $TPSysId,
                            'PlaceSysId' => $city_id[$key],
                            'AgencySysId' => $intLoggedinUserAgencySysId,
                            'UpdateDate' => date('Y-m-d H:i:s'),
                            'CreateDate' => date('Y-m-d H:i:s'),
                            'IsMarkForDel' => 0,
                            'IsActive' => 1
                        );
                        $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Itenary_Places_Fullfillment', $dataPlace);
                        $data = array(
                            'TPIntSysId' => $TravelPlan_ItenaryId,
                            'AccoSysId' => $selected_hotel_id[$key],
                            'SupplierSysId' => $supplier_sys_id[$key],
                            'SeqId' => 1,
                            'IsFromAPI' => 0,
                            'SupplierSysId' => 0,
                            'SourceSysId' => 0,
                            'MasterIntSysId' => 0,
                            'AccoBookingId' => '',
                            'XRefBookingId' => '',
                            'XRefCancellationlId' => '',
                            'APIBookingRes' => '',
                            'APICancellationRes' => '',
                            'InvnItemSysId' => '',
                            'AgencySysId' => $intLoggedinUserAgencySysId,
                            'XrefInvtSysId' => 0,
                            'RoomType' => 0,
                            'RoomIndex' => 0,
                            'RoomTypeStr' => 0,
                            'RoomMemInfoJson' => json_encode($roomjson),
                            'Title' => $hotel_name[$key],
                            'FromDate' => $FromDate,
                            'ToDate' => $ToDate,
                            'XRefCityId' => $city_id[$key],
                            'AdultPax' => $totaladult,
                            'ChildPax' => $totalchild,
                            'InfantPax' => $totalInfant,
                            'TotalPax' => ($totaladult + $totalchild + $totalInfant),
                            'TotalNights' => $noofnight[$key],
                            'IsEarlyCheckIn' => $EarlyCheckIn[$key],
                            'StatusSysId' => $StatusSysId[$key],
                            'UpdateDate' => date('Y-m-d H:i:s'),
                            'CreateDate' => date('Y-m-d H:i:s'),
                            'IsSelectedOnPkg' => 1,
                            'RateType' => 1,
                            'IsMarkForDel' => 0,
                            'IsActive' => 1,
                            'TotalCost' => 0,
                            'Discounts' => 0,
                            'CurrencyType' => $ShareCurrency[$count][0],
                            'TotalCostGen' => 0,
                            'SupplierDiscountVal' => 0,
                            'TotalCostSO' => 0,
                            'TotalCostDO' => 0,
                            'TotalCostTO' => 0,
                            'TotalCostExtraBed' => 0,
                            'TotalCostWithoutBed' => 0,
                            'CancellationChrgs' => 0,
                            'ServiceTaxOnDiscount' => 0,
                            'XServiceTaxAmount' => 0,
                            'GTXServiceTaxAmount' => 0,
                            'AgentServiceTaxAmount' => 0,
                            'AgentsCustomServiceTaxAmount' => 0,
                            'Taxes' => 0,
                            'TDS' => 0,
                            'NetCost' => 0,
                            'MarkUp' => 0,
                            'AgencyMarkUp' => 0,
                            'GTXMarkup' => 0,
                            'TrxFee' => 0,
                            'Commission' => 0,
                            'DiscountMsg' => '',
                            'FullFillmentInfo' => '',
                        );
                        $data['PickUpLocation'] = $PickUpPoint[$key];
                        $data['DropLocation'] = $DropPoint[$key];
                        $data['PickUpDateTime'] = isset($PickUpDTime) ? $PickUpDTime : '';
                        $data['DropDateTime'] = isset($DropDTime) ? $DropDTime : '';
                        $data['Notes'] = isset($notes[$key]) ? $notes[$key] : '';
                        $data['TermsConditions'] = isset($termscondition[$key]) ? $termscondition[$key] : '';
                        //echo '<pre>'; print_r($data);
                        $TravelPlan_AccomId = $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Accom_Fullfillment', $data);

                        if ($ShareCurrency[$count]) {
                            foreach ($ShareCurrency[$count] as $keys => $value) {
                                $userArray = array(
                                    'TPSysId' => $TPSysId,
                                    'CurrencyType' => $ShareCurrency[$count][$keys],
                                    'SourceCost' => $totalSourceCost[$count][$keys] ? $totalSourceCost[$count][$keys] : 0,
                                    'IGST' => $igst[$count][$keys] ? $igst[$count][$keys] : 0,
                                    'SGST' => $sgst[$count][$keys] ? $sgst[$count][$keys] : 0,
                                    'CGST' => $cgst[$count][$keys] ? $cgst[$count][$keys] : 0,
                                    'IsGSTIncluded' => $FullGST[$count][$keys] ? $FullGST[$count][$keys] : 0,
                                    'GSTType' => $FullGSTType[$count][$keys] ? $FullGSTType[$count][$keys] : 0,
                                    'GSTSlab' => $FullGSTSlab[$count][$keys] ? $FullGSTSlab[$count][$keys] : 0,
                                    'Cost' => $FullCost[$count][$keys] ? $FullCost[$count][$keys] : 0,
                                    'TotalCost' => $FullTotalCost[$count][$keys] ? $FullTotalCost[$count][$keys] : 0,
                                    'IsSalesPrice' => $TYPE[$count][$keys] ? $TYPE[$count][$keys] : 0,
                                    'TPIntSysId' => $TravelPlan_ItenaryId ? $TravelPlan_ItenaryId : 0,
                                    'VersionId' => $TravelPlan_AccomId ? $TravelPlan_AccomId : 0,
                                    'CreatedDate' => $date,
                                    'UpdatedDate' => $date
                                );
                                //echo '<pre>'; print_r($userArray);
                                $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray);
                            }
                        }
                    }

                    $count++;
                }

                $response = array('success' => true, 'message' => ' Saved Successfully');
                echo json_encode($response);
                exit;
            }
            //echo "<pre>";print_r($getData);die;
        }
    }

    //this function used for update activity details in fullfillment created on 28 march 2017 at 03:07 PM
    public function updateActivityConfirmationAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($getData);die;
            //echo "<pre>";print_r($_FILES);
            //exit;
            $TPSysId = $this->_HtmlPurifier->filter(base64_decode($getData['id']));
            $aid = $this->_HtmlPurifier->filter(base64_decode($getData['aid']));
            $tpid = $this->_HtmlPurifier->filter(base64_decode($getData['tpid']));
            $vid = $this->_HtmlPurifier->filter(base64_decode($getData['vid']));
            $seqid = $this->_HtmlPurifier->filter(base64_decode($getData['seqid']));
            $activitytype = $this->_HtmlPurifier->filter($getData['activitytype']);
            $isincludedintransport = $this->_HtmlPurifier->filter($getData['isincludedintransport']);
            $vehiclename = isset($getData['vehiclename']) ? $this->_HtmlPurifier->filter($getData['vehiclename']) : '';
            $vehiclenamecontactperson = isset($getData['vehiclenamecontactperson']) ? $this->_HtmlPurifier->filter($getData['vehiclenamecontactperson']) : '';
            $vehiclenamecontactnumber = isset($getData['vehiclenamecontactnumber']) ? $this->_HtmlPurifier->filter($getData['vehiclenamecontactnumber']) : '';
            $vehiclevoucherno = isset($getData['vehiclevoucherno']) ? $this->_HtmlPurifier->filter($getData['vehiclevoucherno']) : '';
            $vehiclesuppliername = $this->_HtmlPurifier->filter($getData['vehiclesuppliername']);
            $vehiclesuppliernumber = $this->_HtmlPurifier->filter($getData['vehiclesuppliernumber']);
            $vehiclesupplieremail = isset($getData['vehiclesupplieremail']) ? $this->_HtmlPurifier->filter($getData['vehiclesupplieremail']) : '';
            $totalcost = $this->_HtmlPurifier->filter(@$getData['totalcost']);
            $updatevoucherno = $this->_HtmlPurifier->filter($getData['updatevoucherno']);
            $vehiclepickuptime = $getData['vehiclepickuptime'] ? $this->_HtmlPurifier->filter($getData['vehiclepickuptime']) : '';
            $vehicledroptime = $getData['vehicledroptime'] ? $this->_HtmlPurifier->filter($getData['vehicledroptime']) : '';
            $vehiclepickuplocation = $this->_HtmlPurifier->filter($getData['vehiclepickuplocation']);
            $vehiclepickuplocation_going_from = $this->_HtmlPurifier->filter($getData['vehiclepickuplocation_going_from']);
            $countryInputId = $this->_HtmlPurifier->filter($getData['countryInputId']);
            $updateremarks = $this->_HtmlPurifier->filter($getData['updateremarks']);
            $is_lead_avail = isset($getData['is_lead_avail']) ? $this->_HtmlPurifier->filter($getData['is_lead_avail']) : '';
            $eventType = isset($getData['eventType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['eventType'])) : '';

            $rowdata = $aid . "_" . $vid . "_" . $tpid;

            $title = '';
            if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
                //update booking info
                $ObjActivity = new Travel_Model_CRM_CustomerTravelItenaryEventsFullfillment();
                $where = "TPIntSysId = " . $tpid . " AND Sequence=" . $seqid . " AND VersionId=" . $vid . " AND TPActivitySysId=" . $aid;
                $date = date('Y-m-d H:i:s');
                if ($eventType == 'activityreadymade') {

                    //$isincludedintransport=0;
                    $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                    $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];
                    $vehiclepickuptime_exp = explode(" ", $vehiclepickuptime);
                    $vehicledroptime_exp = explode(" ", $vehicledroptime);
                    $vehiclepickuptime_exp_date = explode("/", $vehiclepickuptime_exp[0]);
                    $vehiclepickuptime_exp_date_time = '';
                    $vehicledroptime_exp_date_time = '';
                    //print_r($vehiclepickuptime_exp_date);
                    if ($vehiclepickuptime_exp_date[0] != '') {
                        $vehiclepickuptime_exp_date_time = $vehiclepickuptime_exp_date[2] . "-" . $vehiclepickuptime_exp_date[1] . "-" . $vehiclepickuptime_exp_date[0] . " " . $vehiclepickuptime_exp[1];
                    }
                    $vehicledroptime_exp_date = explode("/", $vehicledroptime_exp[0]);
                    if ($vehicledroptime_exp_date[0] != '') {
                        $vehicledroptime_exp_date_time = $vehicledroptime_exp_date[2] . "-" . $vehicledroptime_exp_date[1] . "-" . $vehicledroptime_exp_date[0] . " " . $vehicledroptime_exp[1];
                    }
                    $adult = $this->_HtmlPurifier->filter($getData['adult']);
                    $child = $this->_HtmlPurifier->filter($getData['child']);
                    $activitybookingconfirmed = $this->_HtmlPurifier->filter($getData['activitybookingconfirmed']);
                    $traveldate = $this->_HtmlPurifier->filter($getData['traveldate']);

                    $traveldate_exp_date = explode(" ", $traveldate);
                    $traveldate_exp_date_data = explode("/", $traveldate_exp_date[0]);
                    if ($traveldate_exp_date[0] != '') {
                        $traveldate = $traveldate_exp_date_data[2] . "-" . $traveldate_exp_date_data[1] . "-" . $traveldate_exp_date_data[0] . " " . $traveldate_exp_date[1];
                    }

                    if ($activitybookingconfirmed == 1) {
                        $statusId = 56;
                    } else {
                        $statusId = 60;
                    }
                    $userArray = array(
                        'ActivityType' => $activitytype,
                        'TravelDate' => $traveldate,
                        'TotalAdult' => $adult,
                        'TotalChild' => $child,
                        'IsActivityConfirmed' => $activitybookingconfirmed,
                        'IsIncludedInTransport' => $isincludedintransport,
                        'VehicleSupplierName' => $vehiclesuppliername,
                        'VehicleSupplierNumber' => $vehiclesuppliernumber,
                        'VehiclePickUpTime' => $vehiclepickuptime_exp_date_time,
                        'VehicleDropTime' => $vehicledroptime_exp_date_time,
                        'VehiclePickUpLocation' => $vehiclepickuplocation_going_from,
                        'XRefVoucherNo' => $updatevoucherno,
                        'StatusSysId' => $statusId,
                        'BookingRemarks' => $updateremarks ? addslashes(trim($updateremarks)) : '',
                        'UpdateDate' => $date,
                    );
                } else {
                    if ($isincludedintransport == 1) {
                        $isincludedintransport = 1;
                        $userArray = array(
                            'ActivityType' => $activitytype,
                            'IsIncludedInTransport' => $isincludedintransport,
                            'VehicleName' => $vehiclename ? addslashes(trim($vehiclename)) : '',
                            'VehicleContactPerson' => $vehiclenamecontactperson ? addslashes(trim($vehiclenamecontactperson)) : '',
                            'VehicleContactNumber' => $vehiclenamecontactnumber ? trim($vehiclenamecontactnumber) : '',
                            'BookingRemarks' => $updateremarks ? addslashes(trim($updateremarks)) : '',
                            'XRefVoucherNo' => $vehiclevoucherno,
                            'UpdateDate' => $date,
                        );
                    } else {
                        $isincludedintransport = $getData['isincludedintransport'] ? $this->_HtmlPurifier->filter($getData['isincludedintransport']) : 0;
                        $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                        $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];
                        $vehiclepickuptime_exp = explode(" ", $vehiclepickuptime);
                        $vehicledroptime_exp = explode(" ", $vehicledroptime);
                        $vehiclepickuptime_exp_date = explode("/", $vehiclepickuptime_exp[0]);
                        $vehiclepickuptime_exp_date_time = $vehiclepickuptime_exp_date[2] . "-" . $vehiclepickuptime_exp_date[1] . "-" . $vehiclepickuptime_exp_date[0] . " " . $vehiclepickuptime_exp[1];
                        $vehicledroptime_exp_date = explode("/", $vehicledroptime_exp[0]);
                        $vehicledroptime_exp_date_time = $vehicledroptime_exp_date[2] . "-" . $vehicledroptime_exp_date[1] . "-" . $vehicledroptime_exp_date[0] . " " . $vehicledroptime_exp[1];

                        $userArray = array(
                            'ActivityType' => $activitytype,
                            'IsIncludedInTransport' => $isincludedintransport,
                            'VehicleSupplierName' => $vehiclesuppliername,
                            'VehicleSupplierNumber' => $vehiclesuppliernumber,
                            'VehicleSupplierEmail' => $vehiclesupplieremail,
                            'VehiclePickUpTime' => $vehiclepickuptime_exp_date_time,
                            'VehicleDropTime' => $vehicledroptime_exp_date_time,
                            'VehiclePickUpLocation' => $vehiclepickuplocation_going_from,
                            'XRefVoucherNo' => $updatevoucherno,
                            'TotalCost' => $totalcost,
                            'UpdateDate' => $date,
                        );
                    }
                }
                //echo "<pre>";print_r($userArray);die;
                $Rcord = $ObjActivity->UpdateTravelItenaryEvents($userArray, $where);
                //#end of update booking info
                //update status
                $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
                //echo "<pre>";print_r($checkRecordExist);
                $statusId = 56;
                $date = date('Y-m-d H:i:s');
                if (!empty($checkRecordExist)) {
                    $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                    $userArray = array(
                        'StatusSysId' => $statusId,
                        //'SupplierSysId' => isset($hotelSupplierSysId)?$hotelSupplierSysId:0,
                        //'OnCallSupRemarks' => $hotelremarks,
                        //'EmailText' => $emailText,
                        'UpdatedOn' => $date,
                    );
                    $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
                } else {
                    $objPackage = new Travel_Model_TblPackage();
                    $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                    //echo "<pre>";print_r($flexiPackageItenList);	
                    $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                    $userArray = array(
                        'TPSysId' => $TPSysId,
                        'TPIntSysId' => $TPIntSysId,
                        'SupplierSysId' => isset($hotelSupplierSysId) ? $hotelSupplierSysId : 0,
                        'ItemSysId' => $aid,
                        'IsSupAvalOnCall' => 0,
                        'OnCallSupRateValidTill' => '',
                        'OnCallSupRemarks' => '',
                        'StatusSysId' => $statusId,
                        'CreatedOn' => $date,
                        'UpdatedOn' => $date,
                        'IsActive' => 1,
                        'AgencySysId' => $agencysysID,
                        'IsSupAvalOnCall' => '',
                        'OnCallSupRate' => 0,
                        'OnCallSupRooms' => 0,
                        'OnCallSupRateFrom' => $date,
                        'OnCallSupRateTo' => $date,
                        'OnCallSupRateValidTill' => $date,
                        'OnCallSupRemarks' => $updateremarks,
                        //'EmailText' => $emailText,
                        'IsMarkForDel' => 0
                    );
                    //echo "<pre>";print_r($userArray);
                    $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
                }
                $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
                $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
                //print_r($statusArray);
                $title = $statusArray;
                //# update status 

                $msg = "success";
            } else {
                $msg = "failed";
            }
        }
        echo json_encode(array('status' => $msg, 'title' => stripslashes($title), 'rowdata' => stripslashes($rowdata)));
        exit;
    }

    //this function used for update sightseeing details in fullfillment created on 28 march 2017 at 04:07 PM
    public function updateSightseeingConfirmationAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($getData);die;
            //echo "<pre>";print_r($_FILES);
            //exit;
            $TPSysId = $this->_HtmlPurifier->filter(base64_decode($getData['id']));
            $aid = $this->_HtmlPurifier->filter(base64_decode($getData['aid']));
            $tpid = $this->_HtmlPurifier->filter(base64_decode($getData['tpid']));
            $vid = $this->_HtmlPurifier->filter(base64_decode($getData['vid']));
            $seqid = $this->_HtmlPurifier->filter(base64_decode($getData['seqid']));
            $sightseeingtype = $this->_HtmlPurifier->filter($getData['sightseeingtype']);
            $isincludedintransport = $this->_HtmlPurifier->filter($getData['isincludedintransport']);
            $vehiclename = isset($getData['vehiclename']) ? $this->_HtmlPurifier->filter($getData['vehiclename']) : '';
            $vehiclenamecontactperson = isset($getData['vehiclenamecontactperson']) ? $this->_HtmlPurifier->filter($getData['vehiclenamecontactperson']) : '';
            $vehiclenamecontactnumber = isset($getData['vehiclenamecontactnumber']) ? $this->_HtmlPurifier->filter($getData['vehiclenamecontactnumber']) : '';
            $vehiclevoucherno = isset($getData['vehiclevoucherno']) ? $this->_HtmlPurifier->filter($getData['vehiclevoucherno']) : '';
            $vehiclesuppliername = $this->_HtmlPurifier->filter($getData['vehiclesuppliername']);
            $vehiclesuppliernumber = $this->_HtmlPurifier->filter($getData['vehiclesuppliernumber']);
            $vehiclesupplieremail = isset($getData['vehiclesupplieremail']) ? $this->_HtmlPurifier->filter($getData['vehiclesupplieremail']) : '';
            $totalcost = $this->_HtmlPurifier->filter(@$getData['totalcost']);
            $updatevoucherno = $this->_HtmlPurifier->filter($getData['updatevoucherno']);
            $vehiclepickuptime = $getData['vehiclepickuptime'] ? $this->_HtmlPurifier->filter($getData['vehiclepickuptime']) : '';
            $vehicledroptime = $getData['vehicledroptime'] ? $this->_HtmlPurifier->filter($getData['vehicledroptime']) : '';
            $vehiclepickuplocation = $this->_HtmlPurifier->filter($getData['vehiclepickuplocation']);
            $vehiclepickuplocation_going_from = $this->_HtmlPurifier->filter($getData['vehiclepickuplocation_going_from']);
            $countryInputId = $this->_HtmlPurifier->filter($getData['countryInputId']);
            $updateremarks = $this->_HtmlPurifier->filter($getData['updateremarks']);
            $is_lead_avail = isset($getData['is_lead_avail']) ? $this->_HtmlPurifier->filter($getData['is_lead_avail']) : '';
            $eventType = isset($getData['eventType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['eventType'])) : '';

            $rowdata = $aid . "_" . $vid . "_" . $tpid;

            $title = '';
            if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
                //update booking info
                $ObjSightseeing = new Travel_Model_CRM_CustomerTravelItenarySightSeeingFullfillment();
                $where = "TPIntSysId = " . $tpid . " AND SeqId=" . $seqid . " AND VersionId=" . $vid . " AND SSSysId=" . $aid;
                $date = date('Y-m-d H:i:s');

                if ($eventType == 'sightseeingreadymade') {

                    $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                    $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];
                    $vehiclepickuptime_exp = explode(" ", $vehiclepickuptime);
                    $vehicledroptime_exp = explode(" ", $vehicledroptime);
                    $vehiclepickuptime_exp_date = explode("/", $vehiclepickuptime_exp[0]);
                    $vehiclepickuptime_exp_date_time = '';
                    $vehicledroptime_exp_date_time = '';
                    if ($vehiclepickuptime_exp_date[0] != '') {
                        $vehiclepickuptime_exp_date_time = $vehiclepickuptime_exp_date[2] . "-" . $vehiclepickuptime_exp_date[1] . "-" . $vehiclepickuptime_exp_date[0] . " " . $vehiclepickuptime_exp[1];
                    }

                    //$vehiclepickuptime_exp_date_time=$vehiclepickuptime_exp_date[2]."-".$vehiclepickuptime_exp_date[1]."-".$vehiclepickuptime_exp_date[0]." ".$vehiclepickuptime_exp[1];
                    $vehicledroptime_exp_date = explode("/", $vehicledroptime_exp[0]);
                    if ($vehicledroptime_exp_date[0] != '') {
                        $vehicledroptime_exp_date_time = $vehicledroptime_exp_date[2] . "-" . $vehicledroptime_exp_date[1] . "-" . $vehicledroptime_exp_date[0] . " " . $vehicledroptime_exp[1];
                    }
                    //$vehicledroptime_exp_date_time=$vehicledroptime_exp_date[2]."-".$vehicledroptime_exp_date[1]."-".$vehicledroptime_exp_date[0]." ".$vehicledroptime_exp[1];
                    $adult = $this->_HtmlPurifier->filter($getData['adult']);
                    $child = $this->_HtmlPurifier->filter($getData['child']);
                    $sightseeingbookingconfirmed = $this->_HtmlPurifier->filter($getData['sightseeingbookingconfirmed']);
                    $isincludedintransport = $getData['isincludedintransport'] ? $this->_HtmlPurifier->filter($getData['isincludedintransport']) : 0;
                    $traveldate = $this->_HtmlPurifier->filter($getData['traveldate']);
                    $traveldate_exp = explode(" ", $traveldate);
                    $traveldate_new_array = explode("/", $traveldate_exp[0]);
                    $traveldate_new = $traveldate_new_array[2] . "-" . $traveldate_new_array[1] . "-" . $traveldate_new_array[0] . " " . $traveldate_exp[1];
                    if ($sightseeingbookingconfirmed == 1) {
                        $statusId = 56;
                    } else {
                        $statusId = 60;
                    }

                    $userArray = array(
                        'SightSeeingType' => $sightseeingtype,
                        'TravelDate' => $traveldate_new,
                        'TotalAdult' => $adult,
                        'TotalChild' => $child,
                        'IsSightSeeingConfirmed' => $sightseeingbookingconfirmed,
                        'IsIncludedInTransport' => $isincludedintransport,
                        'VehicleSupplierName' => $vehiclesuppliername,
                        'VehicleSupplierNumber' => $vehiclesuppliernumber,
                        'VehiclePickUpTime' => $vehiclepickuptime_exp_date_time,
                        'VehicleDropTime' => $vehicledroptime_exp_date_time,
                        'VehiclePickUpLocation' => $vehiclepickuplocation_going_from,
                        'XRefVoucherNo' => $updatevoucherno,
                        'StatusSysId' => $statusId,
                        'BookingRemarks' => $updateremarks ? addslashes(trim($updateremarks)) : '',
                        'UpdateDate' => $date,
                    );
                } else {
                    if ($isincludedintransport == 1) {
                        $isincludedintransport = 1;
                        $userArray = array(
                            'SightSeeingType' => $sightseeingtype,
                            'IsIncludedInTransport' => $isincludedintransport,
                            'VehicleName' => $vehiclename ? addslashes(trim($vehiclename)) : '',
                            'VehicleContactPerson' => $vehiclenamecontactperson ? addslashes(trim($vehiclenamecontactperson)) : '',
                            'VehicleContactNumber' => $vehiclenamecontactnumber ? trim($vehiclenamecontactnumber) : '',
                            'BookingRemarks' => $updateremarks ? addslashes(trim($updateremarks)) : '',
                            'XRefVoucherNo' => $vehiclevoucherno,
                            'UpdateDate' => $date,
                        );
                    } else {
                        $isincludedintransport = 0;
                        $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                        $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];
                        $vehiclepickuptime_exp = explode(" ", $vehiclepickuptime);
                        $vehicledroptime_exp = explode(" ", $vehicledroptime);
                        $vehiclepickuptime_exp_date = explode("/", $vehiclepickuptime_exp[0]);
                        $vehiclepickuptime_exp_date_time = $vehiclepickuptime_exp_date[2] . "-" . $vehiclepickuptime_exp_date[1] . "-" . $vehiclepickuptime_exp_date[0] . " " . $vehiclepickuptime_exp[1];
                        $vehicledroptime_exp_date = explode("/", $vehicledroptime_exp[0]);
                        $vehicledroptime_exp_date_time = $vehicledroptime_exp_date[2] . "-" . $vehicledroptime_exp_date[1] . "-" . $vehicledroptime_exp_date[0] . " " . $vehicledroptime_exp[1];

                        $userArray = array(
                            'SightSeeingType' => $sightseeingtype,
                            'IsIncludedInTransport' => $isincludedintransport,
                            'VehicleSupplierName' => $vehiclesuppliername,
                            'VehicleSupplierNumber' => $vehiclesuppliernumber,
                            'VehicleSupplierEmail' => $vehiclesupplieremail,
                            'VehiclePickUpTime' => $vehiclepickuptime_exp_date_time,
                            'VehicleDropTime' => $vehicledroptime_exp_date_time,
                            'VehiclePickUpLocation' => $vehiclepickuplocation_going_from,
                            'XRefVoucherNo' => $updatevoucherno,
                            'BookingRemarks' => $updateremarks ? addslashes(trim($updateremarks)) : '',
                            'TotalCost' => $totalcost,
                            'UpdateDate' => $date,
                        );
                    }
                }
                //echo "<pre>";print_r($userArray);
                $Rcord = $ObjSightseeing->UpdateTravelSightSeeing($userArray, $where);
                //#end of update booking info
                //update status
                $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
                //echo "<pre>";print_r($checkRecordExist);
                $statusId = 56;
                $date = date('Y-m-d H:i:s');
                if (!empty($checkRecordExist)) {
                    $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                    $userArray = array(
                        'StatusSysId' => $statusId,
                        //'SupplierSysId' => isset($hotelSupplierSysId)?$hotelSupplierSysId:0,
                        //'OnCallSupRemarks' => $hotelremarks,
                        //'EmailText' => $emailText,
                        'UpdatedOn' => $date,
                    );
                    //echo "<pre>";print_r($userArray);
                    $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
                } else {
                    $objPackage = new Travel_Model_TblPackage();
                    $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                    //echo "<pre>";print_r($flexiPackageItenList);	
                    $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                    $userArray = array(
                        'TPSysId' => $TPSysId,
                        'TPIntSysId' => $TPIntSysId,
                        'SupplierSysId' => isset($hotelSupplierSysId) ? $hotelSupplierSysId : 0,
                        'ItemSysId' => $aid,
                        'IsSupAvalOnCall' => 0,
                        'OnCallSupRateValidTill' => '',
                        'OnCallSupRemarks' => '',
                        'StatusSysId' => $statusId,
                        'CreatedOn' => $date,
                        'UpdatedOn' => $date,
                        'IsActive' => 1,
                        'AgencySysId' => $agencysysID,
                        'IsSupAvalOnCall' => '',
                        'OnCallSupRate' => 0,
                        'OnCallSupRooms' => 0,
                        'OnCallSupRateFrom' => $date,
                        'OnCallSupRateTo' => $date,
                        'OnCallSupRateValidTill' => $date,
                        'OnCallSupRemarks' => $updateremarks,
                        //'EmailText' => $emailText,
                        'IsMarkForDel' => 0
                    );
                    //echo "<pre>";print_r($userArray);
                    $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
                }
                $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
                $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
                //print_r($statusArray);
                $title = $statusArray;
                //# update status 

                $msg = "success";
            } else {
                $msg = "failed";
            }
        }
        echo json_encode(array('status' => $msg, 'title' => stripslashes($title), 'rowdata' => addslashes($rowdata)));
        exit;
    }

    //this function used for update transport details in fullfillment created on 28 march 2017 at 06:19 PM
    public function updateTransportConfirmationAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $agencysysID = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($getData);die;
            //echo "<pre>";print_r($_FILES);
            //exit;
            $TPSysId = $this->_HtmlPurifier->filter(base64_decode($getData['id']));
            $aid = $this->_HtmlPurifier->filter(base64_decode($getData['aid']));
            $tpid = $this->_HtmlPurifier->filter(base64_decode($getData['tpid']));
            $seqid = $this->_HtmlPurifier->filter(base64_decode($getData['seqid']));
            $eventType = isset($getData['eventType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['eventType'])) : '';
            $vehiclename = $this->_HtmlPurifier->filter($getData['vehiclename']);
            $travelDateFrom = $getData['travelDateFrom'] ? $this->_HtmlPurifier->filter($getData['travelDateFrom']) : '';
            $travelDateTo = $getData['travelDateTo'] ? $this->_HtmlPurifier->filter($getData['travelDateTo']) : '';
            $vehiclepickuplocation_going_from = $this->_HtmlPurifier->filter($getData['vehiclepickuplocation_going_from']);
            $countryInputId = $this->_HtmlPurifier->filter($getData['countryInputId']);
            $pickuplocation = $this->_HtmlPurifier->filter($getData['pickuplocation']);
            $pickupremarks = $this->_HtmlPurifier->filter($getData['pickupremarks']);
            $countryInputId = $this->_HtmlPurifier->filter($getData['countryInputId']);
            $vehicledroplocation_going_from = $this->_HtmlPurifier->filter($getData['vehicledroplocation_going_from']);
            $droplocation = $this->_HtmlPurifier->filter($getData['droplocation']);
            $dropremarks = $this->_HtmlPurifier->filter($getData['dropremarks']);
            $suppliername = $this->_HtmlPurifier->filter($getData['suppliername']);
            $suppliernumber = $this->_HtmlPurifier->filter($getData['suppliernumber']);
            $totalcost = $this->_HtmlPurifier->filter($getData['totalcost']);
            $remarks = $this->_HtmlPurifier->filter($getData['remarks']);
            $emailbody = $this->_HtmlPurifier->filter($getData['emailbody']);
            $sendtoemailid = $this->_HtmlPurifier->filter($getData['sendtoemailid']);

            if (isset($TPSysId) && !empty($TPSysId) && is_numeric($TPSysId) > 0) {
                //update booking info
                $ObjActivity = new Travel_Model_CRM_CustomerTravelPlanFixedFullfillment();
                $where = "TPIntSysId = " . $tpid . " AND Sequence=" . $seqid . " AND FixTransSysId=" . $aid;
                $date = date('Y-m-d H:i:s');

                $vehiclepickuplocation_going_from = explode("__", $vehiclepickuplocation_going_from);
                $vehiclepickuplocation_going_from = $vehiclepickuplocation_going_from[0];

                $vehicledroplocation_going_from = explode("__", $vehicledroplocation_going_from);
                $vehicledroplocation_going_from = $vehicledroplocation_going_from[0];

                $traveldatefrom_exp = explode(" ", $travelDateFrom);
                $traveldateto_exp = explode(" ", $travelDateTo);
                $traveldatefrom_exp_date = explode("/", $traveldatefrom_exp[0]);
                $traveldatefrom_exp_date_time = $traveldatefrom_exp_date[2] . "-" . $traveldatefrom_exp_date[1] . "-" . $traveldatefrom_exp_date[0] . " " . $traveldatefrom_exp[1];
                $traveldateto_exp_date = explode("/", $traveldateto_exp[0]);
                $traveldateto_exp_date_time = $traveldateto_exp_date[2] . "-" . $traveldateto_exp_date[1] . "-" . $traveldateto_exp_date[0] . " " . $traveldateto_exp[1];

                $userArray = array(
                    'VehicleName' => $vehiclename,
                    'TravelDateFrom' => $traveldatefrom_exp_date_time,
                    'TravelDateTo' => $traveldateto_exp_date_time,
                    'PickUpCity' => $vehiclepickuplocation_going_from,
                    'PickUpLocation' => $pickuplocation,
                    'PickUpRemarks' => $pickupremarks,
                    'DropCity' => $vehicledroplocation_going_from,
                    'DropLocation' => $droplocation,
                    'DropRemarks' => $dropremarks,
                    'SupplierName' => $suppliername,
                    'SupplierNumber' => $suppliernumber,
                    'TotalCost' => $totalcost,
                    'Remarks' => $remarks,
                    'EmailText' => $emailbody,
                    'SendToEmailId' => $sendtoemailid,
                    'UpdateDate' => $date,
                );

                //echo "<pre>";print_r($userArray);
                $Rcord = $ObjActivity->UpdateTravelPlanFixedTrans($userArray, $where);
                //#end of update booking info
                //update status
                $supplierOnCallObj = new Travel_Model_CRM_AgencyCustomerReqSupplierOnCall();
                $checkRecordExist = $supplierOnCallObj->ChkRecordExist($TPSysId, $aid);
                //echo "<pre>";print_r($checkRecordExist);
                $statusId = 55; //57 for voucher updated
                $date = date('Y-m-d H:i:s');
                if (!empty($checkRecordExist)) {
                    $where = "ReqSupplierOnCall = " . $checkRecordExist[0]['ReqSupplierOnCall'];
                    $userArray = array(
                        'StatusSysId' => $statusId,
                        //'SupplierSysId' => isset($hotelSupplierSysId)?$hotelSupplierSysId:0,
                        //'OnCallSupRemarks' => $hotelremarks,
                        //'EmailText' => $emailText,
                        'UpdatedOn' => $date,
                    );
                    $Rcord = $supplierOnCallObj->UpdateReqSupplierOnCall($userArray, $where);
                } else {
                    $objPackage = new Travel_Model_TblPackage();
                    $flexiPackageItenList = $objPackage->getCustPackageItenList($TPSysId);
                    //echo "<pre>";print_r($flexiPackageItenList);	
                    $TPIntSysId = isset($tpid) ? $tpid : $flexiPackageItenList[0]['TPIntSysId'];
                    $userArray = array(
                        'TPSysId' => $TPSysId,
                        'TPIntSysId' => $TPIntSysId,
                        'SupplierSysId' => isset($hotelSupplierSysId) ? $hotelSupplierSysId : 0,
                        'ItemSysId' => $aid,
                        'IsSupAvalOnCall' => 0,
                        'OnCallSupRateValidTill' => '',
                        'OnCallSupRemarks' => '',
                        'StatusSysId' => $statusId,
                        'CreatedOn' => $date,
                        'UpdatedOn' => $date,
                        'IsActive' => 1,
                        'AgencySysId' => $agencysysID,
                        'IsSupAvalOnCall' => '',
                        'OnCallSupRate' => 0,
                        'OnCallSupRooms' => 0,
                        'OnCallSupRateFrom' => $date,
                        'OnCallSupRateTo' => $date,
                        'OnCallSupRateValidTill' => $date,
                        'OnCallSupRemarks' => $remarks,
                        //'EmailText' => $emailText,
                        'IsMarkForDel' => 0
                    );
                    //echo "<pre>";print_r($userArray);
                    $Rcord = $supplierOnCallObj->addReqSupplierOnCall($userArray);
                }
                $objTravelPlanStatus = new Travel_Model_CRM_TravelPlanStatus();
                $statusArray = $objTravelPlanStatus->GetTravelPlanStatusByTypeName(4, $statusId);
                //print_r($statusArray);
                $title = $statusArray;
                //# update status 
                //send email to supplier
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($agencysysID);
                $getAgentDetail = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
                $sessionLogin_agnet_details = new Zend_Session_Namespace('sessionLogin_user');
                $cc = trim($getAgentDetail['EmailId']);
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/publicpackage/');
                // render view
                $html->assign('type', 'sendTransportDynamicEnquiryDetail');
                $html->assign('enquiryType', $eventType);
                if ((int) $suppId > 0) {
                    $objSupplier = new Travel_Model_TblSupplier();
                    $objSupplier->SupplierSysId = $suppId;
                    $pkgSupplierDetails = $objSupplier->getSuppliersDetailsById((int) $suppId);
                }
                $html->assign('agencyDetails', $getAgencyDetail);
                $html->assign('agentDetails', $getAgentDetail);
                $html->assign('supplierDetails', @$pkgSupplierDetails);
                //echo "<pre>";print_r($getAgentDetail);
                $html->assign('data', @$allData);
                $html->assign('emailText', $emailbody);
                $bodyText = $html->render('ajax-html.phtml');
                //$sendtoemailid='amit.k@catpl.co.in';
                $emailId = $sendtoemailid;
                $fromName = $this->fromName;
                $fromEmail = $this->fromEmail;
                $subject = 'Transport Enquiry Details-' . $TPSysId;
                $emailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($emailId)), 'bodyHtml' => $bodyText, 'bodyText' => '');
                $emailData_Agent = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subject, 'to' => array(trim($getAgentDetail['EmailId'])), 'bodyHtml' => $bodyText, 'bodyText' => '');

                try {
                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $arrEmailStatistics = array(
                        "TPSysId" => $TPSysId,
                        "TypeSysId" => 1, // 1 For Email 2 For SMS
                        "AgencySysId" => $agencysysID,
                        "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                        "Title" => $bodyText,
                        "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                    );
                    $this->mailSentByElastice($emailData, $arrEmailStatistics);
                    $this->mailSentByElastice($emailData_Agent, $arrEmailStatistics, 0, 0);
                    //insert data for sent email
                    $dataArray = array(
                        "TPSysId" => $TPSysId,
                        "TPIntSysId" => 1, // 1 For Email 2 For SMS
                        "AgencySysId" => $agencysysID,
                        "SupplierSysId" => isset($suppId) ? $suppId : 0,
                        "InvnItemSysId" => $aid,
                        "ItemSysId" => $aid,
                        "AgentSysId" => $sessionLogin_user->intLoggedinUserId,
                        "EmailTextFromAgent" => $bodyText,
                        "FromName" => $fromName,
                        "FromEmail" => $fromEmail,
                        "EmailTo" => $emailId,
                        "EmailSubject" => $subject,
                        "IsReplyFromSupplier" => 0,
                        "IsQueryConfirmed" => 0,
                        "EmailQueryType" => 2, // 2 for hotel
                        "PlanType" => 5, // for package
                        "IsActive" => 1,
                        "IsMarkForDelete" => 0,
                        "StatusSysId" => 0,
                        "CreatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss'),
                        "UpdatedOn" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                    );
                    //print_r($dataArray);
                    try {
                        $insertEmailData = $supplierOnCallObj->insertData('TB_Agency_Customer_SupplierEmail_Fullfillment', $dataArray);
                    } catch (Exception $err) {
                        print_r($err, true);
                    }
                    //echo 'Email has sent to customer';
                } catch (Exception $err) {
                    print_r($err, true);
                }

                $msg = "success";
            } else {
                $msg = "failed";
            }
        }
        echo json_encode(array('status' => $msg, 'title' => stripslashes($title)));
        exit;
    }

    function getCostBreakupAction() {
//        error_reporting(E_ALL);
        $this->_helper->layout->disableLayout();
        $getData = $this->getRequest()->getPost();
        $AgencyMarkupPersentage = 0;
        $NetworkExtraMarkup = 0;
//          echo '<pre>';print_r($getData); echo '</pre>';exit;
        //            $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $exchangeRate = ((float) $_REQUEST['ExchangeRate'] != 0) ? $_REQUEST['ExchangeRate'] : 1;
        $GTXNetworkAgencySysId = ((float) $_REQUEST['GTXNetworkAgencySysId'] != 0) ? $_REQUEST['GTXNetworkAgencySysId'] : 0;
        $objPackage = new Travel_Model_TblPackage();
        $packid = $_REQUEST['packid'];
        $MpType = $_REQUEST['MpType'];
        $travelers = $_REQUEST['travelers'];
        $type = $this->getRequest()->getParam('type');
        $optionalSightInclude = array();
        if (isset($_REQUEST['optionalSightInclude']) && ($_REQUEST['optionalSightInclude'] != "")) {
            $optionalSightIncludeR = $_REQUEST['optionalSightInclude'];
            $base64encodedoptionalSS = base64_decode($optionalSightIncludeR);
            $jsonDecodeencodedoptionalSS = json_decode($base64encodedoptionalSS);
            if (!empty($jsonDecodeencodedoptionalSS) && ($jsonDecodeencodedoptionalSS != '')) {
                $optionalSightInclude = implode(', ', $jsonDecodeencodedoptionalSS);
            }
        }

        $IsFixedDeparturePackage = isset($_REQUEST['IsFixedDeparturePackage']) ? (int) $_REQUEST['IsFixedDeparturePackage'] : 0;
        if ($IsFixedDeparturePackage == 1) {
            
        }
        if ($type == 'customer') {
            $objCust = new Travel_Model_CRM_CustomerTravelPlan();
            $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', $_REQUEST['pkgCheckInDate'])));
            $PackageArray = $objCust->GetTravelPlanByCustomer($packid);
            $NetworkExtraMarkup = isset($PackageArray[0]['NetworkExtraMarkup']) ? (float) $PackageArray[0]['NetworkExtraMarkup'] : 0;
            $strRoomInfoJson = $PackageArray[0]['RoomInfoJson'];
            $roomInfo = json_decode($PackageArray[0]['RoomInfoJson']);
            //             print_r($roomInfo);
            $totaladult = $totalchild = 0;
            foreach ($roomInfo as $room) {
                $totaladult = $totaladult + $room->Adult;
                $totalchild = $totalchild + $room->Child;
            }
            $MarketPlaceId = ($PackageArray[0]['IsB2BAgent'] == 1 || $PackageArray[0]['IsGTXNetwork'] == 1) ? 2 : 1;
            //            echo '<pre>';print_r($PackageArray[0]['IsB2BAgent']);
            // $MarketPlaceId = 1;

            if ($PackageArray[0]['PackSpecType'] == 3) {
                $packRate = $objCust->getCustTravelPackRate($packid, $tripdate, $MarketPlaceId);
                $packMPRate = $objCust->getCustPackRate($packid, $tripdate, $MarketPlaceId);
            } else {
                $packRate = $objCust->getCustTravelPackRateRowWise($packid, $tripdate, $MarketPlaceId, $totaladult);
                $packMPRate = $objCust->getCustPackRateRowWise($packid, $tripdate, $MarketPlaceId, $totaladult);
            }
            //echo '<pre>';print_r($packRate);echo '</pre>'; exit;
            if (!empty($optionalSightInclude)) {
                $ssdaywisearr = $objCust->getFlexiPackageOptionalSightseenListByItenarary($itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $tripdate, $optionalSightInclude);
            }
            $GetPackageFLightData = $objCust->GetPackageFLightData($packid);
            // echo "<pre>";print_r($GetPackageFLightData);
//            $encodedata = array();
//            if (!empty($GetPackageFLightData)) {
//                foreach ($GetPackageFLightData as $fKey => $fVal) {
//                    $encodedata[] = json_decode($fVal['encodedata'], 1);
//                }
//            }
            // echo "<pre>";print_r($encodedata);exit;
            $AgencySysId = $PackageArray[0]['AgencySysId'];
            $arrPkg['EconomyMask'] = $PackageArray[0]['EconomyMask'];
            $arrPkg['PackSpecType'] = $PackageArray[0]['PackSpecType'];
            $arrPkg['PKqueryType'] = $PackageArray[0]['PKqueryType'];
            $arrPkg['isShareWithFlight'] = $PackageArray[0]['isShareWithFlight'];
            $arrPkg['ShareCombinedFlightPricing'] = $PackageArray[0]['ShareCombinedFlightPricing'];
            $arrPkg['EmailText'] = $PackageArray[0]['EmailText'];
            $arrPkg['package_flightdetails'] = $GetPackageFLightData;
            $arrPkg['page'] = 'public';
            $customerSysId = isset($PackageArray[0]['CustomerSysId']) ? (int) $PackageArray[0]['CustomerSysId'] : 0;
            $AgencyMarkupPersentage = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getB2bAgencyMarkPercentage($customerSysId);
            $getTravelPlanAddonServices = $objPackage->getTravelPlanAddonServicesMultipleIds($AgencySysId, $packid, array(6, 21, 19));
            $this->view->getTravelPlanAddonServices = $getTravelPlanAddonServices;
            $totalGSTPrice = (float) $PackageArray[0]['XServiceTaxAmount'] + (float) $PackageArray[0]['AgentServiceTaxAmount'] + (float) $PackageArray[0]['AgentsCustomServiceTaxAmount'] - (float) $PackageArray[0]['ServiceTaxOnCustomDiscount'];
            //            echo "<pre>";print_r($getTravelPlanAddonServices);exit;
        } else {
            $MarketPlaceId = !empty($MpType) ? $MpType : 1;
            $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripstartdate'])));
            // $packRate = $objPackage->getPackRate($packid, $tripdate, $MarketPlaceId);
            // $packMPRate = $objPackage->getPackMPRate($packid, $travelers, $tripdate, $MarketPlaceId);
            $roomjson = array();
            $userSysId = isset($_REQUEST['aId']) ? (int) $_REQUEST['aId'] : 0;
            $AgencyMarkupPersentage = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getMarkPercentageForAgent($userSysId);
            $totaladult = $totalchild = $totalInfant = 0;
            $roomlp = $this->_request->getParam('roomlp') ? $this->_request->getParam('roomlp') : '';
            for ($k = 1; $k <= $roomlp; $k++) {
                $roomjson[$k]['Adult'] = $this->_request->getParam('adult_' . $k);
                $roomjson[$k]['adult_type'] = $this->_request->getParam('adult_type_' . $k);
                if ($roomjson[$k]['Adult'] == 3) {
                    $roomjson[$k]['AdultBedType'] = $this->_request->getParam('adultcl_extrabed_' . $k . '_3');
                }
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $this->_request->getParam('child_' . $k);
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['Infant'] = $this->_request->getParam('infant_' . $k);
                $totalInfant = $totalInfant + $roomjson[$k]['Infant'];
                for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                    $roomjson[$k]['ChildAge_' . $j] = $this->_request->getParam('child_age_' . $k . '_' . $j);
                    $roomjson[$k]['ChildBedType_' . $j] = $this->_request->getParam('child_extrabed_' . $k . '_' . $j);
                }
            }
            $strRoomInfoJson = json_encode($roomjson);
            $packRate = $objPackage->getPackRateRowWise($packid, $tripdate, $MarketPlaceId, (int) $totaladult, $strRoomInfoJson);

            $packMPRate = $objPackage->getPackMPRateRowWise($packid, $travelers, $tripdate, $MarketPlaceId, (int) $totaladult);
            $travelers = $totaladult + $totalchild;

            if (!empty($optionalSightInclude)) {
                $ssdaywisearr = $objPackage->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $tripdate, $optionalSightInclude);
            }
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
            $ShareCombinedPricing = !empty($getData['ShareCombinedPricing']) ? $getData['ShareCombinedPricing'] : 0;
            $isShareWithFlight = !empty($getData['isShareWithFlight']) ? $getData['isShareWithFlight'] : 0;
            $arrPkg['isShareWithFlight'] = $isShareWithFlight;
            $arrPkg['ShareCombinedFlightPricing'] = $ShareCombinedPricing;
            $arrPkg['package_flightdetails'] = isset($_SESSION['package_flightdetails']) ? $_SESSION['package_flightdetails'] : '';
            if (!empty($GTXNetworkAgencySysId)) {
                $objAgency = new Travel_Model_TblAgency();
                $getAgencyDetail = $objAgency->getAgencyUserList($AgencySysId);
                $NetworkExtraMarkup = $getAgencyDetail['MarkUpOnGTXNetworkPackage'];
            }
            $totalGSTPrice = !empty($getData['taxAmount']) ? $getData['taxAmount'] : 0;
        }

        $objActivities = new Travel_Model_TblActivities();
        $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($AgencySysId, $MpType);
        //        echo '<pre>'; print_r($PackageArray);echo '</pre>';
        $totalactcost = $totalactmarkup = 0;
        if (!empty($ssdaywisearr)) {
            foreach ($ssdaywisearr as $sightDetailsArr) {
                $TotalCostArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getReadymadeOptionalSightseeingRatesnMarkup($sightDetailsArr, $arrStandardMarkups);

                $totalactcost += ($totalchild * $TotalCostArr['ChildCost']) + ($totaladult * $TotalCostArr['AdultCost']);
                $totalactmarkup += ($totalchild * $TotalCostArr['ChildCostMarkup']) + ($totaladult * $TotalCostArr['AdultCostMarkup']);
            }
        }
        //        print_r($totalactcost+$totalactmarkup);
        $gstArr = $getData['gsttype'];
        $gsttypeF = $TcsTaxSysIdF = $TcsTaxSysIdP = $gsttypeP = 0;
        foreach ($gstArr as $key => $getValue) {
            if ($key == 1) {
                $gsttypeF = $getValue ? $getValue : '';
                $SACCodeF = $getData['sac_code'][$key] ? $getData['sac_code'][$key] : 440063; // default value 440063 for Tour Oprators..
                $TcsTaxSysIdF = isset($getData['TcsTaxSysId'][$key]) ? $getData['TcsTaxSysId'][$key] : 0;
            } else {
                $TcsTaxSysIdP = isset($getData['TcsTaxSysId'][$key]) ? $getData['TcsTaxSysId'][$key] : 0;
                $gsttypeP = $getData['gsttype'][$key] ? $getData['gsttype'][$key] : '';
                $SACCodeP = $getValue ? $getValue : 440063; // default value 440063 for Tour Oprators.. 
            }
        }
        $arrPkg['DiscountType'] = 0;
        $arrPkg['DiscountVal'] = 0;
        $arrPkg['AdvBookingPercent'] = $_REQUEST['AdvBookingPercent'];
        $arrPkg['ShareCurrency'] = $_REQUEST['ShareCurrency'];
        if (@$PackageArray[0]['IsShared'] == 1) {
            if (($PackageArray[0]['EconomyMask'] == 6 || $PackageArray[0]['EconomyMask'] == 7 || $PackageArray[0]['EconomyMask'] == 8)) {
                $arrPkg['ExtraMarkup'] = $PackageArray[0]['ExtraMarkUp'];
            } else {
                $arrPkg['ExtraMarkup'] = $PackageArray[0]['MarkUp'];
            }
            $arrPkg['ExtraDiscount'] = $PackageArray[0]['CustomDiscount'];
        } else {
            $arrPkg['ExtraMarkup'] = !empty($_REQUEST['MarkUp'][0]) ? $_REQUEST['MarkUp'][0] : 0;
            $arrPkg['ExtraDiscount'] = !empty($_REQUEST['discountValue'][0]) ? $_REQUEST['discountValue'][0] : 0;
        }
        $arrPkg['sac_code'] = !empty($SACCodeP) ? $SACCodeP : @$PackageArray[0]['SACCode'];
        $arrPkg['gsttype'] = !empty($gsttypeP) ? $gsttypeP : @$PackageArray[0]['GSTSharedMode'];
        $arrPkg['IsShareWithGST'] = (isset($getData['GSTIncluded']) && !empty((int) $getData['GSTIncluded'])) ? (int) $getData['GSTIncluded'] : $PackageArray[0]['IsShareWithGST'];

        $isShareWithFlight = isset($isShareWithFlight) ? $isShareWithFlight : '';
        $this->view->isShareWithFlight = $isShareWithFlight;
        $this->view->GSTSharedModes = isset($gsttypeP) ? trim($gsttypeP) : @$PackageArray[0]['GSTSharedMode'];

        // echo "<pre>";print_r($arrPkg); exit;
        $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetTravelPlanPerPersonCost($strRoomInfoJson, $arrPkg, $packMPRate[0], $packRate[0], $exchangeRate, $type, $totalactcost, $totalactmarkup, $AgencyMarkupPersentage, $NetworkExtraMarkup);
        //echo "<pre>";print_r($arrPkgCost);exit;
        $IsShareWithGST = (isset($getData['GSTIncluded']) && ((int) $getData['GSTIncluded']) > 0) ? (int) $getData['GSTIncluded'] : $PackageArray[0]['IsShareWithGST'];
        $this->view->totalGSTPrice = ($IsShareWithGST == 0) ? $totalGSTPrice : 0;
        $this->view->arrPkgCost = $arrPkgCost;
        $this->view->IsShareWithGST = $IsShareWithGST;
        $this->view->ShareCombinedFlightPricing = $getData['ShareCombinedFlightPricings'];
        $GetAllServiceSelected = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServicesDisplay($packid, 1, null, 1);
        $this->view->GetAllServiceSelected = $GetAllServiceSelected;
    }

    function getCostPerpersonSharedAction() {
        $this->_helper->layout->disableLayout();
        $getData = $this->getRequest()->getPost();
        $NetworkExtraMarkup = 0;
        $AgencyMarkupPersentage = 0;
        //  echo '<pre>';print_r($getData); echo '</pre>';exit;
        //            $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $exchangeRate = ((float) $_REQUEST['ExchangeRate'] != 0) ? $_REQUEST['ExchangeRate'] : 1;
        $objPackage = new Travel_Model_TblPackage();
        $packid = @$_REQUEST['packid'];
        $MpType = @$_REQUEST['MpType'];
        $travelers = @$_REQUEST['travelers'];
        $type = $this->getRequest()->getParam('type');
        $optionalSightInclude = array();
        if (isset($_REQUEST['optionalSightInclude']) && ($_REQUEST['optionalSightInclude'] != "")) {
            $optionalSightIncludeR = $_REQUEST['optionalSightInclude'];
            $optionalSightInclude = implode(', ', json_decode(base64_decode($optionalSightIncludeR)));
        }
        if ($type == 'customer') {
            $objCust = new Travel_Model_CRM_CustomerTravelPlan();
            $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['pkgCheckInDate'])));
            $PackageArray = $objCust->GetTravelPlanByCustomer($packid);
            $NetworkExtraMarkup = isset($PackageArray[0]['NetworkExtraMarkup']) ? (float) $PackageArray[0]['NetworkExtraMarkup'] : 0;
            $strRoomInfoJson = $PackageArray[0]['RoomInfoJson'];
            $roomInfo = json_decode($PackageArray[0]['RoomInfoJson']);
            //             print_r($roomInfo);
            $totaladult = $totalchild = 0;
            foreach ($roomInfo as $room) {
                $totaladult = $totaladult + $room->Adult;
                $totalchild = $totalchild + $room->Child;
            }
            $MarketPlaceId = ($PackageArray[0]['IsB2BAgent'] == 1 || $PackageArray[0]['IsGTXNetwork'] == 1) ? 2 : 1;
            //            echo '<pre>';print_r($PackageArray[0]['IsB2BAgent']);
            //$MarketPlaceId = 1;
            $packRate = $objCust->getCustTravelPackRateRowWise($packid, $tripdate, $MarketPlaceId, $totaladult);
            $packMPRate = $objCust->getCustPackRateRowWise($packid, $tripdate, $MarketPlaceId, $totaladult);
            if (!empty($optionalSightInclude)) {
                $ssdaywisearr = $objCust->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $tripdate, $optionalSightInclude);
            }
            $GetPackageFLightData = $objCust->GetPackageFLightData($packid);
            //             echo '<pre>pooja';print_r($GetPackageFLightData);echo '</pre>';
//            $encodedata = '';
//            if (!empty($GetPackageFLightData)) {
//                $encodedata = json_decode($GetPackageFLightData[0]['encodedata'], 1);
//            }
            $customerSysId = isset($PackageArray[0]['CustomerSysId']) ? (int) $PackageArray[0]['CustomerSysId'] : 0;
            $AgencyMarkupPersentage = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getB2bAgencyMarkPercentage($customerSysId);
            $AgencySysId = $PackageArray[0]['AgencySysId'];
            //echo "<pre>";print_r($PackageArray);exit;
            $arrPkg['EconomyMask'] = $PackageArray[0]['EconomyMask'];
            $arrPkg['PackSpecType'] = $PackageArray[0]['PackSpecType'];
            $arrPkg['PKqueryType'] = $PackageArray[0]['PKqueryType'];
            $arrPkg['isShareWithFlight'] = $PackageArray[0]['isShareWithFlight'];
            $arrPkg['ShareCombinedFlightPricing'] = $PackageArray[0]['ShareCombinedFlightPricing'];
            $arrPkg['EmailText'] = $PackageArray[0]['EmailText'];
            $arrPkg['package_flightdetails'] = $GetPackageFLightData;
            $arrPkg['page'] = 'public';
            $getTravelPlanAddonServices = $objPackage->getTravelPlanAddonServicesMultipleIds($AgencySysId, $packid, array(6, 21, 19));
            $this->view->getTravelPlanAddonServices = $getTravelPlanAddonServices;
            $GetAllServiceSelected = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServicesDisplay($packid, 1, null, 1);
            $this->view->GetAllServiceSelected = $GetAllServiceSelected;
        } else {
            $MarketPlaceId = !empty($MpType) ? $MpType : 1;
            $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', @$_REQUEST['tripstartdate'])));
            // $packRate = $objPackage->getPackRate($packid, $tripdate, $MarketPlaceId);
            // $packMPRate = $objPackage->getPackMPRate($packid, $travelers, $tripdate, $MarketPlaceId);
            $roomjson = array();
            $totaladult = $totalchild = $totalInfant = 0;
            $roomlp = $this->_request->getParam('roomlp') ? $this->_request->getParam('roomlp') : '';
            for ($k = 1; $k <= $roomlp; $k++) {
                $roomjson[$k]['Adult'] = $this->_request->getParam('adult_' . $k);
                if ($roomjson[$k]['Adult'] == 3) {
                    $roomjson[$k]['AdultBedType'] = $this->_request->getParam('adultcl_extrabed_' . $k . '_3');
                }
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $this->_request->getParam('child_' . $k);
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['Infant'] = $this->_request->getParam('infant_' . $k);
                $totalInfant = $totalInfant + $roomjson[$k]['Infant'];
                for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                    $roomjson[$k]['ChildAge_' . $j] = $this->_request->getParam('child_age_' . $k . '_' . $j);
                    $roomjson[$k]['ChildBedType_' . $j] = $this->_request->getParam('child_extrabed_' . $k . '_' . $j);
                }
            }
            $packRate = $objPackage->getPackRateRowWise($packid, $tripdate, $MarketPlaceId, (int) $totaladult);
            $packMPRate = $objPackage->getPackMPRateRowWise($packid, $travelers, $tripdate, $MarketPlaceId, (int) $totaladult);
            $travelers = $totaladult + $totalchild;
            $strRoomInfoJson = json_encode($roomjson);
            if (!empty($optionalSightInclude)) {
                $ssdaywisearr = $objPackage->getFlexiPackageOptionalSightseenListByItenarary(@$itenArray[0]['TPIntSysId'], 'Optional', '', $MarketPlaceId, $tripdate, $optionalSightInclude);
            }
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
            $ShareCombinedPricing = !empty($getData['ShareCombinedPricing']) ? $getData['ShareCombinedPricing'] : 0;
            $isShareWithFlight = !empty($getData['isShareWithFlight']) ? $getData['isShareWithFlight'] : 0;
            $arrPkg['isShareWithFlight'] = $isShareWithFlight;
            $arrPkg['ShareCombinedFlightPricing'] = $ShareCombinedPricing;
            $arrPkg['package_flightdetails'] = isset($_SESSION['package_flightdetails']) ? $_SESSION['package_flightdetails'] : '';
            $userSysId = isset($_REQUEST['aId']) ? (int) $_REQUEST['aId'] : 0;
            $AgencyMarkupPersentage = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getMarkPercentageForAgent($userSysId);
        }

        $objActivities = new Travel_Model_TblActivities();
        $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($AgencySysId, $MpType);
        //        echo '<pre>'; print_r($PackageArray);echo '</pre>';
        $totalactcost = $totalactmarkup = 0;
        if (!empty($ssdaywisearr)) {
            foreach ($ssdaywisearr as $sightDetailsArr) {
                $TotalCostArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getReadymadeOptionalSightseeingRatesnMarkup($sightDetailsArr, $arrStandardMarkups);

                $totalactcost += ($totalchild * $TotalCostArr['ChildCost']) + ($totaladult * $TotalCostArr['AdultCost']);
                $totalactmarkup += ($totalchild * $TotalCostArr['ChildCostMarkup']) + ($totaladult * $TotalCostArr['AdultCostMarkup']);
            }
        }
        //        print_r($totalactcost+$totalactmarkup);

        $arrPkg['DiscountType'] = 0;
        $arrPkg['DiscountVal'] = 0;
        $arrPkg['AdvBookingPercent'] = $_REQUEST['AdvBookingPercent'];
        $arrPkg['ShareCurrency'] = $_REQUEST['ShareCurrency'];
        if (@$PackageArray[0]['IsShared'] == 1) {
            if (($PackageArray[0]['EconomyMask'] == 6 || $PackageArray[0]['EconomyMask'] == 7 || $PackageArray[0]['EconomyMask'] == 8)) {
                $arrPkg['ExtraMarkup'] = $PackageArray[0]['ExtraMarkUp'];
            } else {
                $arrPkg['ExtraMarkup'] = $PackageArray[0]['MarkUp'];
            }
            $arrPkg['ExtraDiscount'] = $PackageArray[0]['CustomDiscount'];
        } else {
            $arrPkg['ExtraMarkup'] = !empty($_REQUEST['MarkUp'][0]) ? $_REQUEST['MarkUp'][0] : 0;
            $arrPkg['ExtraDiscount'] = !empty($_REQUEST['discountValue'][0]) ? $_REQUEST['discountValue'][0] : 0;
        }
        $arrPkg['sac_code'] = !empty($_REQUEST['sac_code']) ? $_REQUEST['sac_code'] : @$PackageArray[0]['SACCode'];
        $arrPkg['gsttype'] = !empty($_REQUEST['gsttype']) ? $_REQUEST['gsttype'] : @$PackageArray[0]['GSTSharedMode'];
        $arrPkg['IsShareWithGST'] = !empty($PackageArray[0]['IsShareWithGST']) ? $PackageArray[0]['IsShareWithGST'] : 0;
        $isShareWithFlight = isset($isShareWithFlight) ? $isShareWithFlight : '';
        $this->view->isShareWithFlight = $isShareWithFlight;
        // $AgencyMarkupPersentage = 18;
        //                 Package Cost.....                
        $arrPkgCost = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->GetTravelPlanPerPersonCost($strRoomInfoJson, $arrPkg, $packMPRate[0], $packRate[0], $exchangeRate, $type, $totalactcost, $totalactmarkup, $AgencyMarkupPersentage, $NetworkExtraMarkup);
        //         echo "<pre>";print_r($arrPkgCost);exit;
        $totalGSTPrice = (float) $PackageArray[0]['XServiceTaxAmount'] + (float) $PackageArray[0]['AgentServiceTaxAmount'] + (float) $PackageArray[0]['AgentsCustomServiceTaxAmount'] - (float) $PackageArray[0]['ServiceTaxOnCustomDiscount'];
        $IsShareWithGST = (isset($getData['IsShareWithGST']) && ((int) $getData['IsShareWithGST']) > 0) ? (int) $getData['IsShareWithGST'] : $PackageArray[0]['IsShareWithGST'];
        $this->view->totalGSTPrice = ($PackageArray[0]['IsShareWithGST'] == 0) ? $totalGSTPrice : 0;
        $this->view->arrPkgCost = $arrPkgCost;
        $this->view->IsShareWithGST = $IsShareWithGST;
        $this->view->ShareCombinedFlightPricing = $getData['ShareCombinedFlightPricings'];
        $this->view->GSTApplicable = $getData['GSTSharedModes'];
        $this->view->SelectPricingType = $getData['SelectPricingTypes'];
    }

    public function updateFullfillmentDataAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        //echo '<pre>'; print_r($getData);die;
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $TPSysId = $this->_HtmlPurifier->filter($getData['TPSysId']);
        $totalSourceCost = isset($getData['totalSourceCost']) ? $this->_HtmlPurifier->filter($getData['totalSourceCost']) : '';
        $igst = isset($getData['igst']) ? $this->_HtmlPurifier->filter($getData['igst']) : '';
        $sgst = isset($getData['sgst']) ? $this->_HtmlPurifier->filter($getData['sgst']) : '';
        $cgst = isset($getData['cgst']) ? $this->_HtmlPurifier->filter($getData['cgst']) : '';
        $FullGST = isset($getData['FullGST']) ? $this->_HtmlPurifier->filter($getData['FullGST']) : '';
        $FullGSTType = isset($getData['FullGSTType']) ? $this->_HtmlPurifier->filter($getData['FullGSTType']) : '';
        $FullGSTSlab = isset($getData['FullGSTSlab']) ? $this->_HtmlPurifier->filter($getData['FullGSTSlab']) : '';
        $FullCost = isset($getData['FullCost']) ? $this->_HtmlPurifier->filter($getData['FullCost']) : '';
        $FullTotalCost = isset($getData['FullTotalCost']) ? $this->_HtmlPurifier->filter($getData['FullTotalCost']) : '';
        $formType = isset($getData['formType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['formType'])) : '';
        $VehicleType = isset($getData['vehicltype']) ? $this->_HtmlPurifier->filter($getData['vehicltype']) : '';
        $VehicleQty = isset($getData['transportpickup_noofvihicle']) ? $this->_HtmlPurifier->filter($getData['transportpickup_noofvihicle']) : '';
        $VehicleName = isset($getData['transportpickup_vihiclename']) ? $this->_HtmlPurifier->filter($getData['transportpickup_vihiclename']) : '';
        $PickUpDate = isset($getData['transportpickup_date']) ? $this->_HtmlPurifier->filter($getData['transportpickup_date']) : '';
        $TransContId = isset($getData['country']) ? $this->_HtmlPurifier->filter($getData['country']) : '';
        $PickUpCitySysId = isset($getData['hidden_pickup_typeahead_cityid']) ? $this->_HtmlPurifier->filter($getData['hidden_pickup_typeahead_cityid']) : '';
        $PickUpLocation = isset($getData['pickUpCityName']) ? $this->_HtmlPurifier->filter($getData['pickUpCityName']) : '';
        $PickUpRemarks = isset($getData['transportpickup_remarks']) ? $this->_HtmlPurifier->filter($getData['transportpickup_remarks']) : '';
        $DropCitySysId = isset($getData['hidden_drop_typeahead_cityid']) ? $this->_HtmlPurifier->filter($getData['hidden_drop_typeahead_cityid']) : '';
        $PickupCountryId = isset($getData['PickupCountryId']) ? $this->_HtmlPurifier->filter($getData['PickupCountryId']) : '';
        $DropCountryId = isset($getData['DropCountryId']) ? $this->_HtmlPurifier->filter($getData['DropCountryId']) : '';

        $DropLocation = isset($getData['dropCityName']) ? $this->_HtmlPurifier->filter($getData['dropCityName']) : '';
        $DropDate = isset($getData['transportpickup_date']) ? $this->_HtmlPurifier->filter($getData['transportpickup_date']) : '';
        $InstructionForDriver = isset($getData['transport_instrfordriver']) ? $this->_HtmlPurifier->filter($getData['transport_instrfordriver']) : '';
        $SightSeeingIncluded = isset($getData['transport_ss']) ? $this->_HtmlPurifier->filter($getData['transport_ss']) : '';
        $TransSupplierName = isset($getData['transport_suppliername']) ? $this->_HtmlPurifier->filter($getData['transport_suppliername']) : '';
        $TransSupplierContact = isset($getData['transport_suppliernumber']) ? $this->_HtmlPurifier->filter($getData['transport_suppliernumber']) : '';
        $TransSupportName = isset($getData['transport_supportname']) ? $this->_HtmlPurifier->filter($getData['transport_supportname']) : '';
        $TransSupportContact = isset($getData['transport_supportnumber']) ? $this->_HtmlPurifier->filter($getData['transport_supportnumber']) : '';
        $ShareCurrency = isset($getData['ShareCurrency']) ? $this->_HtmlPurifier->filter($getData['ShareCurrency']) : 0;

        if ($PickUpDate) {
            $PickUpDateRes = explode(" ", $PickUpDate);
            $PickUpDateData = explode('/', $PickUpDateRes[0]);
            $PickUpDate = $PickUpDateData[2] . '-' . $PickUpDateData[1] . '-' . $PickUpDateData[0] . ' ' . $PickUpDateRes[1];
        }
        if ($DropDate) {
            $DropDateRes = explode(" ", $DropDate);
            $DropDateData = explode('/', $DropDateRes[0]);
            $DropDate = $DropDateData[2] . '-' . $DropDateData[1] . '-' . $DropDateData[0] . ' ' . $DropDateRes[1];
        }
        //update status
        $fullfillmentObj = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
        $checkRecordExist = $fullfillmentObj->ChkFullfillmentRecordExist($TPSysId);
        $date = date('Y-m-d H:i:s');
        if (!empty($checkRecordExist)) {
            $where = "TPSysId = " . $TPSysId;

            if ($formType == 'updateTransport') {
                $userArray = array(
                    'VehicleType' => $VehicleType,
                    'VehicleQty' => $VehicleQty,
                    'VehicleName' => $VehicleName,
                    'PickUpDate' => $PickUpDate,
                    'TransContId' => $TransContId,
                    'PickUpCitySysId' => $PickUpCitySysId,
                    'PickUpLocation' => $PickUpLocation,
                    'PickUpRemarks' => $PickUpRemarks,
                    'PickUpContId' => $PickupCountryId,
                    'DropContId' => $DropCountryId,
                    'DropCitySysId' => $DropCitySysId,
                    'DropLocation' => $DropLocation,
                    'DropDate' => $DropDate,
                    'InstructionForDriver' => $InstructionForDriver,
                    'SightSeeingIncluded' => $SightSeeingIncluded,
                    'TransSupplierName' => $TransSupplierName,
                    'TransSupplierContact' => $TransSupplierContact,
                    'TransSupportName' => $TransSupportName,
                    'TransSupportContact' => $TransSupportContact,
                    'CreatedDate' => $date,
                    'UpdatedDate' => $date
                );
            } else {
                $userArray = array(
                    'CurrencyType' => $ShareCurrency,
                    'SourceCost' => $totalSourceCost ? $totalSourceCost : 0,
                    'IGST' => $igst ? $igst : 0,
                    'SGST' => $sgst ? $sgst : 0,
                    'CGST' => $cgst ? $cgst : 0,
                    'IsGSTIncluded' => $FullGST ? $FullGST : 0,
                    'GSTType' => $FullGSTType ? $FullGSTType : 0,
                    'GSTSlab' => $FullGSTSlab ? $FullGSTSlab : 0,
                    'Cost' => $FullCost ? $FullCost : 0,
                    'TotalCost' => $FullTotalCost ? $FullTotalCost : 0,
                    'UpdatedDate' => $date,
                );
            }
            //echo "<pre>";print_r($userArray);die;
            $Rcord = $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray, $where);
        } else {

            if ($formType == 'updateTransport') {

                $userArray = array(
                    'SourceCost' => $totalSourceCost ? $totalSourceCost : 0,
                    'IGST' => $igst ? $igst : 0,
                    'SGST' => $sgst ? $sgst : 0,
                    'CGST' => $cgst ? $cgst : 0,
                    'IsGSTIncluded' => $FullGST ? $FullGST : 0,
                    'GSTType' => $FullGSTType ? $FullGSTType : 0,
                    'GSTSlab' => $FullGSTSlab ? $FullGSTSlab : 0,
                    'Cost' => $FullCost ? $FullCost : 0,
                    'TotalCost' => $FullTotalCost ? $FullTotalCost : 0,
                    'TPSysId' => $TPSysId,
                    'VehicleType' => $VehicleType,
                    'VehicleQty' => $VehicleQty,
                    'VehicleName' => $VehicleName,
                    'PickUpDate' => $PickUpDate,
                    'TransContId' => $TransContId,
                    'PickUpCitySysId' => $PickUpCitySysId,
                    'PickUpLocation' => $PickUpLocation,
                    'PickUpRemarks' => $PickUpRemarks,
                    'PickUpContId' => $PickupCountryId,
                    'DropContId' => $DropCountryId,
                    'DropCitySysId' => $DropCitySysId,
                    'DropLocation' => $DropLocation,
                    'DropDate' => $DropDate,
                    'InstructionForDriver' => $InstructionForDriver,
                    'SightSeeingIncluded' => $SightSeeingIncluded,
                    'TransSupplierName' => $TransSupplierName,
                    'TransSupplierContact' => $TransSupplierContact,
                    'TransSupportName' => $TransSupportName,
                    'TransSupportContact' => $TransSupportContact,
                    'UpdatedDate' => $date,
                    'CreatedDate' => $date,
                );
            } else {
                $userArray = array(
                    'TPSysId' => $TPSysId,
                    'CurrencyType' => $ShareCurrency,
                    'SourceCost' => $totalSourceCost,
                    'IGST' => $igst ? $igst : 0,
                    'SGST' => $sgst ? $sgst : 0,
                    'CGST' => $cgst ? $cgst : 0,
                    'IsGSTIncluded' => $FullGST ? $FullGST : 0,
                    'GSTType' => $FullGSTType ? $FullGSTType : 0,
                    'GSTSlab' => $FullGSTSlab ? $FullGSTSlab : 0,
                    'Cost' => $FullCost ? $FullCost : 0,
                    'TotalCost' => $FullTotalCost ? $FullTotalCost : 0,
                    'CreatedDate' => $date,
                    'UpdatedDate' => $date
                );
            }


            //echo "<pre>";print_r($userArray);
            $Rcord = $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray);
        }
        $response = array('status' => 'success', 'message' => 'Cost Saved Successfully', 'id' => $TPSysId);
        echo json_encode($response);
    }

    public function setOptionalSightseeingAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        //        echo "<pre>";print_r($getData);
        $textAR = $getData['textAr'];
        $VersionId = $getData['VersionId'];
        $packtype = $getData['packtype'];
        $optionalSightIncludeArr = json_decode(base64_decode($getData['optionalSightInclude']), 1);
        if ($textAR == 'Add') {
            $optionalSightIncludeArr[] = $VersionId;
        } else {
            if (($key = array_search($VersionId, $optionalSightIncludeArr)) !== false) {
                unset($optionalSightIncludeArr[$key]);
            }
        }
        if ($packtype == 'customer') {
            $where = "VersionId = " . $VersionId;
            $userArray = array(
                'Type' => ($textAR == 'Add') ? 'Included' : 'Optional',
            );
            //            echo "<pre>".$where;print_r($userArray);die;
            $objPackage = new Travel_Model_TblPackage();
            $objPackage->updateData('TB_Agency_Customer_TravelPlan_SIghtseeing', $userArray, $where);
        }
        //         echo "<pre>";print_r($optionalSightIncludeArr);
        $optionalSightInclude = base64_encode(json_encode($optionalSightIncludeArr));
        echo json_encode(array('msg' => 'Success', 'optionalSightInclude' => $optionalSightInclude));
        exit;
    }

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

        $objPackage = new Travel_Model_TblPackage();
        //        $currentDate = Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss');
        if ($this->getRequest()->isXmlHttpRequest()) {
            $controller = $this->getRequest()->getParam('con');
            $postData = $this->getRequest()->getPost();
            //                            echo '<pre>';print_r($postData); die;
            //                   $date =         
            $MpType = !empty($postData['MpType']) ? $postData['MpType'] : 1;
            $ShareCurrencyArr = explode('_', $postData['ShareCurrency']);
            if ($controller == 'package') {
                $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', $postData['tripstartdate'])));

                $itenArray = $objPackage->getPackItenId($postData['packid'], 2);
                $ssdaywisearr = $objPackage->getFlexiPackageOptionalSightseenListByItenarary($itenArray[0]['TPIntSysId'], 'Optional', '', $MpType, $tripdate);
            } else {
                $tripdate = date("Y-m-d", strtotime(str_replace('/', '-', $postData['tripdate'])));
                $itenArray = $this->_crmcusttravelplan->getPackItenId($postData['packid'], 2);
                $ssdaywisearr = $this->_crmcusttravelplan->getFlexiPackageOptionalSightseenListByItenarary($itenArray[0]['TPIntSysId'], 'Optional', '', $MpType, $tripdate);
            }


            $this->view->ssdaywisearr = $ssdaywisearr;

            $objActivities = new Travel_Model_TblActivities();
            $arrStandardMarkups = $objActivities->getStandardMarkupsActivities($postData['agencyid'], $MpType);
            //                echo "<pre>"; print_r($arrStandardMarkups);die;
            $this->view->arrStandardNativesMarkups = $arrStandardMarkups;

            $totaladult = 0;
            $totalchild = 0;
            $totalInfant = 0;
            $roomjson = array();
            $roomlp = $postData['roomlp'] ? $postData['roomlp'] : '';

            for ($k = 1; $k <= $roomlp; $k++) {
                $roomjson[$k]['Adult'] = $postData['adult_' . $k];
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $postData['child_' . $k];
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['Infant'] = $postData['infant_' . $k];
                $totalInfant = $totalInfant + $roomjson[$k]['Infant'];
            }
            $responseArray['netcost'] = $postData['netprice'];
            $responseArray['sharedcurrency'] = $ShareCurrencyArr;
            $responseArray['traveler'] = array('adult' => $totaladult, 'child' => $totalchild, 'infant' => $totalInfant);
            $responseArray['optionalSightInclude'] = $postData['optionalSightInclude'];
            $responseArray['optionalSightIncludePrice'] = $postData['optionalSightIncludePrice'];
            $responseArray['optionalSightIncludeMPrice'] = $postData['optionalSightIncludeMPrice'];
            $responseArray['tax_rate'] = @$postData['tax_rate'];
            $responseArray['packtype'] = ($controller == 'publicpackage') ? 'customer' : 'agent';
            $this->view->responseArr = $responseArray;
        }
    }

    public function updateplanpriceAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $totprice = $this->_request->getParam('totprice') ? $this->_request->getParam('totprice') : '0';
        $netprice = $this->_request->getParam('netprice') ? $this->_request->getParam('netprice') : '0';
        $npstax = $this->_request->getParam('npstax') ? $this->_request->getParam('npstax') : '0';
        $mpstax = $this->_request->getParam('mpstax') ? $this->_request->getParam('mpstax') : '0';
        $agencyFInalMarkup = $this->_request->getParam('fmp') ? $this->_request->getParam('fmp') : '0';
        $tpID = $this->_request->getParam('tpID') ? $this->_request->getParam('tpID') : '';
        $where = array('TPSysId = ? ' => (int) $tpID);
        $updatetravelplan = array(
            'NetPrice' => (float) $totprice,
            'Price' => (float) $netprice,
            'XServiceTaxAmount' => (float) $npstax,
            'AgentServiceTaxAmount' => (float) $mpstax,
            'AgencyMarkUp' => (float) $agencyFInalMarkup
        );
        $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplan, $where);
        echo "done";
        exit;
    }

    public function getflightdetailsAction() {
        $this->view->layout()->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $controller = $this->getRequest()->getParam('con');
            $postData = $this->getRequest()->getPost();
            $pkgCheckInDate = isset($postData['pkgCheckInDate']) ? trim($postData['pkgCheckInDate']) : '';
            $pkgCheckOutDate = isset($postData['pkgCheckOutDate']) ? trim($postData['pkgCheckOutDate']) : '';
            $this->view->sessionData = @$_SESSION['package_flightdetails'];
            $totaladult = 0;
            $totalchild = 0;
            $totalInfant = 0;
            $roomjson = array();
            $roomlp = $postData['roomlp'] ? $postData['roomlp'] : '';
            $selectedCustomerId = $postData['selectedCustomerId'] ? base64_decode($postData['selectedCustomerId']) : '';

            for ($k = 1; $k <= $roomlp; $k++) {
                $roomjson[$k]['Adult'] = $postData['adult_' . $k];
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $postData['child_' . $k];
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['Infant'] = $postData['infant_' . $k];
                $totalInfant = $totalInfant + $roomjson[$k]['Infant'];
            }
            $responseArray['traveler'] = array('adult' => $totaladult, 'child' => $totalchild, 'infant' => $totalInfant);
            $responseArray['packtype'] = ($controller == 'publicpackage') ? 'customer' : 'agent';
            $responseArray['pkgCheckInDate'] = $pkgCheckInDate;
            $responseArray['pkgCheckOutDate'] = $pkgCheckOutDate;
            $this->view->responseArr = $responseArray;
            $this->view->selectedCustomerId = $selectedCustomerId;
            $markupMdl = new Markup_Model_Markup();
            $getTaxSettingDetail = $this->view->flightTaxDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $_SESSION['sessionLogin_user']['intLoggedinUserAgencySysId'], 0, 0, 1);
            if (empty($getTaxSettingDetail)) {
                $this->view->flightTaxDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $_SESSION['sessionLogin_user']['intLoggedinUserAgencySysId'], 0, 0, 5);
            }
        }
    }

    public function saveflightdetailsAction() {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $postData = $this->getRequest()->getPost();
            if (isset($postData['flighttext']) && !empty($postData['flighttext'])) {
                $postData['flighttext'] = $this->createImageFromCkeditor($postData['flighttext']);
            }
            $_SESSION['package_flightdetails'] = $postData;
        }
    }

    ///// Addes by Sabir

    public function updateSourcingCostAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $getData = $this->getRequest()->getPost();
        //echo '<pre>'; print_r($getData);
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $TPSysId = $this->_HtmlPurifier->filter($getData['TPSysId']);
        $totalSourceCost = isset($getData['totalSourceCost']) ? $this->_HtmlPurifier->filter($getData['totalSourceCost']) : '';
        $TPIntSysId = isset($getData['TPIntSysId']) ? $this->_HtmlPurifier->filter($getData['TPIntSysId']) : '0';
        $VersionId = isset($getData['VersionId']) ? $this->_HtmlPurifier->filter($getData['VersionId']) : '0';
        $TYPE = isset($getData['TYPE']) ? $this->_HtmlPurifier->filter($getData['TYPE']) : '0';
        $igst = isset($getData['igst']) ? $this->_HtmlPurifier->filter($getData['igst']) : '';
        $sgst = isset($getData['sgst']) ? $this->_HtmlPurifier->filter($getData['sgst']) : '';
        $cgst = isset($getData['cgst']) ? $this->_HtmlPurifier->filter($getData['cgst']) : '';
        $FullGST = isset($getData['FullGST']) ? $this->_HtmlPurifier->filter($getData['FullGST']) : '';
        $FullGSTType = isset($getData['FullGSTType']) ? $this->_HtmlPurifier->filter($getData['FullGSTType']) : '';
        $FullGSTSlab = isset($getData['FullGSTSlab']) ? $this->_HtmlPurifier->filter($getData['FullGSTSlab']) : '';
        $FullCost = isset($getData['FullCost']) ? $this->_HtmlPurifier->filter($getData['FullCost']) : '';
        $FullTotalCost = isset($getData['FullTotalCost']) ? $this->_HtmlPurifier->filter($getData['FullTotalCost']) : '';
        $formType = isset($getData['formType']) ? $this->_HtmlPurifier->filter(base64_decode($getData['formType'])) : '';

        $ShareCurrency = isset($getData['ShareCurrency']) ? $this->_HtmlPurifier->filter($getData['ShareCurrency']) : 0;
        $supplier_sys_id = isset($getData['supplier_sys_id']) ? $this->_HtmlPurifier->filter($getData['supplier_sys_id']) : 0;

        //update status
        $fullfillmentObj = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
        $checkRecordExist = $fullfillmentObj->ChkFullfillmentRecordExist($TPSysId, $TYPE, $TPIntSysId, $VersionId);
        //print_r($checkRecordExist);die;
        $date = date('Y-m-d H:i:s');
        $whereSupp = "TPSysId = " . $TPSysId;
        if (!empty($checkRecordExist)) {
            $where = array('TPSysId = ?' => $TPSysId, 'IsSalesPrice = ?' => $TYPE, 'TPIntSysId = ?' => $TPIntSysId, 'VersionId = ?' => $VersionId);
            $userArray = array(
                'CurrencyType' => $ShareCurrency,
                'SourceCost' => $totalSourceCost ? $totalSourceCost : 0,
                'IGST' => $igst ? $igst : 0,
                'SGST' => $sgst ? $sgst : 0,
                'CGST' => $cgst ? $cgst : 0,
                'IsGSTIncluded' => $FullGST ? $FullGST : 0,
                'GSTType' => $FullGSTType ? $FullGSTType : 0,
                'GSTSlab' => $FullGSTSlab ? $FullGSTSlab : 0,
                'Cost' => $FullCost ? $FullCost : 0,
                'TotalCost' => $FullTotalCost ? $FullTotalCost : 0,
                'IsSalesPrice' => $TYPE ? $TYPE : 0,
                'TPIntSysId' => $TPIntSysId ? $TPIntSysId : 0,
                'VersionId' => $VersionId ? $VersionId : 0,
                'UpdatedDate' => $date,
            );
            $SupplierData = array(
                'SupplierSysId' => $supplier_sys_id
            );
            //echo '<pre>'; print_r($userArray);die;
            $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray, $where);
            $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Fullfillment', $SupplierData, $whereSupp);
            $response = array('status' => 'success', 'message' => 'Cost Saved Successfully', 'id' => $TPSysId);
            echo json_encode($response);
            exit;
        } else {
            $userArray = array(
                'TPSysId' => $TPSysId,
                'CurrencyType' => $ShareCurrency,
                'SourceCost' => $totalSourceCost,
                'IGST' => $igst ? $igst : 0,
                'SGST' => $sgst ? $sgst : 0,
                'CGST' => $cgst ? $cgst : 0,
                'IsGSTIncluded' => $FullGST ? $FullGST : 0,
                'GSTType' => $FullGSTType ? $FullGSTType : 0,
                'GSTSlab' => $FullGSTSlab ? $FullGSTSlab : 0,
                'Cost' => $FullCost ? $FullCost : 0,
                'TotalCost' => $FullTotalCost ? $FullTotalCost : 0,
                'IsSalesPrice' => $TYPE ? $TYPE : 0,
                'TPIntSysId' => $TPIntSysId ? $TPIntSysId : 0,
                'VersionId' => $VersionId ? $VersionId : 0,
                'CreatedDate' => $date,
                'UpdatedDate' => $date
            );
            $SupplierData = array(
                'SupplierSysId' => $supplier_sys_id
            );
            $fullfillmentObj->insertData('TB_Agency_Customer_TravelPlan_Other_Fullfillment', $userArray);
            $fullfillmentObj->updateData('TB_Agency_Customer_TravelPlan_Fullfillment', $SupplierData, $whereSupp);
            $response = array('status' => 'success', 'message' => 'Cost Saved Successfully', 'id' => $TPSysId);
            echo json_encode($response);
            exit;
        }
        //echo "<pre>";print_r($userArray);die;
    }

    public function searchProposalAction() {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        //if ($this->_request->isXmlHttpRequest()) {
        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        if ($params['ProposalNo'] == '') {
            $response = array('success' => false, 'message' => 'Please enter proposal Id');
            echo json_encode($response);
            exit;
        }
        $objFullfillment = new Travel_Model_CRM_CustomerTravelPlanFullfillment();
        $result = $objFullfillment->GetCustomerTravelPlanItenaryFullfillment($params['ProposalNo']);
        if (!empty($result)) {
            $response = array('success' => true, 'ProposalNo' => base64_encode($params['ProposalNo']), 'message' => 'Available successfully');
            echo json_encode($response);
            exit;
        } else {
            $response = array('success' => false, 'message' => 'Unable to  find record. try again');
            echo json_encode($response);
            exit;
        }
        //}
    }

    public function suggestRoomTypeAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            $arrResponse = array();
            $response = array();
            if ($this->getRequest()->getParam("term") or $this->getRequest()->getParam("query")) {
                $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
                $objGeneral = new Travel_Model_GeneralFunction();
                $whereStatic = array('IsActive' => 1, 'IsMarkForDel' => 0);
                $whereArr = array('Title' => $term);
                $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
                $intLoggedinUserAgencySysId = isset($sessionLogin_user->intLoggedinUserAgencySysId) ? $sessionLogin_user->intLoggedinUserAgencySysId : null;
                $arrResponse = $objGeneral->getRoomTypeAgencyWise($term, $intLoggedinUserAgencySysId);
            }
            if (!empty($arrResponse)) {
                foreach ($arrResponse as $row) {
                    $Title = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', trim($row['Title']));
                    $response[] = array('RoomType' => $row['RoomType'], 'value' => $Title, 'label' => $Title);
                }
            } else {
                $response[] = array('RoomType' => 0, 'value' => '', 'label' => 'Add New Room');
            }
//            echo "<pre>";print_r($arrResponse);die;
            echo json_encode($response);
            exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }

    public function downloadWordDocumentDynamicAction() {
        $this->_helper->layout->disableLayout();
        $baseUrl = $this->baseUrl;

        $ByoModel = new BuildYourOwn_Model_Byo();
        $objPackage = new Travel_Model_TblPackage();

        $TblAgency = new Travel_Model_TblAgency();

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            $tpproposalID = $postData['id'];
            $secureCode = $postData['code'];

            $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpproposalID); // get proposal data from customer travel plan

            $agentsysID = $transactiontravelplandata[0]['AgentSysId'];
            $agencyId = $transactiontravelplandata[0]['AgencySysId'];
            $getAgencyDetail = $TblAgency->getAgencyDataById($agencyId);
            $getAgencyAddress = $TblAgency->getAddressByAgency($agencyId);
            $getAgencyTnCDetails = $TblAgency->getAgencyTnCDetails($agencyId);
            $queryDetails = $this->_crmcusttravelplan->GetTravelPlanByCustomer($transactiontravelplandata[0]['MasterTPSysId'], 'Query');
            //            echo "<pre>";print_r($queryDetails);die;
            $getAgencyDetailArr = [
                'DisplayName' => $getAgencyDetail['DisplayName'],
                'Url' => $getAgencyDetail['Url'],
                'CompanyAddress' => implode(',', explode('___', $getAgencyAddress['Address'])),
                'PrimaryEmail' => $getAgencyDetail['PrimaryEmail'],
                'PrimaryContactNo' => $getAgencyDetail['PrimaryContactNo'],
                'GSTIN' => $getAgencyDetail['GSTIN'],
                'PaymentDetails' => $getAgencyTnCDetails['PaymentDetails'],
            ];

            $agentDetails = $this->_crmcusttravelplan->getAgentDetails($agentsysID);
            $booknowurl = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . $postData['id'] . '/code/' . $secureCode;

            if ($agentDetails['IsB2CSite'] == 1) {
                $booknowurl = $agentDetails['Url'] . "detail/index/view/id/" . base64_encode($booknowurl);
            } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 1)) {
                $booknowurl = $agentDetails['Url'] . "hellogtx/index.html?id=" . base64_encode($booknowurl);
            } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 0)) {
                $booknowurl = $agentDetails['Url'] . "hellogtx/gtx.php?id=" . base64_encode($booknowurl);
            }
            $FirstName = (isset($transactiontravelplandata[0]['FirstName']) && $transactiontravelplandata[0]['FirstName']) ? $transactiontravelplandata[0]['FirstName'] : '';
            $LastName = (isset($transactiontravelplandata[0]['LastName']) && $transactiontravelplandata[0]['LastName']) ? ' ' . $transactiontravelplandata[0]['LastName'] : '';
            $FullName = trim($FirstName) . ' ' . trim($LastName);

            $CurrSymbol = 'INR';
            $CurrSymbolArr = $ByoModel->getOnlyIndiaCurrency();
            if (!empty($CurrSymbolArr)) {
                $CurrSymbol = $CurrSymbolArr[0]['Symbol'];
            }
            $IsShareWithGST = 1;

            $finalPrice = $transactiontravelplandata[0]['NetPrice'];
            if ($IsShareWithGST == 1) {
                $sentprice = $CurrSymbol . ' ' . $this->moneyFormatIndia((float) round($finalPrice, 2));
            } else {
                $PackageArray = $transactiontravelplandata[0];
                $totalCost = $totalCost - ((float) $PackageArray['XServiceTaxAmount'] + (float) $PackageArray['AgentServiceTaxAmount'] + (float) $PackageArray['AgentsCustomServiceTaxAmount'] - (float) $PackageArray['ServiceTaxOnCustomDiscount']);
                $sentprice = $CurrSymbol . ' ' . $this->moneyFormatIndia((float) round($totalCost, 2));
            }

            $packageDetail = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageDetailsForEmailTemplate($tpproposalID, $transactiontravelplandata[0], $transactiontravelplandata[0]['EconomyMask']); //$paramArray['PackageArray']['EconomyMask'] package category
            //    echo "<pre>"; print_r($packageDetail); die;
            if (!empty($packageDetail['getHotelsBySequenceArray'])) {
                //                    echo "<pre>"; print_r($packageDetail['getHotelsBySequenceArray']); die;

                $hotelArray = $getCityNight = array();
                foreach ($packageDetail['getHotelsBySequenceArray'] as $hotelCityWise) {
                    $k = 0;
                    foreach ($hotelCityWise as $cityKey => $cityVal111) {
                        foreach ($cityVal111 as $cityVal) {
                            $hotelArray = $cityVal['hotels'];
                            $getCityNight[$k]['cityName'] = $cityVal['hotels'][0]['CityName'];
                            if ($transactiontravelplandata[0]['EconomyMask'] == 8) {
                                $getCityNight[$k]['noOfNight'] = count($hotelArray);
                            } else {
                                $getCityNight[$k]['noOfNight'] = count($hotelArray) - 1;
                            }
                        }
                        $k++;
                    }
                }
            }
            if (!empty($getCityNight)) {
                $htmlHotelInclusion = '';
                $i = 0;
                $cnt = count($getCityNight);
                foreach ($getCityNight as $hotelcityNight) {
                    $htmlHotelInclusion .= $hotelcityNight['cityName'] . ' ' . $hotelcityNight['noOfNight'] . "N";
                    $i++;
                    if ($i < $cnt) {
                        $htmlHotelInclusion .= " | ";
                    }
                }
            }

            if (!empty($packageDetail['getFlightDetail'])) {
                $htmlFlightInclusion = '';
                $j = 0;
                foreach ($packageDetail['getFlightDetail'] as $flightInfo) {
                    $jsonFlightData = json_decode($flightInfo['encodedata'], 1);
                    $depCity = explode(',', $jsonFlightData['departureCity']);
                    $arrCity = explode(',', $jsonFlightData['arrivalCity']);
                    $depaartureTime = $jsonFlightData['depaartureTime'];
                    $htmlFlightInclusion .= $depCity[0] . ' to ' . $arrCity[0] . ' <strong>(Flight)</strong> ';
                    $htmlFlightInclusionArr['data'][$jsonFlightData['day']][] = 'Depart From ' . $depCity[0] . ' to ' . $arrCity[0];
                    $htmlFlightInclusionArr['time'][$jsonFlightData['day']][] = $depaartureTime;

                    $j++;
                }
            }
            $guideArray = $miscArray = array();
            $htmlGuideDaywise = $htmlMissDaywise = array();
            if (!empty($packageDetail['otherServiceDetails'])) {
                foreach ($packageDetail['itenDetailArr'] as $ddKey => $ddVal) {
                    $g = $m = 0;
                    foreach ($packageDetail['otherServiceDetails'] as $otherServices) {
                        if ($otherServices['ServiceType'] == 6) {
                            $guideArray[$g] = $otherServices;
                            if ($ddVal['TPIntSysId'] == $otherServices['ItenarySysId']) {
                                $htmlGuideDaywise[$ddKey][] = $otherServices['ServiceTitle'];
                            }

                            $g++;
                        } else {
                            $miscArray[$m] = $otherServices;
                            if ($ddVal['TPIntSysId'] == $otherServices['ItenarySysId']) {
                                $htmlMissDaywise[$ddKey][] = $otherServices['ServiceTitle'];
                            }

                            $m++;
                        }
                    }
                }
            }
            //echo "<pre>"; print_r($htmlFlightInclusionArr); die;

            if (!empty($packageDetail['getTransportDetail'])) {
                $railInfoDisp = $busInfoDisp = $cabInfoDisp = $dwsCab = $dwsBus = $dwsRail = $dwsCabDaywise = $dwsBusDaywise = $dwsRailDaywise = array();
                $railf = $cabf = $busf = 0;
                foreach ($packageDetail['getTransportDetail'] as $allTransPort) {

                    if ($allTransPort['TransId'] == 1 && $allTransPort['IsDisplay'] == 1) {
                        $cabInfoDisp[$cabf]['fromPlace'] = $allTransPort['FromPlace'];
                        $cabInfoDisp[$cabf]['toPlace'] = $allTransPort['ToPlace'];

                        $dwsCab[$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];

                        $cabf++;
                    }
                    if ($allTransPort['TransId'] == 1) {
                        $dwsCabDaywise['data'][$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];
                        $dwsCabDaywise['time'][$allTransPort['Sequence']][] = $allTransPort['FromDate']->format('h:i');
                    }
                    if ($allTransPort['TransId'] == 3) {
                        $busInfoDisp[$busf]['fromPlace'] = $allTransPort['FromPlace'];
                        $busInfoDisp[$busf]['toPlace'] = $allTransPort['ToPlace'];
                        $dwsBus[$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];

                        $busf++;
                    }
                    if ($allTransPort['TransId'] == 3) {
                        $dwsBusDaywise['data'][$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];
                        $dwsBusDaywise['time'][$allTransPort['Sequence']][] = $allTransPort['FromDate']->format('h:i');
                    }
                    if ($allTransPort['TransId'] == 5) {
                        $railInfoDisp[$railf]['fromPlace'] = $allTransPort['FromPlace'];
                        $railInfoDisp[$railf]['toPlace'] = $allTransPort['ToPlace'];
                        $dwsRail[$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];
                        $railf++;
                    }
                    if ($allTransPort['TransId'] == 5) {
                        $dwsRailDaywise['data'][$allTransPort['Sequence']][] = 'Transfer From ' . $allTransPort['FromPlace'] . ' to ' . $allTransPort['ToPlace'];
                        $dwsRailDaywise['time'][$allTransPort['Sequence']][] = $allTransPort['FromDate']->format('h:i');
                    }
                }
            }
            if (!empty($cabInfoDisp)) {
                $cntcar = count($cabInfoDisp);
                $cr = 0;
                foreach ($cabInfoDisp as $caball) {
                    $htmlCabInclusion .= $caball['fromPlace'] . ' to ' . $caball['toPlace'] . ' <strong>(Car)</strong> ';
                    $cr++;
                    if ($cr < $cntcar) {
                        $htmlCabInclusion .= ' | ';
                    }
                }
            }
            if (!empty($busInfoDisp)) {
                if ($cr > 0) {
                    $htmlBusInclusion .= ' | ';
                }
                $cntbus = count($busInfoDisp);
                $cb = 0;
                foreach ($busInfoDisp as $busall) {
                    $htmlBusInclusion .= $busall['fromPlace'] . ' to ' . $busall['toPlace'] . ' <strong>(Bus)</strong> ';
                    $cb++;
                    if ($cb < $cntbus) {
                        $htmlBusInclusion .= ' | ';
                    }
                }
            }
            if (!empty($railInfoDisp)) {
                if ($cb > 0) {
                    $htmlRailInclusion .= ' | ';
                }
                $cntrail = count($railInfoDisp);
                $crail = 0;
                foreach ($railInfoDisp as $railall) {
                    $htmlRailInclusion .= $railall['fromPlace'] . ' to ' . $railall['toPlace'] . ' <strong>(Rail)</strong> ';
                    $crail++;
                    if ($crail < $crail) {
                        $htmlRailInclusion .= ' | ';
                    }
                }
            }
            if (!empty($packageDetail['cruiseData'])) {
                foreach ($packageDetail['cruiseData'] as $cruiseall) {
                    if ($cruiseall['IsDisplay'] == 1) {
                        $dwsCruise[$cruiseall['SeqId']][] = 'Transfer From ' . $cruiseall['EmbarkPortTitle'] . ' to ' . $cruiseall['DebarkPortTitle'];

                        $htmlCruiseInclusion .= ' | ';
                        $htmlCruiseInclusion .= $cruiseall['EmbarkPortTitle'] . ' to ' . $cruiseall['DebarkPortTitle'] . ' <strong>(Cruise)</strong> ';
                        $cru++;
                    }
                }
            }
            $cityWiseSSArr = array();
            //echo "<pre>"; print_r($this->getCityWiseSS);
            foreach ($packageDetail['getCityWiseSS'] as $CitySS) {
                $cityName = $CitySS['CityName'][0];
                foreach ($CitySS['Title'] as $title) {
                    $cityWiseSSArr[$cityName][] = $title;
                }
                //$cityWiseSSArr['City']=$CitySS;
            }
            //$cityWiseSSArrHtml = '';
            //        echo $cityWiseSSArrHtml;die;
            $paramArray = array();
            $paramArray['destinationCoveredCities'] = rtrim(trim($packageDetail['DestinationCity']), ',');
            $paramArray['NoofNights'] = $packageDetail['NoofNights'];
            $paramArray['DestinationPlaces'] = implode(', ', explode(',', $transactiontravelplandata[0]['DestinationPlaces']));
            $paramArray['DestinationPlacesNameArr'] = explode(',', $queryDetails[0]['DestinationPlaces']);
            $paramArray['SourcePlaces'] = trim($transactiontravelplandata[0]['SourcePlaces']);
            $paramArray['QueryDestinationPlaces'] = trim($queryDetails[0]['DestinationPlaces']);
            $paramArray['TotalPax'] = $packageDetail['totalPaxOnly'];
            $paramArray['roomCount'] = (isset($packageDetail['onlyCount']['roomCount']) && $packageDetail['onlyCount']['roomCount'] != 0) ? $packageDetail['onlyCount']['roomCount'] : '';
            $paramArray['StartDate'] = date('D, d M, Y', strtotime($packageDetail['TravellingOn']));
            $paramArray['TravellingOn'] = date('Y-m-d', strtotime($packageDetail['TravellingOn']));
            $paramArray['sentprice'] = ($sentprice);
            $paramArray['finalPrice'] = ($finalPrice);
            $paramArray['getHotelsBySequenceArray'] = $packageDetail['getHotelsBySequenceArray'];
            $paramArray['htmlHotelInclusion'] = $htmlHotelInclusion;
            $paramArray['htmlFlightInclusion'] = $htmlFlightInclusion;
            $paramArray['Transfers'] = $htmlCabInclusion . $htmlBusInclusion . $htmlRailInclusion . $htmlCruiseInclusion;
            $paramArray['cityWiseSSArr'] = $cityWiseSSArr;
            $paramArray['getFlightDetail'] = $packageDetail['getFlightDetail'];
            $paramArray['Inclusions'] = $packageDetail['Inclusions'];
            $paramArray['Exclusions'] = $packageDetail['Exclusions'];
            $paramArray['CancellationPolicy'] = $packageDetail['CancellationPolicy'];
            $paramArray['TermsAndConditions'] = $packageDetail['TermsAndConditions'];
            $paramArray['PaymentTerms'] = $packageDetail['PaymentTerms'];
            $paramArray['BookingTerms'] = $packageDetail['BookingTerms'];
            $paramArray['shared_url'] = $booknowurl;
            $paramArray['getTransportDetail'] = $packageDetail['getTransportDetail'];
            ;
            $paramArray['getDaywiseMergedActSightseeingArr'] = $packageDetail['getDaywiseMergedActSightseeingArr'];
            $paramArray['getDaywiseWiseSSDetail'] = $packageDetail['getDaywiseWiseSSDetail'];
            $paramArray['htmlFlightInclusionArr'] = $htmlFlightInclusionArr;
            $paramArray['htmlGuideDaywise'] = $htmlGuideDaywise;
            $paramArray['htmlMissDaywise'] = $htmlMissDaywise;
            $paramArray['dwsCab'] = $dwsCab;
            $paramArray['dwsCabDaywise'] = $dwsCabDaywise;
            $paramArray['dwsBus'] = $dwsBus;
            $paramArray['dwsBusDaywise'] = $dwsBusDaywise;
            $paramArray['dwsRail'] = $dwsRail;
            $paramArray['dwsRailDaywise'] = $dwsRailDaywise;
            $paramArray['dwsCruise'] = $dwsCruise;
            $paramArray['itenDetailArr'] = $packageDetail['itenDetailArr'];
            $paramArray['PackageName'] = $packageDetail['PackageName'];
            $paramArray['EconomyMask'] = $packageDetail['EconomyMask'];
            $paramArray['PackSpecType'] = $packageDetail['PackSpecType'];
            $paramArray['ShareCombinedFlightPricing'] = $packageDetail['ShareCombinedFlightPricing'];
            $paramArray['EmailText'] = json_decode($transactiontravelplandata[0]['EmailText'], 1);
            $paramArray['CurrSymbol'] = $CurrSymbol;
            $paramArray['IsShareWithGST'] = $transactiontravelplandata[0]['IsShareWithGST'];
            $paramArray['GSTApplicable'] = $transactiontravelplandata[0]['GSTSharedMode'];
            $paramArray['PPCostBreakup'] = isset($packageDetail['PPCostBreakup']) ? $packageDetail['PPCostBreakup'] : array();
            $paramArray['TotalGST'] = isset($packageDetail['TotalGST']) ? $packageDetail['TotalGST'] : '';
            $paramArray['getAgencyDetailArr'] = $getAgencyDetailArr;
            $DestinationPlacesSysId = explode(',', $transactiontravelplandata[0]['DestinationPlacesSysId']);
            $this->view->baseUrl = $baseUrl;
            $this->view->FullName = $FullName;
            $this->view->agentDetails = $agentDetails;
            $this->view->agencyId = $agencyId;
            $this->view->paramArray = $paramArray;
            $this->view->GSTApplicable = $transactiontravelplandata[0]['GSTSharedMode'];
        }
    }

    public function updateOptionalDataPriceAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $baseUrl = $this->baseUrl;
        $objPackage = new Travel_Model_TblPackage();
        $TblAgency = new Travel_Model_TblAgency();
        $this->_crmcustomertravelMarketPlaces = new Travel_Model_CRM_CustomerTravelItenaryMarketRate();
        $this->_crmcustomertravelPlanRate = new Travel_Model_CRM_CustomerTravelPackRate();
        $objCust = new Travel_Model_CRM_CustomerTravelPlan();

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            $TPSysId = $postData['TPSysId'];
            $VersionId = $postData['versionID'];
            $InvnSysId = $postData['InvnSysId'];
            $title = $postData['title'];
            $price = (int) $postData['price'];
            $TotalCostAdult = (int) $postData['TotalCostAdult'];
            $TotalCostChild = (int) $postData['TotalCostChild'];

            $txt = $postData['txt'];
            $type = $postData['type'];
            $PlanType = 0;
            if ($type == 'hotel') {
                $PlanType = 2;
            } else if ($type == 'sight') {
                $PlanType = 9;
            }
            $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId);
            //echo "<pre>";print_r($transactiontravelplandata);die; 
            $packageRoomInfoArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageRoomInfo(@$transactiontravelplandata[0]['RoomInfoJson'], @$transactiontravelplandata[0]['PKqueryType']);
            $Adults = $packageRoomInfoArr['onlyCount']['adultCount'];
            $Child = $packageRoomInfoArr['onlyCount']['childWBCount'] + $packageRoomInfoArr['onlyCount']['childWOBCount'];
            $infantCount = $packageRoomInfoArr['onlyCount']['infantCount'];
            $RoomInfoJson = json_decode($transactiontravelplandata[0]['RoomInfoJson'], 1);
            $CurrencyType = $transactiontravelplandata[0]['CurrencyType'];

            $saveDataArray = [
                'AgencySysId' => trim($transactiontravelplandata[0]['AgencySysId']),
                'TPSysId' => $TPSysId,
                'CustomerSysId' => trim($transactiontravelplandata[0]['CustomerSysId']),
                'SupplierSysId' => 0,
                'PlanType' => $PlanType,
                'InvnSysId' => $InvnSysId,
                'ServiceTitle' => $title,
                'Comment' => '',
                'AdultCount' => $Adults,
                'ChildCount' => $Child,
                'InfentCount' => $infantCount,
                'CurrencyType' => $transactiontravelplandata[0]['CurrencyType'],
                'GSTTYPE' => $transactiontravelplandata[0]['GSTSharedMode'],
                'Markup' => 0,
                'Cost' => $price,
                'IsActive' => 1,
                'IsMarkForDelete' => 0,
                'CreateDate' => date('Y-m-d'),
                'UpdateDate' => date('Y-m-d'),
            ];

            if ($txt == "Include") {
                try {
                    $return = $objPackage->insertData('TB_Agency_Customer_TravelPlan_AddonServices', $saveDataArray);
                } catch (Exception $error) {
                    $this->view->error_msg = $error->getMessage();
                    echo $error->getMessage();
                    die;
                }
            } else {
                $where = array('AgencySysId = ? ' => trim($transactiontravelplandata[0]['AgencySysId']), 'CustomerSysId = ? ' => trim($transactiontravelplandata[0]['CustomerSysId']), 'TPSysId = ? ' => $TPSysId, 'InvnSysId = ? ' => $InvnSysId, 'PlanType = ? ' => $PlanType);
                $objPackage->deleteTravelPlanAddonServices('TB_Agency_Customer_TravelPlan_AddonServices', $where);
            }
            // $TravelPlanAddon = $objPackage->getTravelPlanAddonServices($transactiontravelplandata[0]['AgencySysId'],$transactiontravelplandata[0]['TPSysId']);  
            $gst = 0;
            if ($transactiontravelplandata[0]['GSTSharedMode'] == 2) {
                $gst = 0;
            } else if ($transactiontravelplandata[0]['GSTSharedMode'] == 1) {
                $gst = (int) (($price * 5) / 100);
                $gstAdult = (int) (($TotalCostAdult * 5) / 100);
                $gstChild = (int) (($TotalCostChild * 5) / 100);
            }
            if ($txt == "Include") {
                $basePrice = (int) $transactiontravelplandata[0]['Price'] + (int) $price;
                $NetPrice = (int) $transactiontravelplandata[0]['NetPrice'] + (int) $price;
                $XServiceTaxAmount = (int) $transactiontravelplandata[0]['XServiceTaxAmount'] + (int) $gst;
            } else {
                $basePrice = (int) $transactiontravelplandata[0]['Price'] - (int) $price;
                $NetPrice = (int) $transactiontravelplandata[0]['NetPrice'] - (int) $price;
                $XServiceTaxAmount = (int) $transactiontravelplandata[0]['XServiceTaxAmount'] - (int) $gst;
            }
            $costPerperson = (int) $TotalCostAdult;
            $Extra_With_Bed = (int) $TotalCostChild + (int) $basePrice;
            $Extra_Child_With_Bed = $Extra_Child_Without_Bed = (int) $TotalCostChild + (int) $basePrice;
            $Infant = $PricePerPerson = 0;
            $data = array(
                'Price' => $basePrice,
                'NetPrice' => $NetPrice,
                'XServiceTaxAmount' => $XServiceTaxAmount,
                'UpdateDate' => date('Y-m-d H:i:s'),
            );
            $where = "TPSysId = " . $TPSysId;
            // echo "<pre>";print_r($price);die; 
            $updatetravelplanrecord = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($data, $where);
            $paxCount = array_sum((array_column($RoomInfoJson, 'Adult')));
            $tripdate = $transactiontravelplandata[0]['StartDate']->format('Y-m-d');
            $MarketPlaceId = isset($transactiontravelplandata[0]['MarketPlaceId']) ? $transactiontravelplandata[0]['MarketPlaceId'] : 1;
            $packRate = $objCust->getCustTravelPackRateRowWise($TPSysId, $tripdate, $MarketPlaceId, $paxCount);
            $packMPRate = $objCust->getCustPackRateRowWise($TPSysId, $tripdate, $MarketPlaceId, $paxCount);
            //echo "<pre>";print_r($packMPRate[0]['MarkType']);die;
            $MarkType = $packMPRate[0]['MarkType'];
            $MarkPercent = $packMPRate[0]['MarkPercent'];
            $priceMarkup = 0;
            if ($MarkType == 'FixedPercent') {
                $priceMarkup = ((int) $price * (int) $MarkPercent) / 100;
            } else {
                $priceMarkup = $MarkPercent;
            }
            if ($txt == "Include") {
                //$costPerperson = $costPerperson + $gstAdult;
                $travelmarketpriceArray = array(
                    'CostPPDO' => (float) ($packMPRate[0]['CostPPDO'] + $costPerperson),
//                    'CostFourO' => (float) ($packMPRate[0]['CostFourO']),
//                    'CostSixO' => (float) ($packMPRate[0]['CostSixO']),
//                    'CostEightO' => (float) ($packMPRate[0]['CostEightO']),
//                    'CostTenO' =>  (float) ($packMPRate[0]['CostTenO']),
//                    'CostTwelveO' => (float) ($packMPRate[0]['CostTwelveO']),
                    'CostInfent' => (float) $Infant,
                    'CostPerPerson' => (float) ($packMPRate[0]['CostPerPerson'] + $costPerperson),
                    'PricePerPerson' => (float) ($packMPRate[0]['PricePerPerson']),
                    'TotalCost' => $basePrice,
                    'CostPPSO' => (float) ($packMPRate[0]['CostPPSO'] + $costPerperson),
                    'AdultCostExtraBed' => (float) ($packMPRate[0]['AdultCostExtraBed'] + $Extra_With_Bed),
                    'CostExtraBed' => (float) ($packMPRate[0]['CostExtraBed'] + $Extra_Child_With_Bed),
                    'CostChildWithoutBed' => (float) ($packMPRate[0]['CostChildWithoutBed'] + $Extra_Child_Without_Bed),
//                    'CostPPTO' => 0,
                    'UpdateDate' => date('Y-m-d'),
                );
                $travelpriceArray = array(
                    'CostInfent' => $Infant,
                    'CostSO' => (float) ($packRate[0]['CostSO'] + $costPerperson),
//                    'CostTO' => 0,
                    'AdultCostExtraBed' => (float) ($packRate[0]['AdultCostExtraBed'] + $Extra_With_Bed),
                    'CostExtraBed' => (float) ($packRate[0]['CostExtraBed'] + $Extra_Child_With_Bed),
                    'CostWithoutBed' => (float) ($packRate[0]['CostWithoutBed'] + $Extra_Child_Without_Bed),
                    'CostDO' => (float) ($packRate[0]['CostDO'] + $costPerperson),
//                    'CostFourO' => (float)($packRate[0]['CostFourO']),
//                    'CostSixO' => (float)($packRate[0]['CostSixO']),
//                    'CostEightO' => (float)($packRate[0]['CostEightO']),
//                    'CostTenO' => (float)($packRate[0]['CostTenO']),
//                    'CostTwelveO' => (float)($packRate[0]['CostTwelveO']),
                    'UpdateDate' => date('Y-m-d'),
                );
            } else {
                //$costPerperson = $costPerperson - $gstAdult;
                $travelmarketpriceArray = array(
                    'CostPPDO' => (float) ($packMPRate[0]['CostPPDO'] - $costPerperson),
//                    'CostFourO' => (float) ($packMPRate[0]['CostFourO']),
//                    'CostSixO' => (float) ($packMPRate[0]['CostSixO']),
//                    'CostEightO' => (float) ($packMPRate[0]['CostEightO']),
//                    'CostTenO' =>  (float) ($packMPRate[0]['CostTenO']),
//                    'CostTwelveO' => (float) ($packMPRate[0]['CostTwelveO']),
                    'CostInfent' => (float) $Infant,
                    'CostPerPerson' => (float) ($packMPRate[0]['CostPerPerson'] - $costPerperson),
                    'PricePerPerson' => (float) ($packMPRate[0]['PricePerPerson']),
                    'TotalCost' => $basePrice,
                    'CostPPSO' => (float) ($packMPRate[0]['CostPPSO'] - $costPerperson),
                    'AdultCostExtraBed' => (float) ($packMPRate[0]['AdultCostExtraBed'] - $Extra_With_Bed),
                    'CostExtraBed' => (float) ($packMPRate[0]['CostExtraBed'] - $Extra_Child_With_Bed),
                    'CostChildWithoutBed' => (float) ($packMPRate[0]['CostChildWithoutBed'] - $Extra_Child_Without_Bed),
//                    'CostPPTO' => 0,
                    'UpdateDate' => date('Y-m-d'),
                );
                $travelpriceArray = array(
                    'CostInfent' => $Infant,
                    'CostSO' => (float) ($packRate[0]['CostSO'] + $costPerperson),
//                    'CostTO' => 0,
                    'AdultCostExtraBed' => (float) ($packRate[0]['AdultCostExtraBed'] - $Extra_With_Bed),
                    'CostExtraBed' => (float) ($packRate[0]['CostExtraBed'] - $Extra_Child_With_Bed),
                    'CostWithoutBed' => (float) ($packRate[0]['CostWithoutBed'] - $Extra_Child_Without_Bed),
                    'CostDO' => (float) ($packRate[0]['CostDO'] - $costPerperson),
//                    'CostFourO' => (float)($packRate[0]['CostFourO']),
//                    'CostSixO' => (float)($packRate[0]['CostSixO']),
//                    'CostEightO' => (float)($packRate[0]['CostEightO']),
//                    'CostTenO' => (float)($packRate[0]['CostTenO']),
//                    'CostTwelveO' => (float)($packRate[0]['CostTwelveO']),
                    'UpdateDate' => date('Y-m-d'),
                );
            }
            $where = array('TPIntSysId = ? ' => $TPSysId);
            $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_MarketWise_Rate', $travelmarketpriceArray, $where);
            $wherePack = array('TPSysId = ? ' => $TPSysId);
            $updateId = $objPackage->updateData('TB_Agency_Customer_TravelPlan_Rate', $travelpriceArray, $wherePack);

            //$transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId); 
            //echo "<pre>";print_r($transactiontravelplandata);die; 
            //echo "<pre>";print_r($travelitenryrate);die;  
            $grandtotal = $NetPrice - (int) $transactiontravelplandata[0]['CustomDiscount'] + $priceMarkup;
            echo json_encode(array('TPSysId' => $TPSysId, 'InvnSysId' => $InvnSysId, 'totprice' => $NetPrice, 'grandtotal' => $grandtotal));
            exit;
        }
    }

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

        $TblCurrency = new Travel_Model_TblCurrency();
        $Payment = new Payment_Model_Payment();
        $objPackage = new Travel_Model_TblPackage();
        $params = $this->getRequest()->getParams();
        $TPSysId = isset($params['TPSysId']) ? $params['TPSysId'] : '';
        $this->view->isConf = $isConf = isset($params['isConf']) ? $params['isConf'] : '';
        if ($TPSysId) {
            $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId);
            $AgencySysId = $transactiontravelplandata[0]['AgencySysId'];
            $packageRoomInfoArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageRoomInfo($transactiontravelplandata[0]['RoomInfoJson'], $transactiontravelplandata[0]['PKqueryType']);
            $GetAllService = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServicesDisplay($TPSysId, null, null, 1);
            $this->view->GetAllService = $GetAllService;
//            echo "<pre>";print_r($GetAllService);die;
            //$this->view->CurrencySymbolList = $CurrencySymbolList = $TblCurrency->getCurrencySymbolByIdsList();
            $this->view->CurrencySymbol = $CurrencySymbol = $TblCurrency->getCurrencySymbol($transactiontravelplandata[0]['CurrencyType']);
            $this->view->packageRoomInfoArr = $packageRoomInfoArr;
            $this->view->flexiPackageList = $transactiontravelplandata[0];

            $objGstRates = new Travel_Model_TblGstRates();
            $this->view->arrGSTRatesInfo = $arrGSTRatesInfo = $objGstRates->getGSTTypeAndRates(9, $transactiontravelplandata[0]['GSTSharedMode'], 0, 0);
            $this->view->TcsAddonServicesData = $TcsAddonServicesData = $Payment->getTcsAddonServicesData($AgencySysId, $TPSysId, 21);
            $addOnItemsCurrencyArray = array_column($GetAllService, 'CurrencyType');
            $exchangerateAll = array();
            if (!empty($addOnItemsCurrencyArray)) {
                $AllCurrenciesIds = (!empty($addOnItemsCurrencyArray)) ? implode(',', array_unique($addOnItemsCurrencyArray)) : '';
                $exchangerateArray = $objPackage->multipleCurrencyExchangeRate($AllCurrenciesIds, $transactiontravelplandata[0]['CurrencyType']);
                $MarkUpPersentage = $exchangerateArray['MarkUpPersentage'];
                foreach ($exchangerateArray['conversion'] as $exKey => $exVal) {
                    if ($MarkUpPersentage > 0) {
                        $Rate = isset($exVal['Rate']) ? ((float) $exVal['Rate'] + ((float) ($exVal['Rate']) * $MarkUpPersentage) / 100) : 1;
                    } else {
                        $Rate = isset($exVal['Rate']) ? (float) $exVal['Rate'] : 1;
                    }
                    $exchangerateAll[$exVal['FCurrencyType'] . '-' . $exVal['TCurrencyType']] = $Rate;
                }
            }
            $this->view->exchangerateAll = $exchangerateAll;
//             echo "<pre>";print_r($exchangerateAll);die;           
        }
    }

    public function updateCustomizeAddonItemPopupAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $baseUrl = $this->baseUrl;
        $objPackage = new Travel_Model_TblPackage();
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

            $SightVersionId = (isset($postData['SightVersionId']) && !empty($postData['SightVersionId'])) ? $postData['SightVersionId'] : array();
            $btntype = (isset($postData['btntype']) && !empty($postData['btntype'])) ? $postData['btntype'] : 1;
            $TPSysId = (isset($postData['TPSysId']) && !empty($postData['TPSysId'])) ? $postData['TPSysId'] : '';
            $ServiceTitle = (isset($postData['ServiceTitle']) && !empty($postData['ServiceTitle'])) ? $postData['ServiceTitle'] : array();
            $selectAddon = (isset($postData['selectAddon']) && !empty($postData['selectAddon'])) ? $postData['selectAddon'] : array();
            $IsOptionalServices = (isset($postData['IsOptionalServices']) && !empty($postData['IsOptionalServices'])) ? $postData['IsOptionalServices'] : array();
            $GSTSharedMode = (isset($postData['GSTSharedMode']) && !empty($postData['GSTSharedMode'])) ? $postData['GSTSharedMode'] : 0;
            $AdultTotalHide = (isset($postData['AdultTotalHide']) && !empty($postData['AdultTotalHide'])) ? $postData['AdultTotalHide'] : 0;
            $ChildTotalHide = (isset($postData['ChildTotalHide']) && !empty($postData['ChildTotalHide'])) ? $postData['ChildTotalHide'] : 0;
            if ($btntype == 1) {
                $selectAddon = $IsOptionalServices;
            }

            if (!empty($selectAddon)) {
                $selectAddonStr = trim(implode(',', $selectAddon));
                foreach ($selectAddon as $addonVersionId) {
                    if ($btntype == 1) {
                        
                    } else {
                        $NoofAdults = (isset($postData['NoofAdults'][$addonVersionId])) ? (int) $postData['NoofAdults'][$addonVersionId] : 0;
                        $NoofChild = (isset($postData['NoofChild'][$addonVersionId])) ? (int) $postData['NoofChild'][$addonVersionId] : 0;
                        $NoofItems = (isset($postData['NoofItems'][$addonVersionId])) ? (int) $postData['NoofItems'][$addonVersionId] : 0;
                        $minpax = isset($postData['minpax'][$addonVersionId]) ? $postData['minpax'][$addonVersionId] : 0;
                        $title = isset($ServiceTitle[$addonVersionId]) ? ' for addon (' . $ServiceTitle[$addonVersionId] . ')' : '';

                        if ($postData['RateTypePop'][$addonVersionId] == 1) {
                            $totalPAx = $NoofAdults + $NoofChild;
                            if ($totalPAx < $minpax) {
                                echo json_encode(array('status' => false, 'msg' => 'Please select minimum ' . $minpax . ' pax ' . $title));
                                exit;
                            }
                        } else {
                            if ($NoofItems < $minpax) {
                                echo json_encode(array('status' => false, 'msg' => 'Please select minimum ' . $minpax . ' item(s) ' . $title));
                                exit;
                            }
                        }
                    }
                }
            }
            if (!empty($TPSysId)) {
                $data = array('IsSelected' => 0);
                $where = array('TPIntSysId = ? ' => $TPSysId);
                $objPackage->updateData('TB_Agency_Customer_TravelPlan_OtherServices', $data, $where);
                if (!empty($SightVersionId)) {
                    $updateWhereSight = array('VersionId IN(?) ' => $SightVersionId);
                    $updateDataSight = array('Type' => 'Optional');
                    $objPackage->updateData('TB_Agency_Customer_TravelPlan_SightSeeing', $updateDataSight, $updateWhereSight);
                }

                if (!empty($selectAddon)) {
                    $selectAddonStr = trim(implode(',', $selectAddon));
                    foreach ($selectAddon as $addonVersionId) {
                        if ($btntype == 1) {
                            $data1 = array(
                                'IsSelected' => 1,
                                'TotalAdult' => (isset($AdultTotalHide)) ? (int) $AdultTotalHide : 0,
                                'TotalChild' => (isset($ChildTotalHide)) ? (int) $ChildTotalHide : 0,
                                'TotalItem' => isset($postData['minpax'][$addonVersionId]) ? $postData['minpax'][$addonVersionId] : 1
                            );
                        } else {
                            $data1 = array(
                                'IsSelected' => 1,
                                'TotalAdult' => (isset($postData['NoofAdults'][$addonVersionId])) ? (int) $postData['NoofAdults'][$addonVersionId] : 0,
                                'TotalChild' => (isset($postData['NoofChild'][$addonVersionId])) ? (int) $postData['NoofChild'][$addonVersionId] : 0,
                                'TotalItem' => (isset($postData['NoofItems'][$addonVersionId])) ? (int) $postData['NoofItems'][$addonVersionId] : 0,
                            );
                        }


                        $where1 = array('VersionId = ? ' => $addonVersionId, 'TPIntSysId = ? ' => $TPSysId);
                        //$where1 = "VersionId IN (" . $addonVersionId . ") AND TPIntSysId = ".$TPSysId;
                        $objPackage->updateData('TB_Agency_Customer_TravelPlan_OtherServices', $data1, $where1);
                        $VersionIdSight = (isset($SightVersionId[$addonVersionId])) ? (int) $SightVersionId[$addonVersionId] : 0;
                        if (!empty($VersionIdSight)) {
                            $updateWhereSight1 = array('VersionId = ? ' => $VersionIdSight);
                            $updateDataSight1 = array('Type' => 'Included');
                            $objPackage->updateData('TB_Agency_Customer_TravelPlan_SightSeeing', $updateDataSight1, $updateWhereSight1);
                        }
                    }
                }

                $GetAllServiceSelected = $this->_crmcusttravelplan->GetCustomerTravelPlanOtherServicesDisplay($TPSysId, null, null, 1);
                $addOnItemsCurrencyArray = array_column($GetAllServiceSelected, 'CurrencyType');
                $exchangerateAll = array();
                if (!empty($addOnItemsCurrencyArray)) {
                    $AllCurrenciesIds = (!empty($addOnItemsCurrencyArray)) ? implode(',', array_unique($addOnItemsCurrencyArray)) : '';
                    $exchangerateArray = $objPackage->multipleCurrencyExchangeRate($AllCurrenciesIds, $GetAllServiceSelected[0]['SharedCurrencyType']);
                    $MarkUpPersentage = $exchangerateArray['MarkUpPersentage'];
                    foreach ($exchangerateArray['conversion'] as $exKey => $exVal) {
                        if ($MarkUpPersentage > 0) {
                            $Rate = isset($exVal['Rate']) ? ((float) $exVal['Rate'] + ((float) ($exVal['Rate']) * $MarkUpPersentage) / 100) : 1;
                        } else {
                            $Rate = isset($exVal['Rate']) ? (float) $exVal['Rate'] : 1;
                        }
                        $exchangerateAll[$exVal['FCurrencyType'] . '-' . $exVal['TCurrencyType']] = $Rate;
                    }
                }
                if (!empty($GetAllServiceSelected)) {
                    $AgencySysId = (isset($GetAllServiceSelected[0]['AgencySysId'])) ? $GetAllServiceSelected[0]['AgencySysId'] : 0;
                    $Payment = new Payment_Model_Payment();
                    $TotalCostPack = $Payment->getTcsAddonServicesPriceByPlanType($AgencySysId, $TPSysId, array(5, 1));

                    $TotalCost = 0;
                    foreach ($GetAllServiceSelected as $ssKey => $ssVal) {
                        $exchangerate = (isset($exchangerateAll[$ssVal['CurrencyType'] . '-' . $ssVal['SharedCurrencyType']])) ? $exchangerateAll[$ssVal['CurrencyType'] . '-' . $ssVal['SharedCurrencyType']] : 1;
                        if ($ssVal['IsSelected'] == 1) {
                            if ($ssVal['RateType'] == 1) {
                                $TotalCost += (int) ($ssVal['AdultCost'] * $exchangerate * $ssVal['TotalAdult']) + (int) ($ssVal['ChildCost'] * $exchangerate * $ssVal['TotalChild']);
                            } else {
                                $TotalCost += (int) ($ssVal['Cost'] * $exchangerate * $ssVal['TotalItem']);
                            }
                        }
                    }

                    $arrInputData = array(
                        "GSTApplicableOn" => $GSTSharedMode,
                        "intProductType" => 9,
                        "intProductGeoType" => 1,
                        "Cost" => $TotalCost,
                        "AgencyMarkUp" => 0,
                        "AgencyExtraMarkUp" => 0,
                        "AgencyDiscount" => 0
                    );
                    $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
                    $GSTAmount = $arrGSTCalculations['GSTAmount'];
                    $AmountWithGST = $arrGSTCalculations['AmountWithGST'];
                    $dataTravelPlan = array('TotalCostGen' => $AmountWithGST, 'ServiceProiderFee' => $GSTAmount);
                    $whereTravelPlan = array('TPSysId = ? ' => $TPSysId);
                    $objPackage->updateData('TB_Agency_Customer_TravelPlan', $dataTravelPlan, $whereTravelPlan);
                    $Payment = new Payment_Model_Payment();
                    $NetPrice = (int) ($TotalCostPack + $AmountWithGST);
                    if (!empty($AgencySysId) && !empty($TPSysId)) {
                        $Payment->checkAndUpdateTcsAddonData($AgencySysId, $TPSysId, $NetPrice);
                    }


                    $result = array('status' => true, 'msg' => 'success');
                } else {
                    $result = array('status' => true, 'msg' => 'false');
                }
            } else {
                $result = array('status' => false, 'msg' => 'false');
            }
            echo json_encode($result);
            exit;
        }
    }

    public function sendShareProposalAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $baseUrl = $this->baseUrl;
        $objPackage = new Travel_Model_TblPackage();
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

            $TPSysId = isset($postData['id']) ? (int) $postData['id'] : 0;
            $MasterTPSysId = isset($postData['mid']) ? (int) $postData['mid'] : 0;
            $packtype = isset($postData['packtype']) ? $postData['packtype'] : '';
            $GreetingsMessage = isset($postData['GreetingsMessage']) ? trim($postData['GreetingsMessage']) : '';
            if ($TPSysId > 0) {
                $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($MasterTPSysId, 'Query');
//                $getAgentDetails = $this->_crmcusttravelplan->getAgentDetails($transactiontravelplandata['AgentSysId']);
                $OpsAgentDetails = $this->_crmcusttravelplan->getAgentDetails($transactiontravelplandata[0]['OpsAgentSysId']);
                $CustomerFirstName = trim($transactiontravelplandata[0]['FirstName']);
                $CustomerLastName = trim($transactiontravelplandata[0]['LastName']);

                $EmailId = $transactiontravelplandata[0]['agEmailId'];
                $FirstName = trim($transactiontravelplandata[0]['agFirstName']);
                $LastName = trim($transactiontravelplandata[0]['agLastName']);
                $FullName = trim($FirstName . ' ' . $LastName);
                $fromEmail = $OpsAgentDetails['EmailId'];
                $fromName = trim($OpsAgentDetails['FirstName'] . ' ' . $OpsAgentDetails['LastName']);

                if ($packtype == 'pro') {
                    $secureCode = Catabatic_ValidateCustomer::secureCode($MasterTPSysId, 1);
                    $packageUrl = $this->view->baseUrl("/build-your-own/preview/index/tpid/" . base64_encode($TPSysId) . "/qid/" . $MasterTPSysId . '/code/' . $secureCode . '/opt/1');
                } else {
                    $secureCode = Catabatic_ValidateCustomer::secureCode(base64_encode($TPSysId), 1);
                    $packageUrl = $this->view->baseUrl("/publicpackage/view-customer-final-package/id/" . base64_encode($TPSysId) . '/code/' . $secureCode);
                }
                $bitly_response = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->getSmallLinkFromBitlyAPI($packageUrl, $this->BITLYLOGIN, $this->BITLYAPIKEY);
                if ($bitly_response['errorCode'] == 0) {
                    $packageUrl = $bitly_response['results'][trim($packageUrl)]['shortUrl'];
                }

                $packageRoomInfoArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageRoomInfo($transactiontravelplandata[0]['RoomInfoJson'], $transactiontravelplandata[0]['PKqueryType']);
//                echo "<pre>";print_r($OpsAgentDetails['ContactNo1']);die;  
                $custparams = array(
                    'opsStaffName' => trim($fromName),
                    'opsStaffContactNo' => trim($OpsAgentDetails['ContactNo1']),
                    'agentName' => trim($FirstName . ' ' . $LastName),
                    'packageUrl' => $packageUrl,
                    'CompanyName' => $transactiontravelplandata[0]['CompanyName'],
                    'GreetingsMessage' => $GreetingsMessage,
                    'CustomerName' => $CustomerFirstName . ' ' . $CustomerLastName,
                    'Destination' => (isset($transactiontravelplandata[0]['DestinationPlaces'])) ? trim($transactiontravelplandata[0]['DestinationPlaces']) : '',
                    'QueryID' => $MasterTPSysId,
                    'TravelDate' => (isset($transactiontravelplandata[0]['StartDate'])) ? $transactiontravelplandata[0]['StartDate']->format('d M y') : '',
                    'NoofPax' => $packageRoomInfoArr['totalPaxOnly'],
                );
                $subjectCust = 'Proposal Received from Ops for ' . $CustomerFirstName . ' for Query ID ' . $MasterTPSysId;
                $custhtml = new Zend_View();
                $custhtml->setScriptPath(APPLICATION_PATH . '/views/emails/');
                $custhtml->assign($custparams);
                $custbodyText = $custhtml->render('proposalRequest.phtml');

                $ccEmail = array($OpsAgentDetails['EmailId']);
                $custemailData = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subjectCust, 'to' => $ccEmail, 'bodyHtml' => $custbodyText, 'bodyText' => '');
                $emailData_senderCC = array('fromEmail' => $fromEmail, 'fromName' => $fromName, 'subject' => $subjectCust, 'to' => array($EmailId), 'bodyHtml' => $custbodyText, 'bodyText' => '');
                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => $TPSysId,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => 0,
                    "AgentSysId" => 0,
                    "Title" => $custbodyText,
                    "Source" => $arrEmailStatisticsType[2], // 7 For Misc
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss')
                );
                $checkStatus2 = $this->mailSentByElastice($custemailData, $arrEmailStatistics);

                $arrEmailStatisticsAgent = $arrEmailStatistics;
                $arrEmailStatisticsAgent["Source"] = $arrEmailStatisticsType[2];
                if (!empty($ccEmail)) {
                    Catabatic_ValidateCustomer::mailSentByElastice($emailData_senderCC, $arrEmailStatisticsAgent, 0, 0, $ccEmail);
                }
                if ($checkStatus2) {
                    $return = array('status' => true, 'message' => 'Intimation sent to ' . $FullName . '.');
                } else {
                    $return = array('status' => false, 'message' => 'Unable to share!!');
                }
            } else {
                $return = array('status' => false, 'message' => 'ID missing, Unable to share!!');
            }

            echo json_encode($return);
            exit;
        }
    }

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

        $TblCurrency = new Travel_Model_TblCurrency();
        $Payment = new Payment_Model_Payment();
        $objPackage = new Travel_Model_TblPackage();
        $params = $this->getRequest()->getParams();
        $TPSysId = isset($params['TPSysId']) ? $params['TPSysId'] : '';
        $this->view->isConf = $isConf = isset($params['isConf']) ? $params['isConf'] : '';
        if ($TPSysId) {
            $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId);
            $getServiceFeeAmount = $this->_crmcusttravelplan->getTcsAmount($TPSysId, 22, 0);
            $transactiontravelplandataOld = $getAdvancedBalance = array();
            if (isset($transactiontravelplandata[0]['RefTPSysId']) && $transactiontravelplandata[0]['RefTPSysId'] > 0) {
                $transactiontravelplandataOld = $this->_crmcusttravelplan->GetTravelPlanByCustomer($transactiontravelplandata[0]['RefTPSysId']);
                $getAdvancedBalance = $this->_crmcusttravelplan->getAdvancedBalance($transactiontravelplandata[0]['RefTPSysId']);
            }
            $this->view->transactiontravelplandata = $transactiontravelplandata;
            $this->view->transactiontravelplandataOld = $transactiontravelplandataOld;
            $this->view->getServiceFeeAmount = $getServiceFeeAmount;
            $this->view->getAdvancedBalance = $getAdvancedBalance;
        }
    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit