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/PackagesearchController_1.php
<?php

/*
 * Catabatic Technology Pvt. Ltd.
 * File Name :PackagesearchController.php
 * File Description :Packagesearch Controller managed all data related to package search
 * Created By : Pooja Choudhary
 * Created Date: 22-August-2016
 */

class PackagesearchController extends Catabatic_ValidateGtx {
    
    public $ReportingToSysId;
    public $intLoggedinUserId;
    public $roleID;
    public $intLoggedinUserGroupSysId;
    public $intLoggedinUserAgencySysId;
    public $intLoggedinUserTrxCurrency;
    public $IsSMSApi;
    public $agencyDetails;
    public $_crmcusttravelplan;
    public $_objPackage;
    public $_crmcustomertravelItenary;
    public $_crmcusttravelplanItenaryAccom;
    public $_crmcustomertravelItenaryEvents;
    public $_crmcustomertravelItenaryPlaces;
    public $_crmcustomertravelSightSeeing;
    public $_crmcustomertravelMarketPlaces;
    public $_crmcustomertravelPlanRate;
    public $_crmcustomertravelTerm;
    public $_crmcustomerObj;
    public $_crmremarkObj;
    public $SupplierTypeSysId;
    public $currentDate;
    public $_HtmlPurifier;
    public $baseUrl;
    public $BITLYLOGIN;
    public $BITLYAPIKEY;
    public $InfoSourceSysId;
    public $paymentMdl;
    private $_agencyuserroleObj;

    public function init() {
        parent::init();
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $this->ReportingToSysId = $sessionLogin_user->ReportingToSysId;
        $this->intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $this->roleID = $sessionLogin_user->UserRole;
        $this->intLoggedinUserGroupSysId = $sessionLogin_user->intLoggedinUserGroupSysId;
        $this->intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->view->intLoggedinUserTrxCurrency = $this->intLoggedinUserTrxCurrency = $sessionLogin_user->intLoggedinUserTrxCurrency;
        $this->IsSMSApi = $sessionLogin_user->agencyDetails['IsSMSApi'];
        $this->agencyDetails = $sessionLogin_user->agencyDetails;
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $this->_objPackage = new Travel_Model_TblPackage();
        $this->_crmcustomertravelItenary = new Travel_Model_CRM_CustomerTravelItenary();
        $this->_crmcusttravelplanItenaryAccom = new Travel_Model_CRM_CustomerTravelPlanAccom();
        $this->_crmcustomertravelItenaryEvents = new Travel_Model_CRM_CustomerTravelItenaryEvents();
        $this->_crmcustomertravelItenaryPlaces = new Travel_Model_CRM_CustomerTravelItenaryPlaces();
        $this->_crmcustomertravelSightSeeing = new Travel_Model_CRM_CustomerTravelItenarySightSeeing();
        $this->_crmcustomertravelMarketPlaces = new Travel_Model_CRM_CustomerTravelItenaryMarketRate();
        $this->_crmcustomertravelPlanRate = new Travel_Model_CRM_CustomerTravelPackRate();
        $this->_crmcustomertravelTerm = new Travel_Model_CRM_CustomerTravelTerm();
        $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
        $this->_crmremarkObj = new Travel_Model_CRM_Remark();
        $this->SupplierTypeSysId = 9;
        $this->currentDate = date('Y-m-d H:i:s');
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $this->baseUrl = $request->getScheme() . '://' . $request->getHttpHost();
        $this->BITLYLOGIN = 'gpurwar';
        $this->BITLYAPIKEY = 'R_c1c94b5c789249d5a59d585bc0e7ef80';
        if (!empty($this->intLoggedinUserAgencySysId)) {
            $this->InfoSourceSysId = '2'; // Information Source is Agent //
        }
        $this->paymentMdl = new Payment_Model_Payment();
        //        error_reporting(E_ALL);
    }

    public function indexAction() {
        $objPackage = new Travel_Model_PackageSearch();
        $packageThemeList = $objPackage->getPackageThemeList();
        $this->view->packageThemeList = $packageThemeList;
        $packageInclusionList = $objPackage->getPackageInclusionList();
        $this->view->packageInclusionList = $packageInclusionList;
        $foodPreferenceList = $objPackage->getFoodPreferenceList();
        $this->view->foodPreferenceList = $foodPreferenceList;
    }

    public function searchResultAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->_layout->setLayout('layout-search')->setLayoutPath(APPLICATION_PATH . '/layouts/scripts');
        $AgencySysId = $this->intLoggedinUserAgencySysId;
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
        }
        //echo "<pre>";print_r($_SESSION);exit;
        $economyArray = array(1 => 'Budget', 'Standard', 'Deluxe', 'Luxury', 'Premium');
        $sessionPackageFilterData = new Zend_Session_Namespace('sessionPackageFilterData');
        $sessionPackageFilterData->filterData = array();
        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $getDataFinal = $sessionPackageSearchData->searchData;
        $paxCount = array_sum((array_column(json_decode($getDataFinal['roominfojson'], true), 'Adult')));

        if ($paxCount == 1) {
            $paxCount = 2;
        } else if ($paxCount % 2 != 0) {
            $paxCount = $paxCount - 1;
        }

        $this->view->IsNetworkTab = 0;
        if (!empty($sessionPackageSearchData->searchData)) {
            if (!empty($getDataFinal) && trim(@$getDataFinal['is_source']) == 'CRM' && $getDataFinal['customerID'] > 0) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById(trim($getDataFinal['customerID']));
                $sessionPackageSearchData->searchData['customerDetails'] = $customerDetails;
            }
            $getDataFinal['IsB2BAgent'] = $customerDetails['IsB2BAgent'];
            $getDataFinal['MarketPlaceId'] = $getDataFinal['IsB2BAgent'] == 1 ? 2 : 1;
            $this->view->IsB2BCustomer = $customerDetails['IsB2BAgent'];
            $TblPackageSearch = new Travel_Model_TblPackageSearch();
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            if (in_array('ShowNetworkPackageInGTX', $sessionLogin_user->manageNotifications)) {
                $readymadePackageSearchResult = $TblPackageSearch->searchPackageWithAllNetwork($AgencySysId, $getDataFinal);
            } else {
                $readymadePackageSearchResult = $TblPackageSearch->searchPackage($AgencySysId, $getDataFinal);
            }
            $this->view->IsNetworkTab = array();
            $packageSearchResult = $getOtherData = $ReadymadeArray = $checkFixedDepature = array();
            $this->view->otherData = array();
            $i = 0;
            foreach ($readymadePackageSearchResult as $readymadePackageSearchResultVal) {
                if (!in_array($readymadePackageSearchResultVal['TPSysId'], $ReadymadeArray)) {
                    $ReadymadeArray[] = $readymadePackageSearchResultVal['TPSysId'];
                }
            }
            if (!empty($ReadymadeArray)) {
                $modelProcedure = new Gtxwebservices_Model_Createxml();
                $getOtherData = $modelProcedure->getPackageOtherData($ReadymadeArray, $AgencySysId, $getDataFinal['MarketPlaceId'], $paxCount);
                //echo "<pre>";print_r($getOtherData);exit;
                $this->view->otherData = $getOtherData;
                $sightseeingDataArray = $categoryDataArray = array();
                foreach ($getOtherData['Result1'] as $otKey => $otVal) {
                    $Title = $otVal['Title'];
                    $SSSysId = $otVal['SSSysId'];
                    $sightseeingDataArray[$otVal['TPSysId']][$otVal['Sequence']][] = '<a data-toggle="modal" data-target="#myModalPkg" href="javascript:void(0);" onclick="getsightdetails(' . $SSSysId . ')">' . trim($Title) . ' </a>';
                }
                foreach ($getOtherData['Result2'] as $otKey2 => $otVal2) {
                    if (isset($otVal2['PackSpecType']) && $otVal2['PackSpecType'] == 3) {
                        $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['EconomyMask'] = $otVal2['PackCategoryId'];
                        $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['EconomyMaskTitle'] = $economyArray[$otVal2['PackCategoryId']];
                        $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['CostPPDO'] = $otVal2['CostPPDO'];
                    } else {
                        if ($otVal2['MasterRefId'] == 0) {
                            $categoryDataArray[$otVal2['TPSysId']][$otVal2['TPSysId']]['EconomyMask'] = $otVal2['EconomyMask'];
                            $categoryDataArray[$otVal2['TPSysId']][$otVal2['TPSysId']]['EconomyMaskTitle'] = isset($otVal2['PackageCategoryName']) && !empty($otVal2['PackageCategoryName']) ? $otVal2['PackageCategoryName'] : $economyArray[$otVal2['EconomyMask']];
                        } else {
                            $categoryDataArray[$otVal2['MasterRefId']][$otVal2['TPSysId']]['EconomyMask'] = $otVal2['EconomyMask'];
                            $categoryDataArray[$otVal2['MasterRefId']][$otVal2['TPSysId']]['EconomyMaskTitle'] = isset($otVal2['PackageCategoryName']) && !empty($otVal2['PackageCategoryName']) ? $otVal2['PackageCategoryName'] : $economyArray[$otVal2['EconomyMask']];
                        }
                    }
                }
                $this->view->sightseeingDataArray = $sightseeingDataArray;
                $this->view->categoryDataArray = $categoryDataArray;
            }

            $ExchangeRateMaarkup = $this->agencyDetails['ExchangeRateMaarkup'];
            $CurrencyConversionArray = array();
            foreach ($getOtherData['Result14'] as $cKey => $cVal) {
                $RateWithMarkup = (float) $cVal['Rate'] + (float) $cVal['Rate'] * $ExchangeRateMaarkup / 100;
                $CurrencyConversionArray[$cVal['FCurrencyType'] . '-' . $cVal['TCurrencyType']] = $RateWithMarkup;
            }
            $ReadymadeCostArray = array();
            $currentDate = date('Y-m-d');
            if ($getDataFinal['search_specific_date'] && $getDataFinal['search_specific_date'] != '__/__/____') {
                $tripDate = $getDataFinal['search_specific_date'];
            } else {
                $tripDate = date('d/m/Y');
            }
            $travelDate = date("Y-m-d", strtotime(str_replace('/', '-', $tripDate)));
            $date1 = new DateTime($currentDate);
            $date2 = new DateTime($travelDate);
            $interval = $date1->diff($date2);
            $diffDays = $interval->days;
            foreach ($readymadePackageSearchResult as $readymadePackageSearchResultVal) {
                //echo "<pre>";print_r($getDataFinal);die;
                $bookingvalidityDay = (int) $readymadePackageSearchResultVal['bookingvalidityDay'];
                if ($diffDays < $bookingvalidityDay) {
                    continue;
                }
                $IsGTXNetwork = (int) $readymadePackageSearchResultVal['IsGTXNetwork'];
                $packageSearchResult[$i]['AgencySysId'] = trim($readymadePackageSearchResultVal['AgencySysId']);
                ;
                $packageSearchResult[$i]['IsGTXNetwork'] = $IsGTXNetwork;
                $packageSearchResult[$i]['TPSysId'] = trim($readymadePackageSearchResultVal['TPSysId']);
                $packageSearchResult[$i]['Title'] = $readymadePackageSearchResultVal['Title'];
                $packageSearchResult[$i]['SourcePlaces'] = $readymadePackageSearchResultVal['SourcePlaces'];
                $packageSearchResult[$i]['DestinationPlaces'] = $readymadePackageSearchResultVal['DestinationPlaces'];
                $packageSearchResult[$i]['secureCode'] = Catabatic_ValidateCustomer::secureCode($packageSearchResult[$i]['TPSysId'], $IsGTXNetwork);
                $packageSearchResult[$i]['InclMask'] = $readymadePackageSearchResultVal['InclMask'];
                $packageSearchResult[$i]['MasterRefId'] = $readymadePackageSearchResultVal['MasterRefId'];
                $packageSearchResult[$i]['EconomyMask'] = $readymadePackageSearchResultVal['EconomyMask'];
                $packageSearchResult[$i]['PackSpecType'] = $readymadePackageSearchResultVal['PackSpecType'];
                $packageSearchResult[$i]['IsFixedDeparturePackage'] = $readymadePackageSearchResultVal['IsFixedDeparturePackage'];
                $packageSearchResult[$i]['IsCommonFlightPackage'] = $readymadePackageSearchResultVal['IsCommonFlightPackage'];
                $packageSearchResult[$i]['SupplierSysId'] = $readymadePackageSearchResultVal['SupplierSysId'];
                $packageSearchResult[$i]['SupplierName'] = $readymadePackageSearchResultVal['SupplierName'];
                $packageSearchResult[$i]['SupplierRating'] = $readymadePackageSearchResultVal['SupplierRating'];
                $packageSearchResult[$i]['days'] = $readymadePackageSearchResultVal['days'];
                $packageSearchResult[$i]['PACKAGETYPE'] = 'READYMADE';
                if ($readymadePackageSearchResultVal['PackSpecType'] == 3) {
                    $packageSearchResult[$i]['PACKAGETYPE'] = 'DYNAMIC';
                }
                $packageSearchResult[$i]['TPRateSheetSysId'] = $readymadePackageSearchResultVal['TPRateSheetSysId'];
                $packageSearchResult[$i]['BYOPackTypeMask'] = '';
                $packageSearchResult[$i]['TourType'] = '';
                $packageSearchResult[$i]['PackCategoryId'] = '';
                $packageSearchResult[$i]['MinPax'] = '';
                $packageSearchResult[$i]['GroupSize'] = '';
                $packageSearchResult[$i]['CancellationPolicy'] = $readymadePackageSearchResultVal['CancellationPolicy'];
                $packageSearchResult[$i]['Exclusions'] = $readymadePackageSearchResultVal['Exclusions'];
                $packageSearchResult[$i]['Inclusions'] = $readymadePackageSearchResultVal['Inclusions'];
                $packageSearchResult[$i]['FlightDepartureCity'] = $packageSearchResult[$i]['CityData'] = $packageSearchResult[$i]['DayTitles'] = array();
                $jj = $sequesceIdPre = $cityIdPre = 0;
                $packageSearchResult[$i]['isdisplay'] = 1;
                $packageSearchResult[$i]['CostPPDO'] = 0;
                if (!empty($getOtherData)) {
                    $kk = 0;
                    if (!empty($getOtherData['Result9'])) {
                        foreach ($getOtherData['Result9'] as $costVal) {
                            if ($costVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                                if (!in_array($costVal['TPSysId'], $ReadymadeCostArray) || $costVal['Pax'] >= $paxCount) {
                                    $ReadymadeCostArray[] = $costVal['TPSysId'];
                                    $packageSearchResult[$i]['CostPPDO'] = $costVal['CostPPDO'];
                                    $packageSearchResult[$i]['CurrencyType'] = $costVal['CurrencyType'];
                                    $fromDate = $costVal['FromDate']->format("Y-m-d");
                                    $packageSearchResult[$i]['FromDate'] = $fromDate;
                                }
                            }
                        }
                        if (!in_array($packageSearchResult[$i]['TPSysId'], $ReadymadeCostArray)) {
                            $packageSearchResult[$i]['isdisplay'] = 0;
                        }
                    } else {
                        $packageSearchResult[$i]['isdisplay'] = 0;
                    }
                    foreach ($getOtherData['Result11'] as $FlightDepartureCityVal) {
                        if ($FlightDepartureCityVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                            $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['CityName'] = $FlightDepartureCityVal['CityName'];
                            $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['DestinationSysId'] = $FlightDepartureCityVal['DestinationSysId'];
                            foreach ($getOtherData['Result13'] as $asFixedDepartureVal) {
                                $dapartureFDate = $asFixedDepartureVal['FromDate']->format("Y-m-d");
                                if ($asFixedDepartureVal['TPSysId'] == $packageSearchResult[$i]['TPSysId'] && ($FlightDepartureCityVal['id'] == $asFixedDepartureVal['FixedInvnSysId'])) {
                                    if ($packageSearchResult[$i]['FromDate'] == $dapartureFDate) {
                                        $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FromDate'] = $dapartureFDate;
                                        if ($asFixedDepartureVal['MarkupType'] == 1) {
                                            $flightCost = $asFixedDepartureVal['B2CAdultMarkup'] + $asFixedDepartureVal['AdultCost'];
                                        } else {
                                            $flightCost = $asFixedDepartureVal['AdultCost'] + ($asFixedDepartureVal['B2CAdultMarkup'] * $asFixedDepartureVal['AdultCost']) / 100;
                                        }
                                        $FlightConversion = 1;
                                        if ($packageSearchResult[$i]['CurrencyType'] != $asFixedDepartureVal['CurrencySysId'] && isset($CurrencyConversionArray[$asFixedDepartureVal['CurrencySysId'] . '-' . $packageSearchResult[$i]['CurrencyType']]) && !empty($CurrencyConversionArray[$asFixedDepartureVal['CurrencySysId'] . '-' . $packageSearchResult[$i]['CurrencyType']])) {
                                            $FlightConversion = $CurrencyConversionArray[$asFixedDepartureVal['CurrencySysId'] . '-' . $packageSearchResult[$i]['CurrencyType']];
                                        }

                                        //echo "<pre>";print_r($FlightConversion);die;
                                        $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightCost'] = $flightCost * $FlightConversion;
                                        $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightCurrency'] = $asFixedDepartureVal['CurrencySysId'];
                                    }
                                }
                            }
                            $kk = 0;
                            foreach ($getOtherData['Result12'] as $asFixedDepartureOtherVal) {
                                if ($asFixedDepartureOtherVal['TPSysId'] == $packageSearchResult[$i]['TPSysId'] && $asFixedDepartureOtherVal['FixedInvnSysId'] == $FlightDepartureCityVal['id']) {
                                    $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightOtherDetail'][$asFixedDepartureOtherVal['FlightType']][$kk] = $asFixedDepartureOtherVal;
                                    $kk++;
                                }
                            }
                        }
                    }
                    foreach ($getOtherData['Result10'] as $otKey => $otVal) {
                        if ($otVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                            $packageSearchResult[$i]['DayTitles'][$otVal['Sequence']] = !empty($otVal['DayTitle']) ? $otVal['DayTitle'] : '';
                        }
                    }
                    //echo "<pre>";print_r($getOtherData['Result8']);
                    foreach ($getOtherData['Result8'] as $cityDataKey => $cityDataVal) {
                        if ($cityDataVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                            $cityIdCurrent = (int) $cityDataVal['CityId'] . '-' . (int) $cityDataVal['AccomSysId'] . '-' . (int) $cityDataVal['RoomType'] . '-' . (int) $cityDataVal['MealPlanType'];
                            if ($cityIdCurrent != $cityIdPre) {
                                $jj++;
                            }
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['HotelCount'] = $cityDataVal['HotelCount'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['TPIntSysId'] = $cityDataVal['TPIntSysId'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['Sequence'] = $cityDataVal['Sequence'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['CityId'] = $cityDataVal['CityId'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['CityName'] = $cityDataVal['CityName'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['HotelName'] = $cityDataVal['HotelName'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['Stars'] = $cityDataVal['Stars'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['EconomyTypeTitle'] = $cityDataVal['EconomyTypeTitle'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['MealPlanTypeTitle'] = $cityDataVal['MealPlanTypeTitle'];
                            $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['AccomSysId'] = $cityDataVal['AccomSysId'];
                            $sequesceIdPre = $cityDataVal['Sequence'];
                            $cityIdPre = (int) $cityDataVal['CityId'] . '-' . (int) $cityDataVal['AccomSysId'] . '-' . (int) $cityDataVal['RoomType'] . '-' . (int) $cityDataVal['MealPlanType'];
                        }
                    }
                    //                    echo "<pre>";print_r($packageSearchResult[$i]['CityData']);die;
                }
                $i++;
            }

            $packageSearchResultnew = array();
            if (!empty($packageSearchResult)) {
                foreach ($packageSearchResult as $checkpackages) {
                    //if ($checkpackages['isdisplay'] == 1) {
                    $packageSearchResultnew[] = $checkpackages;
                    //}
                }
            }
            $intPageNumber = !empty($this->getRequest()->getPost('page')) ? $this->getRequest()->getPost('page') : '1';
            $intLimitPerPage = 500;
            $page = $this->_getParam('page', $intPageNumber);
            $packageSearchResultPagignation = Zend_Paginator::factory($packageSearchResultnew);
            $packageSearchResultPagignation->setItemCountPerPage($intLimitPerPage);
            $packageSearchResultPagignation->setCurrentPageNumber($page);
            $this->view->packageSearchResult = $packageSearchResultPagignation;
            $this->view->sessionFlag = $intPageNumber;
            $this->view->count = $page * $intLimitPerPage;
            $this->view->getDataFinal = $getDataFinal;
            $this->view->packageThemeList = isset($this->view->otherData['Result5']) ? $this->view->otherData['Result5'] : array();
            $this->view->packageInclusionList = isset($this->view->otherData['Result6']) ? $this->view->otherData['Result6'] : array();
            $this->view->foodPreferenceList = isset($this->view->otherData['Result7']) ? $this->view->otherData['Result7'] : array();
            $this->view->getleadSource = isset($this->view->otherData['Result3']) ? $this->view->otherData['Result3'] : array();
            $getAllCurrency = isset($this->view->otherData['Result4']) ? $this->view->otherData['Result4'] : array();
            $getAllCurrencyArr = array();
            foreach ($getAllCurrency as $cKey => $cVal) {
                $getAllCurrencyArr[$cVal['CurrencyType']] = $cVal['Symbol'];
            }
            $this->view->getAllCurrency = $getAllCurrencyArr;
            $this->view->CurrencyConversionArray = $CurrencyConversionArray;
            if ($page != 1) {
                $this->render('search-result-include');
            }
        } else {
            $this->_redirect('/dashboard/agency');
        }
    }

    public function searchResultIncludeAction() {
        $AgencySysId = $this->intLoggedinUserAgencySysId;
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            if (isset($getData['sorting']) && $getData['sorting'] == '') {
                $sessionPackageFilterData->filterData = $getData;
            } else {
                $sorting = $getData;
            }
            $this->view->getDatasorting = isset($getData) ? $getData : '';
            $objPackage = new Travel_Model_PackageSearch();
            $packageThemeList = $objPackage->getPackageThemeList();
            $this->view->packageThemeList = $packageThemeList;
            $packageInclusionList = $objPackage->getPackageInclusionList();
            $this->view->packageInclusionList = $packageInclusionList;
            $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
            $getDataFinal = $sessionPackageSearchData->searchData;
            $paxCount = array_sum((array_column(json_decode($getDataFinal['roominfojson'], true), 'Adult')));
            if ($paxCount % 2 != 0) {
                $paxCount = $paxCount - 1;
            } else if ($paxCount == 1) {
                $paxCount = 2;
            }
            if (!empty($sessionPackageSearchData->searchData)) {
                if (!empty($getDataFinal) && trim(@$getDataFinal['is_source']) == 'CRM' && $getDataFinal['customerID'] > 0) {
                    $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                    $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById(trim($getDataFinal['customerID']));
                    $sessionPackageSearchData->searchData['customerDetails'] = $customerDetails;
                }
                $sessionPackageSearchData->searchData['IsB2BAgent'] = $customerDetails['IsB2BAgent'];
                $sessionPackageSearchData->searchData['MarketPlaceId'] = $customerDetails['IsB2BAgent'] == 1 ? 2 : 1;
            }
            $economyArray = array(1 => 'Budget', 'Standard', 'Deluxe', 'Luxury', 'Premium');
            $this->view->IsNetworkTab = 0;
            if (!empty($sessionPackageSearchData->searchData)) {
                if (!empty($getDataFinal) && trim(@$getDataFinal['is_source']) == 'CRM' && $getDataFinal['customerID'] > 0) {
                    $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                    $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById(trim($getDataFinal['customerID']));
                    $sessionPackageSearchData->searchData['customerDetails'] = $customerDetails;
                }
                $getDataFinal['IsB2BAgent'] = $customerDetails['IsB2BAgent'];
                $getDataFinal['MarketPlaceId'] = $getDataFinal['IsB2BAgent'] == 1 ? 2 : 1;
                $this->view->IsB2BCustomer = $customerDetails['IsB2BAgent'];
                $TblPackageSearch = new Travel_Model_TblPackageSearch();
                $readymadePackageSearchResult = $TblPackageSearch->searchPackage($AgencySysId, $getDataFinal, $getData);
                // $objPackageNetwork = new Gtxnetwork_Model_PackageSearch();
                // $readymadePackageSearchResultCount = $objPackageNetwork->getPackageSearchDataCount($getDataFinal);
                //  $this->view->IsNetworkTab = $readymadePackageSearchResultCount;
                $packageSearchResult = $getOtherData = $ReadymadeArray = $checkFixedDepature = array();
                $this->view->otherData = array();
                $i = 0;
                foreach ($readymadePackageSearchResult as $readymadePackageSearchResultVal) {
                    if (!in_array($readymadePackageSearchResultVal['TPSysId'], $ReadymadeArray)) {
                        $ReadymadeArray[] = $readymadePackageSearchResultVal['TPSysId'];
                    }
                }
                if (!empty($ReadymadeArray)) {
                    $modelProcedure = new Gtxwebservices_Model_Createxml();
                    $getOtherData = $modelProcedure->getPackageOtherData($ReadymadeArray, $AgencySysId, $getDataFinal['MarketPlaceId'], $paxCount);
                    $this->view->otherData = $getOtherData;
                    $sightseeingDataArray = $categoryDataArray = array();
                    foreach ($getOtherData['Result1'] as $otKey => $otVal) {
                        $Title = $otVal['Title'];
                        $SSSysId = $otVal['SSSysId'];
                        $sightseeingDataArray[$otVal['TPSysId']][$otVal['Sequence']][] = '<a data-toggle="modal" data-target="#myModalPkg" href="javascript:void(0);" onclick="getsightdetails(' . $SSSysId . ')">' . trim($Title) . ' </a>';
                    }
                    foreach ($getOtherData['Result2'] as $otKey2 => $otVal2) {
                        if (isset($otVal2['PackSpecType']) && $otVal2['PackSpecType'] == 3) {
                            $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['EconomyMask'] = $otVal2['PackCategoryId'];
                            $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['EconomyMaskTitle'] = $economyArray[$otVal2['PackCategoryId']];
                            $categoryDataArray[$otVal2['TPSysId']][$otVal2['PackCategoryId']]['CostPPDO'] = $otVal2['CostPPDO'];
                        } else {
                            if ($otVal2['MasterRefId'] == 0) {
                                $categoryDataArray[$otVal2['TPSysId']][$otVal2['TPSysId']]['EconomyMask'] = $otVal2['EconomyMask'];
                                $categoryDataArray[$otVal2['TPSysId']][$otVal2['TPSysId']]['EconomyMaskTitle'] = isset($otVal2['PackageCategoryName']) && !empty($otVal2['PackageCategoryName']) ? $otVal2['PackageCategoryName'] : $economyArray[$otVal2['EconomyMask']];
                            } else {
                                $categoryDataArray[$otVal2['MasterRefId']][$otVal2['TPSysId']]['EconomyMask'] = $otVal2['EconomyMask'];
                                $categoryDataArray[$otVal2['MasterRefId']][$otVal2['TPSysId']]['EconomyMaskTitle'] = isset($otVal2['PackageCategoryName']) && !empty($otVal2['PackageCategoryName']) ? $otVal2['PackageCategoryName'] : $economyArray[$otVal2['EconomyMask']];
                            }
                        }
                    }
                    $this->view->sightseeingDataArray = $sightseeingDataArray;
                    $this->view->categoryDataArray = $categoryDataArray;
                }
                $ReadymadeCostArray = array();
                $currentDate = date('Y-m-d');
                if ($getDataFinal['search_specific_date'] && $getDataFinal['search_specific_date'] != '__/__/____') {
                    $tripDate = $getDataFinal['search_specific_date'];
                } else {
                    $tripDate = date('d/m/Y');
                }
                $travelDate = date("Y-m-d", strtotime(str_replace('/', '-', $tripDate)));
                $date1 = new DateTime($currentDate);
                $date2 = new DateTime($travelDate);
                $interval = $date1->diff($date2);
                $diffDays = $interval->days;
                foreach ($readymadePackageSearchResult as $readymadePackageSearchResultVal) {
                    $bookingvalidityDay = (int) $readymadePackageSearchResultVal['bookingvalidityDay'];
                    if ($diffDays < $bookingvalidityDay) {
                        continue;
                    }
                    $packageSearchResult[$i]['TPSysId'] = trim($readymadePackageSearchResultVal['TPSysId']);
                    $packageSearchResult[$i]['Title'] = $readymadePackageSearchResultVal['Title'];
                    $packageSearchResult[$i]['SourcePlaces'] = $readymadePackageSearchResultVal['SourcePlaces'];
                    $packageSearchResult[$i]['DestinationPlaces'] = $readymadePackageSearchResultVal['DestinationPlaces'];
                    $packageSearchResult[$i]['secureCode'] = Catabatic_ValidateCustomer::secureCode($packageSearchResult[$i]['TPSysId'], 0);
                    $packageSearchResult[$i]['InclMask'] = $readymadePackageSearchResultVal['InclMask'];
                    $packageSearchResult[$i]['MasterRefId'] = $readymadePackageSearchResultVal['MasterRefId'];
                    $packageSearchResult[$i]['EconomyMask'] = $readymadePackageSearchResultVal['EconomyMask'];
                    $packageSearchResult[$i]['PackSpecType'] = $readymadePackageSearchResultVal['PackSpecType'];
                    $packageSearchResult[$i]['IsFixedDeparturePackage'] = $readymadePackageSearchResultVal['IsFixedDeparturePackage'];
                    $packageSearchResult[$i]['SupplierSysId'] = $readymadePackageSearchResultVal['SupplierSysId'];
                    $packageSearchResult[$i]['SupplierName'] = $readymadePackageSearchResultVal['SupplierName'];
                    $packageSearchResult[$i]['SupplierRating'] = $readymadePackageSearchResultVal['SupplierRating'];
                    $packageSearchResult[$i]['days'] = $readymadePackageSearchResultVal['days'];
                    $packageSearchResult[$i]['PACKAGETYPE'] = 'READYMADE';
                    if ($readymadePackageSearchResultVal['PackSpecType'] == 3) {
                        $packageSearchResult[$i]['PACKAGETYPE'] = 'DYNAMIC';
                    }
                    $packageSearchResult[$i]['TPRateSheetSysId'] = $readymadePackageSearchResultVal['TPRateSheetSysId'];
                    $packageSearchResult[$i]['BYOPackTypeMask'] = '';
                    $packageSearchResult[$i]['TourType'] = '';
                    $packageSearchResult[$i]['PackCategoryId'] = '';
                    $packageSearchResult[$i]['MinPax'] = '';
                    $packageSearchResult[$i]['GroupSize'] = '';
                    $packageSearchResult[$i]['CancellationPolicy'] = $readymadePackageSearchResultVal['CancellationPolicy'];
                    $packageSearchResult[$i]['Exclusions'] = $readymadePackageSearchResultVal['Exclusions'];
                    $packageSearchResult[$i]['Inclusions'] = $readymadePackageSearchResultVal['Inclusions'];
                    $packageSearchResult[$i]['FlightDepartureCity'] = $packageSearchResult[$i]['CityData'] = $packageSearchResult[$i]['DayTitles'] = array();
                    $jj = $sequesceIdPre = $cityIdPre = 0;
                    $packageSearchResult[$i]['CostPPDO'] = 0;
                    if (!empty($getOtherData)) {
                        $kk = 0;
                        foreach ($getOtherData['Result9'] as $costVal) {
                            if ($costVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                                if (!in_array($costVal['TPSysId'], $ReadymadeCostArray)) {
                                    $ReadymadeCostArray[] = $costVal['TPSysId'];
                                    $packageSearchResult[$i]['CostPPDO'] = $costVal['CostPPDO'];
                                    $packageSearchResult[$i]['CurrencyType'] = $costVal['CurrencyType'];
                                    $fromDate = $costVal['FromDate']->format("Y-m-d");
                                    $packageSearchResult[$i]['FromDate'] = $fromDate;
                                }
                            }
                        }
                        foreach ($getOtherData['Result11'] as $FlightDepartureCityVal) {
                            if ($FlightDepartureCityVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                                $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['CityName'] = $FlightDepartureCityVal['CityName'];
                                $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['DestinationSysId'] = $FlightDepartureCityVal['DestinationSysId'];
                                foreach ($getOtherData['Result13'] as $asFixedDepartureVal) {
                                    $dapartureFDate = $asFixedDepartureVal['FromDate']->format("Y-m-d");
                                    if ($asFixedDepartureVal['TPSysId'] == $packageSearchResult[$i]['TPSysId'] && ($FlightDepartureCityVal['id'] == $asFixedDepartureVal['FixedInvnSysId'])) {
                                        if ($packageSearchResult[$i]['FromDate'] == $dapartureFDate) {
                                            $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FromDate'] = $dapartureFDate;
                                            if ($asFixedDepartureVal['MarkupType'] == 1) {
                                                $flightCost = $asFixedDepartureVal['B2CAdultMarkup'] + $asFixedDepartureVal['AdultCost'];
                                            } else {
                                                $flightCost = $asFixedDepartureVal['AdultCost'] + ($asFixedDepartureVal['B2CAdultMarkup'] * $asFixedDepartureVal['AdultCost']) / 100;
                                            }
                                            $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightCost'] = $flightCost;
                                            $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightCurrency'] = $asFixedDepartureVal['CurrencySysId'];
                                        }
                                    }
                                }
                                $kk = 0;
                                foreach ($getOtherData['Result12'] as $asFixedDepartureOtherVal) {
                                    if ($asFixedDepartureOtherVal['TPSysId'] == $packageSearchResult[$i]['TPSysId'] && $asFixedDepartureOtherVal['FixedInvnSysId'] == $FlightDepartureCityVal['id']) {
                                        $packageSearchResult[$i]['FlightDepartureCity'][$FlightDepartureCityVal['DestinationSysId']]['FlightOtherDetail'][$asFixedDepartureOtherVal['FlightType']][$kk] = $asFixedDepartureOtherVal;
                                        $kk++;
                                    }
                                }
                            }
                        }
                        foreach ($getOtherData['Result10'] as $otKey => $otVal) {
                            if ($otVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                                $packageSearchResult[$i]['DayTitles'][$otVal['Sequence']] = !empty($otVal['DayTitle']) ? $otVal['DayTitle'] : '';
                            }
                        }
                        foreach ($getOtherData['Result8'] as $cityDataKey => $cityDataVal) {
                            if ($cityDataVal['TPSysId'] == $packageSearchResult[$i]['TPSysId']) {
                                $cityIdCurrent = (int) $cityDataVal['CityId'] . '-' . (int) $cityDataVal['AccomSysId'] . '-' . (int) $cityDataVal['RoomType'] . '-' . (int) $cityDataVal['MealPlanType'];
                                if ($cityIdCurrent != $cityIdPre) {
                                    $jj++;
                                }
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['HotelCount'] = $cityDataVal['HotelCount'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['TPIntSysId'] = $cityDataVal['TPIntSysId'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['Sequence'] = $cityDataVal['Sequence'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['CityId'] = $cityDataVal['CityId'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['CityName'] = $cityDataVal['CityName'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['HotelName'] = $cityDataVal['HotelName'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['Stars'] = $cityDataVal['Stars'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['EconomyTypeTitle'] = $cityDataVal['EconomyTypeTitle'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['MealPlanTypeTitle'] = $cityDataVal['MealPlanTypeTitle'];
                                $packageSearchResult[$i]['CityData'][$jj][$cityDataVal['Sequence']]['AccomSysId'] = $cityDataVal['AccomSysId'];
                                $sequesceIdPre = $cityDataVal['Sequence'];
                                $cityIdPre = (int) $cityDataVal['CityId'] . '-' . (int) $cityDataVal['AccomSysId'] . '-' . (int) $cityDataVal['RoomType'] . '-' . (int) $cityDataVal['MealPlanType'];
                            }
                        }
                    }
                    $i++;
                }
                //echo "<pre>";print_r($packageSearchResult);exit;
                $intPageNumber = !empty($this->getRequest()->getPost('page')) ? $this->getRequest()->getPost('page') : '1';
                $intLimitPerPage = 500;
                $page = $this->_getParam('page', $intPageNumber);
                $packageSearchResultPagignation = Zend_Paginator::factory($packageSearchResult);
                $packageSearchResultPagignation->setItemCountPerPage($intLimitPerPage);
                $packageSearchResultPagignation->setCurrentPageNumber($page);
                $this->view->packageSearchResult = $packageSearchResultPagignation;
                $this->view->sessionFlag = $intPageNumber;
                $this->view->count = $page * $intLimitPerPage;
                $this->view->getDataFinal = $getDataFinal;
                $this->view->packageThemeList = isset($this->view->otherData['Result5']) ? $this->view->otherData['Result5'] : array();
                $this->view->packageInclusionList = isset($this->view->otherData['Result6']) ? $this->view->otherData['Result6'] : array();
                $this->view->foodPreferenceList = isset($this->view->otherData['Result7']) ? $this->view->otherData['Result7'] : array();
                $this->view->getleadSource = isset($this->view->otherData['Result3']) ? $this->view->otherData['Result3'] : array();
                $getAllCurrency = isset($this->view->otherData['Result4']) ? $this->view->otherData['Result4'] : array();
                $getAllCurrencyArr = array();
                foreach ($getAllCurrency as $cKey => $cVal) {
                    $getAllCurrencyArr[$cVal['CurrencyType']] = $cVal['Symbol'];
                }
                $this->view->getAllCurrency = $getAllCurrencyArr;
            }
        }
    }

    public function buildquickpackageAction() {
        $this->byo = new BuildYourOwn_Model_Byo();
        //        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        //        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $objPackage = new Travel_Model_TblPackage();
        $packageInclList = $objPackage->getPackageInclusionList();
        $this->view->packageInclList = $packageInclList;
        $objHotelMealType = new Travel_Model_Master_Mealtype();
        $this->view->arrHotelRoomMealTypes = $objHotelMealType->getRoomMealtypes();
        //$objHotel = new Travel_Model_TblHotel();
        //        $this->view->getMasterRoomType = $objHotel->getMasterRoomType();
        $this->view->getMasterRoomType = array();
        $this->view->qid = $qid = ($this->getRequest()->getParam('qid')) ? base64_decode($this->getRequest()->getParam('qid')) : 0;
        $this->view->PackageType = $type = $this->getRequest()->getParam('type');
        $tpsysID = ($this->getRequest()->getParam('id')) ? base64_decode($this->getRequest()->getParam('id')) : 0;
        $this->view->EnqSupplierSysId = $EnqSupplierSysId = !empty($this->getRequest()->getParam('sid')) ? $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('sid'))) : '';
        $PkgId = base64_decode($this->getRequest()->getParam('pkgId'));
        if ($qid) {
            $code = $this->getRequest()->getParam('code');
            $secureCode = Catabatic_ValidateCustomer::secureCode($this->getRequest()->getParam('qid'), 1);
            if ($code != $secureCode) {
                echo "Do not change qid or code";
                exit;
            }
            $travelplandata = $objPackage->GetTravelPlanQueryDetailsPkgString($qid); // get query data from customer travel plan
            $CustomerSysId = isset($travelplandata[0]['CustomerSysId']) ? $travelplandata[0]['CustomerSysId'] : 0;
            if ($CustomerSysId > 0) {
                $getLeadRemarkDetail = $this->_crmremarkObj->GetLeadRemarkById($qid);
                $CustomerRemark = isset($travelplandata[0]['CustomerRemark']) ? $travelplandata[0]['CustomerRemark'] : '';
                $travelplandata[0]['leadRemark'] = is_array($getLeadRemarkDetail) && count($getLeadRemarkDetail) > 0 ? $getLeadRemarkDetail['Remarks'] : $CustomerRemark;
            }

            $this->view->flexiQueryDataList = $travelplandata[0];
        }

        $CitySysIdsArr = $getAdvancedBalance = array();
        $objAgency = new Travel_Model_TblAgency();
        if ($tpsysID > 0) {
            $code = $this->getRequest()->getParam('code');
            $travelplandata = $this->_crmcusttravelplan->GetVersionAndOptionsByTpSysId($tpsysID); // get proposal data from customer travel plan
            $secureCode = Catabatic_ValidateCustomer::secureCode(trim(base64_encode($tpsysID)), 1);
            //            if ($code != $secureCode) {
            //                echo "Please check your request parameters";
            //                exit;
            //            }
            if ($travelplandata['EconomyMask'] == 6) {
                if ($type == 'mod') {
                    $travelplandata['MultiOptions'] = "";
                }
                if ($travelplandata['MultiOptions'] != "") {
                    $mMultiOptions = json_decode($travelplandata['MultiOptions'], 1);
                    $VersionsOfOptions = (array_values($mMultiOptions));
                    $versionIds = array_keys($VersionsOfOptions[0]);
                    $MasterTPsysIdArr = array_values($VersionsOfOptions[0]);
                    $MasterTPSysId = $MasterTPsysIdArr[0];
                    //                $versionIds = implode(', ', $varsionArray);
                    //                print_r($MasterTPsysIdArr);
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanDetailsByQueryIdAndVersion($MasterTPSysId, $versionIds);
                } else {
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);
                    $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
                }
            } else {
                $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);
                $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
            }
            $miscList = $this->_crmcusttravelplan->GetAllService($tpsysID);
            //            echo"<pre>";print_r($flexiPackageList);die('dd');
            $IsDayWiseItinerary = $flexiPackageList[0]['IsDayWiseItinerary'];
            $flexiPackageListOptions = $TPSysIdArr = array();
            foreach ($flexiPackageList as $flexiPackage) {
                $flexiPackageListOptions['TPdetails'][] = $flexiPackage;
                $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($flexiPackage['TPSysId']); // get itenary// get proposal data from customer travel plan
                $CitySysIdsArr = array_unique(array_column($travelplanIetnaryData, 'CitySysId'));
                //                echo "<pre>";print_r($flexiPackage);die;
                $TPIntSysIdsArr = array_column($travelplanIetnaryData, 'TPIntSysId');
                $TPIntSysIds = implode(', ', $TPIntSysIdsArr);
                $flexiPackageListOptions['travelplanIetnaryData'][] = $travelplanIetnaryData;
                if (!empty($TPIntSysIds)) {
                    $flexiPackageListOptions['ItenaryAccom'][] = $this->_crmcusttravelplan->GetTravelPlanCustomerItenaryAccom($TPIntSysIds); // get accom by itenary id
                }
                $flexiPackageListOptions['travelplanmarketPriceArr'][] = $this->_crmcusttravelplan->GetCustomerTravelMarketPrice($flexiPackage['TPSysId']);
                $CustPackageRoomwisePrice = array();
                if (trim($flexiPackage['SelectPricingType']) == 'RoomWise') {
                    $CustPackageRoomwisePrice = $this->_crmcusttravelplan->getCustPackageRoomwisePrice($flexiPackage['TPSysId']);
                }
                $flexiPackageListOptions['CustPackageRoomwisePrice'][] = $CustPackageRoomwisePrice;
                if ($flexiPackage['TPSysId'] == $tpsysID) {
                    $IsDayWiseItinerary = $flexiPackage['IsDayWiseItinerary'];
                }
                $TPSysIdArr[] = $flexiPackage['TPSysId'];
            }
            $objSightseeing = new Travel_Model_TblSightseeing();
            $paidCoverSight = implode(", ", $CitySysIdsArr);
            $StartDate = (isset($flexiPackageList[0]['StartDate']) && !empty($flexiPackageList[0]['StartDate'])) ? $flexiPackageList[0]['StartDate']->format('Y-m-d') : '';
            $resultPaidSightseeing = array();
            if ($IsDayWiseItinerary == 1) {
                $resultPaidSightseeing = $objSightseeing->getSightseeingListWithPrice('', $this->intLoggedinUserAgencySysId, '', $paidCoverSight, $StartDate, 1);
            }
            $resultPaidMicsItem = array();
            if ($travelplandata['PlanType'] == 24) {
                $resultPaidMicsItem = $objSightseeing->getMiscItemListWithPrice($this->intLoggedinUserAgencySysId);
            }
            $this->view->CitySysIdsArr = $CitySysIdsArr;
            $this->view->IsDayWiseItinerary = $IsDayWiseItinerary;
            $this->view->flexiPackageListOptions = $flexiPackageListOptions;
            if ($PkgId > 0) {
                $travelplandataQuery = $objPackage->GetTravelPlanQueryDetails($PkgId);
                $getLeadRemarkDetail = $this->_crmremarkObj->GetLeadRemarkById($PkgId);
            } else {
                $travelplandataQuery = $objPackage->GetTravelPlanQueryDetails($MasterTPSysId);
                $getLeadRemarkDetail = $this->_crmremarkObj->GetLeadRemarkById($MasterTPSysId);
            }

            if (!empty($getLeadRemarkDetail)) {
                $CustomerRemark = isset($travelplandataQuery[0]['CustomerRemark']) ? $travelplandataQuery[0]['CustomerRemark'] : '';
                $travelplandataQuery[0]['leadRemark'] = is_array($getLeadRemarkDetail) && count($getLeadRemarkDetail) > 0 ? $getLeadRemarkDetail['Remarks'] : $CustomerRemark;
            }
            $this->view->flexiQueryDataList = $travelplandataQuery[0];

            $this->view->miscList = $miscList;
            $this->view->flexiPackageQueryDestination = $travelplandataQuery[0]['DestinationPlaces'];
            $this->view->resultPaidSightseeing = $resultPaidSightseeing;
            $this->view->resultPaidMicsItem = $resultPaidMicsItem;
            $travelplanterms = $this->_crmcusttravelplan->GetCustomerTravelPlanTermsCond($tpsysID);  // get tnc by travel plan id;
            $this->view->gettransportdata = $gettransportdata = $this->_crmcusttravelplan->GetAllQuickTransportOption($tpsysID);
            $this->view->packageTncList = $travelplanterms[0];

            $this->view->flexiPackageItenList = $travelplanIetnaryData;
            if (!empty($TPIntSysIds)) {
                $tpitenarysightseeing = $this->_crmcusttravelplan->GetCustomerTravelPlanSightSeeing($TPIntSysIds); // get sightseeing by itenary ids
                $this->view->tpitenarysightseeing = $tpitenarysightseeing;
            }

            $objHotelRooms = new Travel_Model_TblHotelRooms();
            $this->view->arrHotelRoomTypes = $objHotelRooms->getRoomTypes($this->intLoggedinUserAgencySysId);
            $FlightData = array();
            $apiFlightData = array();
            if (!isset($PkgId) || empty($PkgId) || $type == 'mod') {
                $FlightData = $this->_crmcusttravelplan->GetPackageFLightData($tpsysID);
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $PostData = ['TPSysId' => $tpsysID, 'version' => null, 'IsApproved' => 0, 'IsPackage' => 1];
                $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
                $apiFlightData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            } else {
                $EmailText = isset($flexiPackageList[0]['EmailText']) ? json_decode($flexiPackageList[0]['EmailText'], 1) : array();
                $EmailText['FlightContent'] = '';
                $EmailText['flightPriceArray'] = array();
                $flexiPackageList[0]['EmailText'] = json_encode($EmailText);
                //                echo "<pre>";print_r($EmailText);die;
            }
            $encodedata = (isset($FlightData[0]['encodedata']) && !empty($FlightData[0]['encodedata'])) ? json_decode($FlightData[0]['encodedata'], 1) : [];
            $BookingDataAPIOld = (isset($encodedata['BookingDataAPI']) && !empty($encodedata['BookingDataAPI'])) ? $encodedata['BookingDataAPI'] : [];
            if ($apiFlightData['FlightBookingData']) {
                $objSupplier = new Travel_Model_TblSupplier();
                $objFlight = new Travel_Model_TblFlight();
                foreach ($apiFlightData['FlightBookingData'] as $keys => $value) {
                    $SupplierSysId = (isset($value['SupplierSysId']) && !empty($value['SupplierSysId'])) ? $value['SupplierSysId'] : 0;

                    $SupplierName = '';
                    if ($SupplierSysId > 0) {
                        $supplierDetails = $objSupplier->getSupplierList($SupplierSysId);
                        $SupplierName = isset($supplierDetails['SupplierName']) ? $supplierDetails['SupplierName'] : '';
                    }


                    $total_markup = 0;
                    $totalcost_wom = 0;
                    $total_gst = 0;
                    $totalflightcost = 0;
                    $PassengerTypeWise = [];
                    if ($value['FareBreakdown']) {
                        foreach ($value['FareBreakdown'] as $BrKkey => $BrkVal) {
                            $TDSEarn = ($BrkVal['TDSEarn']);
                            $CommissionEarned = ($BrkVal['CommissionEarned']);
                            $PassengerCount = ($BrkVal['PassengerCount']);
                            $PassengerType = ($BrkVal['PassengerType']);
                            $BaseFare = ($BrkVal['BaseFare'] + $BrkVal['Tax'] + $CommissionEarned + $TDSEarn);
                            $FixedMarkUp = ($BrkVal['FixedMarkUp']);
                            $GSTOnMarkUp = ($BrkVal['GSTOnMarkUp']);

                            $totalcost_wom += ($BaseFare);
                            $total_markup += ($FixedMarkUp);
                            $total_gst += ($GSTOnMarkUp);
                            $totalflightcost += ($BaseFare + $FixedMarkUp + $GSTOnMarkUp);

                            $PassengerTypeWise[$PassengerType]['total_pax'] += ($PassengerCount);
                            $PassengerTypeWise[$PassengerType]['cost_pp'] += ($BaseFare / $PassengerCount);
                            $PassengerTypeWise[$PassengerType]['markup'] += ($FixedMarkUp / $PassengerCount);
                            $PassengerTypeWise[$PassengerType]['gst'] += ($GSTOnMarkUp / $PassengerCount);
                            $PassengerTypeWise[$PassengerType]['total'] += ($BaseFare + $FixedMarkUp + $GSTOnMarkUp);
                        }
                    }
                    $AirlineCode = $value['AirLineCode'];
                    $condCity = "tbl.Code = '" . $AirlineCode . "'";
                    $arrResponse = $objFlight->getAirlineName($condCity);

                    $originAirportCode = $value['SourceAirportCode'];
                    $destinationAirportCode = $value['DestAirportCode'];
                    $condCity = "AirportCode = '" . $originAirportCode . "'";
                    $originAirportCodeData = $objFlight->getAirPortAutoSuggest($condCity);

                    $DescondCity = "AirportCode = '" . $destinationAirportCode . "'";
                    $destinationAirportCodeData = $objFlight->getAirPortAutoSuggest($DescondCity);
                    $strDuration = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->CalculateTotalTime($value['LocalFromTime'], $value['LocalToTime']);
                    $CustomEncodedata = [
                        "textbased" => "textbased",
                        "supplier_type" => $SupplierName,
                        "supplier_type_id" => $value['SupplierSysId'],
                        "flighttext" => "",
                        "adult_pax" => isset($PassengerTypeWise[1]['total_pax']) ? $PassengerTypeWise[1]['total_pax'] : 0,
                        "adult_cost_pp" => isset($PassengerTypeWise[1]['cost_pp']) ? $PassengerTypeWise[1]['cost_pp'] : 0,
                        "adult_markup" => isset($PassengerTypeWise[1]['markup']) ? $PassengerTypeWise[1]['markup'] : 0,
                        "adult_gst" => isset($PassengerTypeWise[1]['gst']) ? $PassengerTypeWise[1]['gst'] : 0,
                        "adult_total" => isset($PassengerTypeWise[1]['total']) ? $PassengerTypeWise[1]['total'] : 0,
                        "totalcost_wom" => $totalcost_wom,
                        "total_markup" => $total_markup,
                        "total_gst" => $total_gst,
                        "totalflightcost" => $totalflightcost,
                        "FlightNo" => $value['FlightNumber'],
                        "AirlineName" => $value['AirLineTitle'],
                        "hidden_selected_airline_sys_id" => isset($arrResponse[0]['AirlineSysId']) ? $arrResponse[0]['AirlineSysId'] : 0,
                        "departureCity" => isset($originAirportCodeData[0]['label']) ? $originAirportCodeData[0]['label'] : '',
                        "depaartureDate" => date('d/m/Y', strtotime($value['LocalFromTime'])),
                        "depaartureTime" => date('H:i', strtotime($value['LocalFromTime'])),
                        "arrivalCity" => isset($destinationAirportCodeData[0]['label']) ? $destinationAirportCodeData[0]['label'] : '',
                        "arrivalDate" => date('d/m/Y', strtotime($value['LocalToTime'])),
                        "arrivalTime" => date('H:i', strtotime($value['LocalToTime'])),
                        "stops" => (count($value['Segments']) > 0) ? (count($value['Segments']) - 1) : 0,
                        "stopOver" => isset($value['Segments'][0]['StopPoint']) ? $value['Segments'][0]['StopPoint'] : '',
                        "duration" => $strDuration,
                        "currencyTypes" => $value['CurrencyType'],
                        "FareClass" => isset($value['Segments'][0]['cabinClass']) ? $value['Segments'][0]['cabinClass'] : '',
                        "Baggage" => isset($value['Segments'][0]['Baggage']) ? $value['Segments'][0]['Baggage'] : '',
                        "CabinBaggage" => isset($value['Segments'][0]['CabinBaggage']) ? $value['Segments'][0]['CabinBaggage'] : '',
                        "refundableFlight" => $value['IsRefundable'],
                        "totalFightCost" => $totalcost_wom,
                        "totalFightMarkup" => $total_markup,
                        "totalTax" => $total_gst,
                        "totalFightCostWithMarkup" => $totalflightcost,
                        "fareRules" => "",
                        "child_pax" => isset($PassengerTypeWise[2]['total_pax']) ? $PassengerTypeWise[2]['total_pax'] : 0,
                        "child_cost_pp" => isset($PassengerTypeWise[2]['cost_pp']) ? $PassengerTypeWise[2]['cost_pp'] : 0,
                        "child_markup" => isset($PassengerTypeWise[2]['markup']) ? $PassengerTypeWise[2]['markup'] : 0,
                        "child_gst" => isset($PassengerTypeWise[2]['gst']) ? $PassengerTypeWise[2]['gst'] : 0,
                        "child_total" => isset($PassengerTypeWise[2]['total']) ? $PassengerTypeWise[2]['total'] : 0,
                        "infant_pax" => isset($PassengerTypeWise[3]['total_pax']) ? $PassengerTypeWise[3]['total_pax'] : 0,
                        "infant_cost_pp" => isset($PassengerTypeWise[3]['cost_pp']) ? $PassengerTypeWise[3]['cost_pp'] : 0,
                        "infant_markup" => isset($PassengerTypeWise[3]['markup']) ? $PassengerTypeWise[3]['markup'] : 0,
                        "infant_gst" => isset($PassengerTypeWise[3]['gst']) ? $PassengerTypeWise[3]['gst'] : 0,
                        "infant_total" => isset($PassengerTypeWise[3]['total']) ? $PassengerTypeWise[3]['total'] : 0,
                        "GstTaxFlight" => '0',
                    ];
                    // echo "<pre>";
                    // print_r($CustomEncodedata);
                    ///$FlightData[$keys]['encodedata'] = json_encode($CustomEncodedata);
                }
            }
            // echo "<pre>";
            // print_r($apiFlightData);
            // echo "<pre>";
            // print_r($FlightData);
            // die;
            $this->view->BookingDataAPIOld = json_encode($BookingDataAPIOld);
            $this->view->FlightData = $FlightData;
            $this->view->apiFlightData = $apiFlightData;
            $this->view->flexiPackageList = $flexiPackageList;
            $ConfirmQuery = array(17, 13, 7);
            if (in_array($flexiPackageList[0]['StatusType'], $ConfirmQuery) && $PkgId == $flexiPackageList[0]['MasterTPSysId']) {
                $getAdvancedBalance = $this->_crmcusttravelplan->getAdvancedBalance($tpsysID);
            } else if ($flexiPackageList[0]['StatusType'] == 16 && (int) $flexiPackageList[0]['RefTPSysId'] > 0) {
                $getAdvancedBalance = $this->_crmcusttravelplan->getAdvancedBalance((int) $flexiPackageList[0]['RefTPSysId']);
            }
            //            echo "<pre>";print_r($flexiPackageList[0]['RefTPSysId']);die;
            if (!empty($gettransportdata)) {
                //                echo "<pre>";print_r($gettransportdata);
                foreach ($gettransportdata as $dayInventtraData) {
                    $categoryTransport = $dayInventtraData['TransportCategory'];
                    $day = $dayInventtraData['Sequence'];
                    $startCityId = $dayInventtraData['SourceCityId'];
                    $endCityId = $dayInventtraData['DestCityId'];
                    $transferType = 0;
                    if ($categoryTransport == 1) {
                        if ($day == 1) {
                            $StartCityId = $flexiPackageList[0]['SourcePlaceSysId'];
                            $StartDestinationId = ($CitySysIdsArr[0]) ? $CitySysIdsArr[0] : 0;
                            $cityIds = implode(',', $CitySysIdsArr);
                            $autosugestTransportData1 = $this->byo->getAutosuggestTransportRouteDataWithVehicle($this->intLoggedinUserAgencySysId, $StartCityId, $cityIds . ',' . $StartCityId, '', '', 1, '');
                            $autosugestTransportData2 = $this->byo->getAutosuggestTransportRouteDataWithVehicle($this->intLoggedinUserAgencySysId, $StartDestinationId, $cityIds, '', '', 1, '');
                            $autosugestTransportData[$day][$categoryTransport] = array_merge($autosugestTransportData1, $autosugestTransportData2);
                        }
                    } else {
                        if ($categoryTransport == 3) {
                            $subCategoryTransport1 = '';
                            $categoryTransport1 = 3;
                        } else {
                            $subCategoryTransport1 = $categoryTransport;
                            $categoryTransport1 = 2;
                        }

                        if ($day == 1) {
                            $StartCityId = (isset($flexiPackageList[0]['SourcePlaceSysId']) && $flexiPackageList[0]['SourcePlaceSysId'] > 0) ? (int) $flexiPackageList[0]['SourcePlaceSysId'] : $startCityId;
                        } else {
                            $StartCityId = (isset($travelplanIetnaryData[$day - 1]['CitySysId']) && $travelplanIetnaryData[$day - 1]['CitySysId'] > 0) ? (int) $travelplanIetnaryData[$day - 1]['CitySysId'] : $startCityId;
                        }
                        $EndCityId = $endCityId;

                        $autosugestTransportData1 = $this->byo->getAutosuggestTransportRouteDataWithVehiclePreToNext($this->intLoggedinUserAgencySysId, $StartCityId, $EndCityId, 0, '', $transferType, $categoryTransport1, $subCategoryTransport1);
                        //                        $autosugestTransportData2 = $this->byo->getAutosuggestTransportRouteDataWithVehicle($this->intLoggedinUserAgencySysId, $EndCityId, $EndCityId, '', $transferType, $categoryTransport1, $subCategoryTransport1);
                        $autosugestTransportData[$day][$categoryTransport] = $autosugestTransportData1;
                    }
                }
                $autosugestTransportDataNewEdit = $autosugestTransportDataVehicleEdit = $autosugestTransportDataCityIncludes = $autosugestTransportDataAreaEdit = $autosugestTransportDataPickupAreaEdit = $autosugestTransportDataTransportRouteEdit = array();
                $CheckRouteDestSysIdArray = array();
                foreach ($autosugestTransportData as $tKey => $tranVal) {
                    foreach ($tranVal as $tvky => $tVal) {
                        foreach ($tVal as $tvky1 => $tVal1) {
                            $autosugestTransportDataAreaEdit[$tKey][$tvky][$tVal1['dropAreaId']] = $tVal1['DropLocation'];
                            $autosugestTransportDataPickupAreaEdit[$tKey][$tvky][$tVal1['pickupAreaId']] = $tVal1['PickupLocation'];
                            $autosugestTransportDataTransportRouteEdit[$tKey][$tvky][$tVal1['RouteSysId']] = $tVal1;
                            $autosugestTransportDataVehicleEdit[$tKey][$tVal1['RouteSysId']][$tVal1['RouteVechSysId']] = $tVal1['VehName'];
                            $nights = ($tVal1['destSequence'] == 1 && $tVal1['nights'] < $tVal1['Noofnights'] && $tVal1['StartCitySysId'] != $tVal1['DestSysId']) ? $tVal1['nights'] - 1 : $tVal1['nights'];

                            if (!in_array($tVal1['RouteSysId'] . '_' . $tVal1['RouteDestSysId'], $CheckRouteDestSysIdArray)) {
                                for ($im1 = 0; $im1 < $nights; $im1++) {
                                    $autosugestTransportDataCityIncludes[$tVal1['RouteSysId']][] = $tVal1['DestSysId'];
                                }
                            }
                            $CheckRouteDestSysIdArray[] = $tVal1['RouteSysId'] . '_' . $tVal1['RouteDestSysId'];
                        }
                    }
                }
            }
            //echo "<pre>";print_r($autosugestTransportDataCityIncludes);die;
        } else {

            $packageTncList = $objAgency->getAgencyTnCDetails($this->intLoggedinUserAgencySysId);
            $getAddressAgency = $objAgency->getAddressByAgency($this->intLoggedinUserAgencySysId, '', 1);

            if (!empty($travelplandata[0]['Countries']) && $getAddressAgency['CountrySysId'] != $travelplandata[0]['Countries']) {
                $packageTncList['Inclusions'] = $packageTncList['InclusionsInternational'];
                $packageTncList['Exclusions'] = $packageTncList['ExclusionInternational'];
                $packageTncList['TermsAndConditions'] = $packageTncList['TermsAndConditionsInternational'];
                $packageTncList['CancellationPolicy'] = $packageTncList['CancellationPolicyInternational'];
            }
            $this->view->packageTncList = $packageTncList;
        }

        $autosugestTransportDataNewEdit = array(
            'autosugestTransportDataAreaEdit' => $autosugestTransportDataAreaEdit,
            'autosugestTransportDataPickupAreaEdit' => $autosugestTransportDataPickupAreaEdit,
            'autosugestTransportDataTransportRouteEdit' => $autosugestTransportDataTransportRouteEdit,
            'autosugestTransportDataVehicleEdit' => $autosugestTransportDataVehicleEdit,
            'autosugestTransportDataCityIncludes' => $autosugestTransportDataCityIncludes,
        );

        $this->view->autosugestTransportDataNewEdit = $autosugestTransportDataNewEdit;
        $this->view->getAdvancedBalance = $getAdvancedBalance;
        $this->view->flexiPackageListForEdit = '';
        $this->view->pkgId = '';
        if (isset($PkgId) && (int) $PkgId > 0) {
            $flexiPackageList1 = $this->_crmcusttravelplan->GetTravelPlanByCustomer($PkgId, 'Query');
            $this->view->flexiPackageListForEdit = $flexiPackageList1;
            $this->view->pkgId = $PkgId;
        }
        $cityobj = new Travel_Model_TblCity();
        if (isset($flexiPackageList[0]['DestinationCovered']) && !empty($flexiPackageList[0]['DestinationCovered']) && $flexiPackageList[0]['EconomyMask'] == 6) { // 6 = quick package 7 = email only
            $cityIds = trim($flexiPackageList[0]['DestinationCovered']);
            if ($cityIds != '') {
                $destinationCovered = $cityobj->getCityDetailsByMultipleId($cityIds);
            }
            $this->view->DestinationCovered = $destinationCovered;
        }

        $this->view->otherlocationcity = array();
        if (isset($flexiPackageList[0]['MasterTPSysId']) && $flexiPackageList[0]['MasterTPSysId'] > 0) {
            if (isset($flexiPackageList[0]['DestinationPlacesSysId']) && !empty($flexiPackageList[0]['DestinationPlacesSysId'])) {
                $cityIds = trim($flexiPackageList[0]['DestinationPlacesSysId']);
                if ($cityIds != '') {
                    $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                }
                $this->view->otherlocationcity = $otherlocationcity;
            }
        }
        $PlanType = (!empty($travelplandata[0]['PlanType'])) ? $travelplandata[0]['PlanType'] : 5;

        $this->view->PlanType = $travelplandata[0]['PlanType'];
        $currencyarr = $objPackage->getCurrencyList();
        $this->view->currencyarr = $currencyarr;
        $this->view->TCurrencyType = $this->agencyDetails['TrxCurrency'];
        $markupMdl = new Markup_Model_Markup();
        $this->view->getTaxSettingDetailAll = $getTaxSettingDetailAll = $markupMdl->getTaxSettingDetailForCustom("TB_Master_Agency_Tax_Settings", $this->intLoggedinUserAgencySysId, 0, 1, 0, 1, array(1, 5, 6));

        //$this->view->flightTaxDetail = $markupMdl->getTaxSettingDetailForCustom("TB_Master_Agency_Tax_Settings", $this->intLoggedinUserAgencySysId, 0, 1, 1);
        $getTaxSettingDetail = array_filter($getTaxSettingDetailAll, function ($var) {
            return ($var['PlanType'] == '5');
        });
        $flightTaxDetail = array_filter($getTaxSettingDetailAll, function ($var) {
            return ($var['PlanType'] == '1');
        });
        $visaTaxDetail = array_filter($getTaxSettingDetailAll, function ($var) {
            return ($var['PlanType'] == '6');
        });
        if (empty($flightTaxDetail)) {
            $flightTaxDetail = $getTaxSettingDetail;
        }
        if (empty($visaTaxDetail)) {
            $visaTaxDetail = $getTaxSettingDetail;
        }
        $this->view->getTaxSettingDetail = $getTaxSettingDetail;
        $this->view->flightTaxDetail = $flightTaxDetail;
        $this->view->visaTaxDetail = $visaTaxDetail;
        $getTravelPlanAddonServices = array();
        //        if (!empty($TPSysIdArr)) {
        //            $getTravelPlanAddonServices = $objPackage->getTravelPlanAddonServices($this->intLoggedinUserAgencySysId, 0, 6, $TPSysIdArr);
        //        }
        //
        //        $this->view->getTravelPlanAddonServices = $getTravelPlanAddonServices;
        $this->view->getTcsSettingDetail = $getTcsSettingDetail = $objAgency->getTcsSettingDetail($this->intLoggedinUserAgencySysId);
        // $flightTaxDetail = (!empty($this->view->flightTaxDetail))  ? $this->view->flightTaxDetail : $this->view->getTaxSettingDetail;
        $getAllAddonServices = array();
        if (!empty($TPSysIdArr)) {
            $getAllAddonServices = $objPackage->getTravelPlanAddonServicesMultipleIds($this->intLoggedinUserAgencySysId, 0, array(1, 2, 5, 6, 21, 11, 9, 22,10), $TPSysIdArr);
        }


        $getAllAddonServicesArray = array();
        foreach ($getAllAddonServices as $key => $value) {
            $getAllAddonServicesArray[$value['PlanType']][] = $value;
        }
        $this->view->flightAddonArray = (isset($getAllAddonServicesArray[1])) ? $getAllAddonServicesArray[1] : array();
        $this->view->packageAddonArray = (isset($getAllAddonServicesArray[5])) ? $getAllAddonServicesArray[5] : array();
        $this->view->TCSAddonArray = (isset($getAllAddonServicesArray[21])) ? $getAllAddonServicesArray[21] : array();
        $this->view->getTravelPlanAddonServices = (isset($getAllAddonServicesArray[6])) ? $getAllAddonServicesArray[6] : array();
        $this->view->hotelAddonArray = (isset($getAllAddonServicesArray[2])) ? $getAllAddonServicesArray[2] : array();
        $this->view->transferAddonArray = (isset($getAllAddonServicesArray[11])) ? $getAllAddonServicesArray[11] : array();
        $this->view->sightseeingAddonArray = (isset($getAllAddonServicesArray[9])) ? $getAllAddonServicesArray[9] : array();
        $this->view->mealAddonArray = (isset($getAllAddonServicesArray[10])) ? $getAllAddonServicesArray[10] : array();
        $this->view->cancellationAddonArray = (isset($getAllAddonServicesArray[22])) ? $getAllAddonServicesArray[22] : array();

        $modelBY0 = new BuildYourOwn_Model_Byo();
        $TblCurrency = new Travel_Model_TblCurrency();
        $getAllCurrency = $modelBY0->getOnlyIndiaCurrency();
        $selectedCurrency = (isset($flexiPackageList[0]['CurrencyType']) && $flexiPackageList[0]['CurrencyType'] != 0) ? (int) $flexiPackageList[0]['CurrencyType'] : (int) $getAllCurrency[0]['CurrencyType'];
        $getToCurrencyConvertionRate = $TblCurrency->getToCurrencyConvertionRate($selectedCurrency);
        $this->view->selectedCurrency = $selectedCurrency;
        $this->view->getAllCurrency = $getAllCurrency;
        $this->view->getToCurrencyConvertionRate = $getToCurrencyConvertionRate;
        $CurrencyConvertionRateFromTo = array();
        $ExchangeRateMaarkup = $this->agencyDetails['ExchangeRateMaarkup'];
        foreach ($getToCurrencyConvertionRate as $cKey => $cValue) {
            $RateWithMarkup = (float) $cValue['Rate'] + (float) $cValue['Rate'] * $ExchangeRateMaarkup / 100;
            $CurrencyConvertionRateFromTo[(int) $cValue['FCurrencyType'] . '-' . (int) $cValue['TCurrencyType']] = $RateWithMarkup;
        }
        $this->view->CurrencyConvertionRateFromTo = $CurrencyConvertionRateFromTo;
        $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $this->view->intLoggedinUserId = $this->intLoggedinUserId;
        $this->view->isDisplayTax = $_SESSION['sessionLogin_user']['agencyDetails']['TaxLabelId'];
    }

    public function buildquickpackagenewAction() {
        //        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        //        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $objPackage = new Travel_Model_TblPackage();
        $packageInclList = $objPackage->getPackageInclusionList();
        $this->view->packageInclList = $packageInclList;
        $objHotelMealType = new Travel_Model_Master_Mealtype();
        $this->view->arrHotelRoomMealTypes = $objHotelMealType->getRoomMealtypes();
        $objHotel = new Travel_Model_TblHotel();
        $this->view->getMasterRoomType = $objHotel->getMasterRoomType();
        $this->view->qid = $qid = $this->getRequest()->getParam('qid');
        $this->view->PackageType = $this->getRequest()->getParam('type');
        $this->view->EnqSupplierSysId = $EnqSupplierSysId = !empty($this->getRequest()->getParam('sid')) ? $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('sid'))) : '';
        if ($qid) {
            $code = $this->getRequest()->getParam('code');
            $secureCode = Catabatic_ValidateCustomer::secureCode($qid, 1);
            if ($code != $secureCode) {
                echo "Do not change qid or code";
                exit;
            }
            $travelplandata = $objPackage->GetTravelPlanQueryDetails($qid); // get query data from customer travel plan
            $this->view->flexiQueryDataList = $travelplandata[0];
        }
        // echo "<pre>"; print_r($travelplandata[0]['PlanType']); die;
        if ($this->getRequest()->getParam('id') > 0) {
            $tpsysID = $this->getRequest()->getParam('id');
            $travelplandata = $this->_crmcusttravelplan->GetVersionAndOptionsByTpSysId($tpsysID); // get proposal data from customer travel plan
            //            print_r($travelplandata); die;
            if ($travelplandata['EconomyMask'] == 6) {
                if ($travelplandata['MultiOptions'] != "") {
                    $mMultiOptions = json_decode($travelplandata['MultiOptions'], 1);
                    $VersionsOfOptions = (array_values($mMultiOptions));
                    $versionIds = array_keys($VersionsOfOptions[0]);
                    $MasterTPsysIdArr = array_values($VersionsOfOptions[0]);
                    $MasterTPSysId = $MasterTPsysIdArr[0];
                    //                $versionIds = implode(', ', $varsionArray);
                    //                print_r($MasterTPsysIdArr);
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanDetailsByQueryIdAndVersion($MasterTPSysId, $versionIds);
                } else {
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);
                    $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
                }
            } else {
                $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);

                $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
            }
            $flexiPackageListOptions = array();
            foreach ($flexiPackageList as $flexiPackage) {
                $flexiPackageListOptions['TPdetails'][] = $flexiPackage;
                $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($flexiPackage['TPSysId']); // get itenary// get proposal data from customer travel plan
                $TPIntSysIdsArr = array_column($travelplanIetnaryData, 'TPIntSysId');
                $TPIntSysIds = implode(', ', $TPIntSysIdsArr);
                $flexiPackageListOptions['travelplanIetnaryData'][] = $travelplanIetnaryData;
                if (!empty($TPIntSysIds)) {
                    $flexiPackageListOptions['ItenaryAccom'][] = $this->_crmcusttravelplan->GetTravelPlanCustomerItenaryAccom($TPIntSysIds); // get accom by itenary id
                }
                $flexiPackageListOptions['travelplanmarketPriceArr'][] = $this->_crmcusttravelplan->GetCustomerTravelMarketPrice($flexiPackage['TPSysId']);
            }
            //            echo '<pre>';  print_r($flexiPackageListOptions); die;
            $this->view->flexiPackageListOptions = $flexiPackageListOptions;
            $travelplandataQuery = $objPackage->GetTravelPlanQueryDetails($MasterTPSysId);
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->flexiPackageQueryDestination = $travelplandataQuery[0]['DestinationPlaces'];

            $travelplanterms = $this->_crmcusttravelplan->GetCustomerTravelPlanTermsCond($tpsysID);  // get tnc by travel plan id;
            $this->view->gettransportdata = $gettransportdata = $this->_crmcusttravelplan->GetAllQuickTransportOption($tpsysID);
            $this->view->packageTncList = $travelplanterms[0];
            $this->view->flexiPackageItenList = $travelplanIetnaryData;

            if (!empty($TPIntSysIds)) {
                $tpitenrayEvents = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryEvents($TPIntSysIds); // get activities by itenary ids
                $tpitenarysightseeing = $this->_crmcusttravelplan->GetCustomerTravelPlanSightSeeing($TPIntSysIds); // get sightseeing by itenary ids
                //                $this->view->tplanitenaryaccomdata = $tplanitenaryaccomdata;
                $this->view->tpitenrayEvents = $tpitenrayEvents;
                $this->view->tpitenarysightseeing = $tpitenarysightseeing;
            }
            $objHotelRooms = new Travel_Model_TblHotelRooms();
            $this->view->arrHotelRoomTypes = $objHotelRooms->getRoomTypes($this->intLoggedinUserAgencySysId);
        } else {
            $objAgency = new Travel_Model_TblAgency();
            $packageTncList = $objAgency->getAgencyTnCDetails($this->intLoggedinUserAgencySysId);
            //          echo '<pre>'; print_r($packageTncList);  echo '</pre>';
            $this->view->packageTncList = $packageTncList;
        }

        $PkgId = $this->getRequest()->getParam('pkgId');
        $this->view->flexiPackageListForEdit = '';
        $this->view->pkgId = '';
        if (isset($PkgId) && (int) $PkgId > 0) {
            $flexiPackageList1 = $this->_crmcusttravelplan->GetTravelPlanByCustomer($PkgId);
            $this->view->flexiPackageListForEdit = $flexiPackageList1;
            $this->view->pkgId = $PkgId;
        }


        //         echo '<pre>'; print_r($travelplandata);  echo '</pre>';
        if (isset($flexiPackageList[0]['DestinationCovered']) && !empty($flexiPackageList[0]['DestinationCovered']) && $flexiPackageList[0]['EconomyMask'] == 6) { // 6 = quick package 7 = email only
            $cityobj = new Travel_Model_TblCity();
            $cityIds = trim($flexiPackageList[0]['DestinationCovered']);
            $destinationCovered = $cityobj->getCityDetailsByMultipleId($cityIds);
            //            echo "<pre>";print_r($destinationCovered);die;
            $this->view->DestinationCovered = $destinationCovered;
        }

        $this->view->otherlocationcity = array();
        if (isset($flexiPackageList[0]['MasterTPSysId']) && $flexiPackageList[0]['MasterTPSysId'] != 0) {
            if (isset($flexiPackageList[0]['DestinationPlacesSysId']) && !empty($flexiPackageList[0]['DestinationPlacesSysId']) && empty($tplanitenaryaccomdata)) {
                $cityobj = new Travel_Model_TblCity();
                $cityIds = trim($flexiPackageList[0]['DestinationPlacesSysId']);
                $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                $this->view->otherlocationcity = $otherlocationcity;
            }
        }
        $PlanType = (!empty($travelplandata[0]['PlanType'])) ? $travelplandata[0]['PlanType'] : 5;

        $this->view->PlanType = $travelplandata[0]['PlanType'];
        $currencyarr = $objPackage->getCurrencyList();
        $this->view->currencyarr = $currencyarr;
        $markupMdl = new Markup_Model_Markup();
        $this->view->getTaxSettingDetail = $markupMdl->getTaxSettingDetailForCustom("TB_Master_Agency_Tax_Settings", $this->intLoggedinUserAgencySysId, 0, 1, $PlanType);

        $this->view->flightTaxDetail = $markupMdl->getTaxSettingDetailForCustom("TB_Master_Agency_Tax_Settings", $this->intLoggedinUserAgencySysId, 0, 1, 1);
        // echo "<pre>"; print_r($this->view->flightTaxDetail); die("ljkhb");
        // $flightTaxDetail = (!empty($this->view->flightTaxDetail))  ? $this->view->flightTaxDetail : $this->view->getTaxSettingDetail;
        // echo "<pre>"; print_r($flightTaxDetail); die;
    }

    public function buildquicksightseeingpackageAction() {
        //        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        //        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $objPackage = new Travel_Model_TblPackage();
        $packageInclList = $objPackage->getPackageInclusionList();
        $this->view->packageInclList = $packageInclList;
        $objHotelMealType = new Travel_Model_Master_Mealtype();
        $this->view->arrHotelRoomMealTypes = $objHotelMealType->getRoomMealtypes();
        $objHotel = new Travel_Model_TblHotel();
        $this->view->getMasterRoomType = $objHotel->getMasterRoomType();
        $this->view->qid = $qid = ($this->getRequest()->getParam('qid')) ? base64_decode($this->getRequest()->getParam('qid')) : 0;
        $this->view->PackageType = $this->getRequest()->getParam('type');
        // echo $this->view->PackageType; die();
        $this->view->EnqSupplierSysId = $EnqSupplierSysId = !empty($this->getRequest()->getParam('sid')) ? $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getParam('sid'))) : '';
        $tpsysID = ($this->getRequest()->getParam('id')) ? base64_decode($this->getRequest()->getParam('id')) : 0;
        if ($qid) {
            $code = $this->getRequest()->getParam('code');
            $secureCode = Catabatic_ValidateCustomer::secureCode($this->getRequest()->getParam('qid'), 1);
            if ($code != $secureCode) {
                echo "Do not change qid or code";
                exit;
            }
            $travelplandata = $objPackage->GetTravelPlanQueryDetails($qid); // get query data from customer travel plan
            $this->view->flexiQueryDataList = $travelplandata[0];
        }
        if ($tpsysID > 0) {
            $travelplandata = $this->_crmcusttravelplan->GetVersionAndOptionsByTpSysId($tpsysID); // get proposal data from customer travel plan
            //            print_r($travelplandata); die;
            if ($travelplandata['EconomyMask'] == 6) {
                if ($travelplandata['MultiOptions'] != "") {
                    $mMultiOptions = json_decode($travelplandata['MultiOptions'], 1);
                    $VersionsOfOptions = (array_values($mMultiOptions));
                    $versionIds = array_keys($VersionsOfOptions[0]);
                    $MasterTPsysIdArr = array_values($VersionsOfOptions[0]);
                    $MasterTPSysId = $MasterTPsysIdArr[0];
                    //                $versionIds = implode(', ', $varsionArray);
                    //                print_r($MasterTPsysIdArr);
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanDetailsByQueryIdAndVersion($MasterTPSysId, $versionIds);
                } else {
                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);
                    $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
                }
            } else {
                $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID);

                $MasterTPSysId = $flexiPackageList[0]['MasterTPSysId'];
            }
            $flexiPackageListOptions = array();
            foreach ($flexiPackageList as $flexiPackage) {
                $flexiPackageListOptions['TPdetails'][] = $flexiPackage;
                $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($flexiPackage['TPSysId']); // get itenary// get proposal data from customer travel plan
                $TPIntSysIdsArr = array_column($travelplanIetnaryData, 'TPIntSysId');
                $TPIntSysIds = implode(', ', $TPIntSysIdsArr);
                $flexiPackageListOptions['travelplanIetnaryData'][] = $travelplanIetnaryData;
                if (!empty($TPIntSysIds)) {
                    $flexiPackageListOptions['ItenaryAccom'][] = $this->_crmcusttravelplan->GetTravelPlanCustomerItenaryAccom($TPIntSysIds); // get accom by itenary id
                }
                $flexiPackageListOptions['travelplanmarketPriceArr'][] = $this->_crmcusttravelplan->GetCustomerTravelMarketPrice($flexiPackage['TPSysId']);
            }
            //            echo '<pre>';  print_r($flexiPackageListOptions); die;
            $this->view->flexiPackageListOptions = $flexiPackageListOptions;
            $travelplandataQuery = $objPackage->GetTravelPlanQueryDetails($MasterTPSysId);
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->flexiPackageQueryDestination = $travelplandataQuery[0]['DestinationPlaces'];

            $travelplanterms = $this->_crmcusttravelplan->GetCustomerTravelPlanTermsCond($tpsysID);  // get tnc by travel plan id;
            $this->view->gettransportdata = $gettransportdata = $this->_crmcusttravelplan->GetAllQuickTransportOption($tpsysID);
            $this->view->packageTncList = $travelplanterms[0];
            $this->view->flexiPackageItenList = $travelplanIetnaryData;

            if (!empty($TPIntSysIds)) {
                $tpitenrayEvents = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryEvents($TPIntSysIds); // get activities by itenary ids
                $tpitenarysightseeing = $this->_crmcusttravelplan->GetCustomerTravelPlanSightSeeing($TPIntSysIds); // get sightseeing by itenary ids
                //                $this->view->tplanitenaryaccomdata = $tplanitenaryaccomdata;
                $this->view->tpitenrayEvents = $tpitenrayEvents;
                $this->view->tpitenarysightseeing = $tpitenarysightseeing;
            }
            $objHotelRooms = new Travel_Model_TblHotelRooms();
            $this->view->arrHotelRoomTypes = $objHotelRooms->getRoomTypes($this->intLoggedinUserAgencySysId);
        } else {
            $objAgency = new Travel_Model_TblAgency();
            $packageTncList = $objAgency->getAgencyTnCDetails($this->intLoggedinUserAgencySysId);
            //          echo '<pre>'; print_r($packageTncList);  echo '</pre>';
            $this->view->packageTncList = $packageTncList;
        }

        $PkgId = $this->getRequest()->getParam('pkgId');
        $this->view->flexiPackageListForEdit = '';
        $this->view->pkgId = '';
        if (isset($PkgId) && (int) $PkgId > 0) {
            $flexiPackageList1 = $this->_crmcusttravelplan->GetTravelPlanByCustomer($PkgId, 'Query');
            $this->view->flexiPackageListForEdit = $flexiPackageList1;
            $this->view->pkgId = $PkgId;
        }


        //         echo '<pre>'; print_r($travelplandata);  echo '</pre>';
        if (isset($flexiPackageList[0]['DestinationCovered']) && !empty($flexiPackageList[0]['DestinationCovered']) && $flexiPackageList[0]['EconomyMask'] == 6) { // 6 = quick package 7 = email only
            $cityobj = new Travel_Model_TblCity();
            $cityIds = trim($flexiPackageList[0]['DestinationCovered']);
            $destinationCovered = $cityobj->getCityDetailsByMultipleId($cityIds);
            //            echo "<pre>";print_r($destinationCovered);die;
            $this->view->DestinationCovered = $destinationCovered;
        }
        $this->view->otherlocationcity = array();
        if (isset($flexiPackageList[0]['MasterTPSysId']) && $flexiPackageList[0]['MasterTPSysId'] != 0) {
            if (isset($flexiPackageList[0]['DestinationPlacesSysId']) && !empty($flexiPackageList[0]['DestinationPlacesSysId']) && empty($tplanitenaryaccomdata)) {
                $cityobj = new Travel_Model_TblCity();
                $cityIds = trim($flexiPackageList[0]['DestinationPlacesSysId']);
                $otherlocationcity = $cityobj->getCityDetailsByMultipleId($cityIds);
                $this->view->otherlocationcity = $otherlocationcity;
            }
        }
        $currencyarr = $objPackage->getCurrencyList();
        $this->view->currencyarr = $currencyarr;
        $this->view->onlysightseeingPkg = 1;
        $markupMdl = new Markup_Model_Markup();
        $this->view->getTaxSettingDetail = $markupMdl->getTaxSettingDetailForCustom("TB_Master_Agency_Tax_Settings", $this->intLoggedinUserAgencySysId, 0, 1, 5);
    }

    public function buildquickpackageDataAction() {
        $this->_helper->layout->disableLayout();
        $objSightseeing = new Travel_Model_TblSightseeing();
        $objTransportsRoutes = new Travel_Model_TblTransportsRoutes();
        $TblCurrency = new Travel_Model_TblCurrency();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $AgencySysId = $this->intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $ProposalExpiryDays = $sessionLogin_user->agencyDetails['ProposalExpiryDays'];
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            $BookingDataAPI = (isset($postData['BookingDataAPI']) && !empty($postData['BookingDataAPI'])) ? json_decode($postData['BookingDataAPI'], 1) : [];
            // echo "<pre>";
            // print_r($postData);
            // die;
            $pdfFileName = '';

            if (isset($postData['FlightContent']) && !empty($postData['FlightContent'])) {
                $postData['FlightContent'] = $this->createImageFromCkeditor($postData['FlightContent'], 'quick');
            }
            $FlightContentCheck = strip_tags($postData['FlightContent'], '<img>');
            $FlightContentCheck = htmlentities($FlightContentCheck, null, 'utf-8');
            $FlightContentCheck = str_replace(['&', 'amp;', 'nbsp;'], ' ', trim($FlightContentCheck));
            if (trim($FlightContentCheck) == '') {
                $postData['FlightContent'] = '';
            }

            $checkDuplicateSightseeingSeq = array();
            $SupplierSysId = !empty($postData['supplier_type_id']) ? $this->_HtmlPurifier->filter($postData['supplier_type_id']) : '0';
            $displayTCS = isset($postData['displayTCS']) ? $postData['displayTCS'] : 0;
            $IsPackageTCS = isset($postData['IsPackageTCS']) ? (int) $postData['IsPackageTCS'] : 0;
            $IsVisaTCS = isset($postData['IsVisaTCS']) ? (int) $postData['IsVisaTCS'] : 0;
            $IsFlightTCS = isset($postData['IsFlightTCS']) ? (int) $postData['IsFlightTCS'] : 0;
            $TcsTaxSysId = isset($postData['TcsTaxSysId']) ? (int) $postData['TcsTaxSysId'] : 0;

            $displayFlightBreakup = isset($postData['displayFlightBreakup']) ? $postData['displayFlightBreakup'] : 0;
            $displayHotelBreakup = isset($postData['displayHotelBreakup']) ? $postData['displayHotelBreakup'] : 0;
            $displayTransferBreakup = isset($postData['displayTransferBreakup']) ? $postData['displayTransferBreakup'] : 0;
            $displaySightseeingBreakup = isset($postData['displaySightseeingBreakup']) ? $postData['displaySightseeingBreakup'] : 0;
            $displayVisaBreakup = isset($postData['displayVisaBreakup']) ? $postData['displayVisaBreakup'] : 0;

            $IsDayWiseItinerary = isset($postData['IsDayWiseItinerary']) ? (int) $postData['IsDayWiseItinerary'] : 0;
            $OverviewDetails = isset($postData['OverviewDetails']) ? $postData['OverviewDetails'] : '';
            $InternalRemark = isset($postData['InternalRemark']) ? $postData['InternalRemark'] : '';
            $ShareModifyRemark = isset($postData['ShareModifyRemark']) ? (int) $postData['ShareModifyRemark'] : 0;
            $ModificationRemark = isset($postData['ModificationRemark']) ? substr($postData['ModificationRemark'], 0, 1950) : '';

            $tpsysID = $postData['TPSysId'];
            $ProposalTPSysId = $postData['ProposalTPSysId'];
            $RefTPSysId = 0;
            $currentDate = date('Y-m-d H:i:s');
            $travelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID, 'Query'); // get query data from customer travel plan
            $PackageTypeEconomyMask = ($postData['PackageType'] == 'Quick') ? 6 : 7;
            $EconomyMask = $PackageTypeEconomyMask;
            $destinatioPlaces = $destinationIds = $destinatioPlacesForTitle = $countriesIds = '';
            if (!empty($postData['PackageType']) && $postData['PackageType'] == 'Quick') {
                $destinatioPlacesA = $destinationIdsA = $destinatioPlacesForTitleA = $countriesId = array();
                if (isset($postData['destination']) && is_array($postData['destination'])) {
                    foreach ($postData['destination'] as $keyOption => $desCityA) {
                        foreach ($desCityA as $key => $desCity) {
                            $destinatioPlacesA[] = $desCity;
                            $destinationIdsA[] = $postData['hidden_destination_id'][$keyOption][$key];
                            $destinatioPlacesForTitleA[] = $postData['hidden_destination_withoutcountry'][$keyOption][$key];
                            $countriesId[] = $postData['hidden_destination_id'][$keyOption][$key];
                        }
                        $noOfNights = 0;
                        if (isset($postData['noofnight'][$keyOption]) && !empty($postData['noofnight'][$keyOption]) && is_array($postData['noofnight'][$keyOption])) {
                            foreach ($postData['noofnight'][$keyOption] as $nnKey => $nnVal) {
                                $noOfNights += $nnVal;
                            }
                        }
                    }
                }
                $destinatioPlaces .= implode(', ', array_unique($destinatioPlacesA));
                $destinationIds .= implode(', ', array_unique($destinationIdsA));
                $destinatioPlacesForTitle .= implode('-', array_unique($destinatioPlacesForTitleA));
                $countriesIds .= implode(', ', array_unique($countriesId));
            } else {
                $cityobj = new Travel_Model_TblCity();
                $destinationIds = trim($postData['otherlocationcity']);
                if (!empty($destinationIds)) {
                    $otherlocationcity = $cityobj->getCityDetailsByMultipleId($destinationIds);
                    $CityNameArr = array_column($otherlocationcity, 'Title');
                    $destinatioPlaces = implode(', ', $CityNameArr);
                    $destinatioPlacesForTitle = implode('-', $CityNameArr);
                } else {
                    $destinatioPlaces = '';
                    $destinatioPlacesForTitle = '';
                }
                $noOfNights = $postData['noofnights'];
                $packagePdf = $_FILES['packagePdf']['name'];
                if (isset($packagePdf) && $packagePdf != '') {
                    $StartDate = $travelplandata[0]['StartDate']->format('Y_M');
                    $orignalFolderName = $_SERVER["DOCUMENT_ROOT"] . "/public/upload/media/agency/" . $AgencySysId . "/pdf/" . $StartDate;
                    $fileExt = end((explode(".", $packagePdf)));
                    $fileName = 'quick_package_pdf' . '_' . time() . '.' . $fileExt;
                    if (!file_exists($orignalFolderName)) {
                        @mkdir($orignalFolderName, 0777, true);
                    }
                    if ($fileExt == 'pdf') {
                        $temp_file_name = $_FILES['packagePdf']["tmp_name"]; // temprary file name
                        if (move_uploaded_file($temp_file_name, $orignalFolderName . "/" . $fileName)) {
                            $pdfFileName = $fileName;
                        }
                    }
                }
            }
            $packagePdfValue = isset($postData['packagePdfValue']) ? $postData['packagePdfValue'] : '';
            $modelPkgString = new Gtxwebservices_Model_Currency();
            $pkgSearhString = $modelPkgString->updateQuickPkgSearchString($destinationIds);
            $agentsysID = $this->intLoggedinUserId;
            $objPackage = new Travel_Model_TblPackage();
            $packageInclList = $objPackage->getPackageInclusionList();
            if (!empty($postData['InclMask'])) {
                $charIM = '';
                $inclmask = '1';
                for ($k = 0; $k < count($packageInclList); $k++) {
                    $charIM = in_array($packageInclList[$k]['InclId'], @$postData['InclMask']) ? '1' : '0';
                    $inclmask .= $charIM;
                }
            }
            $supplier_type_id = $this->_HtmlPurifier->filter($postData['supplier_type_id']);
            if ($supplier_type_id != "" && $supplier_type_id != 0) {
                $objSupplier = new Travel_Model_TblSupplier();
                $supplierDetails = $objSupplier->getSupplierList($supplier_type_id);
                $supplierMasking = $supplierDetails['Services'];
                $SupplierServicesArrDB = $objSupplier->getSupplierServices(); //Get Supplier Services
                $servicesMaskingArr = $objSupplier->getMasking($supplierMasking, $SupplierServicesArrDB, 'SupplierSerSysId');
                $PackageSupplierTypeSysIdArr = array($this->SupplierTypeSysId);
                $newMaskingArr = array_unique(array_merge($servicesMaskingArr, $PackageSupplierTypeSysIdArr));
                $supplierServicesNewMasking = $objSupplier->setMasking($newMaskingArr, $SupplierServicesArrDB, 'SupplierSerSysId');
                $supplierMaskingUpdateArr = array('Services' => $supplierServicesNewMasking);
                $objSupplier->updateSupplier($supplierMaskingUpdateArr, $supplier_type_id);
            }
            $IsB2BAgent = !empty($travelplandata[0]['IsB2BAgent']) ? $travelplandata[0]['IsB2BAgent'] : 0;
            $ProposalEmailTo = $travelplandata[0]['EmailId'];
            //            if ($IsB2BAgent != '') {
            //                $getcustomerdetails = $this->_crmcustomerObj->GetCustomerDetailsByEmailB2B($ProposalEmailTo, $travelplandata[0]['AgencySysId']);
            //            } else {
            //                $getcustomerdetails = $this->_crmcustomerObj->GetCustomerDetailsByEmail($ProposalEmailTo, $travelplandata[0]['AgencySysId']);
            //            }

            $getlatestversion = $this->_crmcusttravelplan->GetLatestVersionID($tpsysID);
            $versionnum = isset($getlatestversion[0]['VersionId']) ? $getlatestversion[0]['VersionId'] : 0;
            $VersionId = $versionnum;
            $currentDate = date('Y-m-d H:i:s');
            $PkgSellValidTill = (!is_null($ProposalExpiryDays) && $ProposalExpiryDays !== '') ? date('Y-m-d', strtotime($currentDate . ' + ' . (int) $ProposalExpiryDays . ' days')) : date('Y-m-d', strtotime($currentDate . ' + 90 days'));
            if (isset($postData['onlySightseeing']) && $postData['onlySightseeing'] == 1) {
                $noOfNights = 0;
                $checkDateArr = array();
                foreach ($postData['sightseeingDate'] as $hdKey => $hdVal) {
                    if (!in_array($hdVal, $checkDateArr)) {
                        $checkDateArr[] = $postData['sightseeingDate'][$hdKey];
                        $noOfNights++;
                    }
                }
                $noOfNights = $noOfNights - 1;
                $destinationIds = $postData['DestinationPlacesSysId'];
                $destinatioPlaces = $postData['DestinationPlaces'];
            }
            if ($ProposalTPSysId > 0) {
                if ($postData['PackageType'] == 'Quick') {
                    $travelplandataProp = $this->_crmcusttravelplan->GetVersionAndOptionsByTpSysId($ProposalTPSysId); // get proposal data from customer travel plan
                    $mMultiOptions = json_decode($travelplandataProp['MultiOptions'], 1);
                    $VersionsOfOptions = (isset($mMultiOptions) && !empty($mMultiOptions)) ? (array_values($mMultiOptions)) : '';
                    $versionIds = (isset($VersionsOfOptions) && !empty($VersionsOfOptions)) ? array_keys($VersionsOfOptions[0]) : '';
                    $MasterTPsysIdArr = (isset($VersionsOfOptions) && !empty($VersionsOfOptions)) ? array_values($VersionsOfOptions[0]) : '';
                    $MasterTPSysId = $MasterTPsysIdArr[0];
                    if (empty($versionIds)) {
                        $versionIds = $ProposalTPSysId;
                    }

                    $flexiPackageList = $this->_crmcusttravelplan->GetTravelPlanDetailsByQueryIdAndVersion($MasterTPSysId, $versionIds);
                    $TPIntSysIdsArr = $ProposalTPSysIdArr = array();
                    $flexiPackageListOptions = array();
                    foreach ($flexiPackageList as $flexiPackage) {
                        $ProposalTPSysIdArr[] = $flexiPackage['TPSysId'];
                        $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($flexiPackage['TPSysId']); // get itenary// get proposal data from customer travel plan
                        $TPIntSysIdsArr[] = array_column($travelplanIetnaryData, 'TPIntSysId');
                    }
                    $TPIntSysIdsArr = array_values($TPIntSysIdsArr);
                }
                $ProposalData = $this->_crmcusttravelplan->GetTravelPlanByCustomer($ProposalTPSysId); // get proposal data from customer travel plan
                if (empty($ProposalTPSysIdArr)) {
                    $ProposalTPSysIdArr[0] = $ProposalTPSysId;
                }
                if ($ProposalData[0]['StatusType'] == 16) {

                    $deldata = array(
                        'UpdateDate' => $this->currentDate,
                        'IsMarkForDel' => '1',
                        'IsActive' => '0'
                    );
                    $delsightdata = array(
                        'UpdateDate' => $this->currentDate,
                        'IsMarkForDelete' => '1',
                        'IsActive' => '0'
                    );
                    $whereI = array('TPSysId IN (?) ' => $ProposalTPSysIdArr);
                    $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan', $deldata, $whereI);
                    $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_Rate', $deldata, $whereI);
                    $this->_objPackage->updateData('TB_Agency_Customer_Trans_Fixed', $deldata, $whereI);
                    $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_AddonServices', $delsightdata, $whereI);
                    $whereMPR = array('TPIntSysId IN (?)' => $ProposalTPSysIdArr);
                    $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_MarketWise_Rate', $deldata, $whereMPR);
                    if (!empty($TPIntSysIdsArr)) {
                        $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_Itenary', $deldata, $whereI);
                        $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_Itenary_Places', $deldata, $whereI);
                        $where = array('TPIntSysId IN (?)' => $TPIntSysIdsArr);
                        $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_Itenary_Events', $deldata, $where);
                        $where1 = array('InvnItemSysId IN (?)' => $TPIntSysIdsArr);
                        $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_SightSeeing', $delsightdata, $where1);
                        $where2 = array('TPIntSysId IN (?)' => $TPIntSysIdsArr);
                        $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_Accom', $deldata, $where2);
                    }
                    $getlatestversion = $this->_crmcusttravelplan->GetLatestVersionID($tpsysID); //here 4 is statustype //removed ,4 from function by mangal (03.06.2022) because multiple same version id created
                    if (!empty($getlatestversion)) {
                        $versionnum = $getlatestversion[0]['VersionId'] ? $getlatestversion[0]['VersionId'] : 0;
                        $VersionId = $versionnum;
                    } else {
                        $VersionId = 0;
                    }
                    if ((int) $ProposalData[0]['RefTPSysId'] > 0) {
                        $RefTPSysId = $ProposalData[0]['RefTPSysId'];
                    }
                } else if ($ProposalData[0]['StatusType'] == 17 || $ProposalData[0]['StatusType'] == 13 || $ProposalData[0]['StatusType'] == 7) {
                    $RefTPSysId = $ProposalData[0]['TPSysId'];
                }
                $cust_name = ucfirst(stripslashes($ProposalData[0]['FirstName']));
                $AgentRemark = $ProposalData[0]['AgentRemark'];
                $roomjson = (isset($travelplandata[0]['RoomInfoJson'])) ? $travelplandata[0]['RoomInfoJson'] : $ProposalData[0]['RoomInfoJson'];
                $roomjsonArr = json_decode($roomjson, 1);
                $main_trip_start_date = (isset($travelplandata[0]['StartDate']) && !empty($travelplandata[0]['StartDate'])) ? $travelplandata[0]['StartDate']->format('Y-m-d') : $ProposalData[0]['StartDate']->format('Y-m-d');
                $main_trip_end_date = date('Y-m-d', strtotime($main_trip_start_date . " + $noOfNights days"));
                $main_trip_departuredate = date('d/m/Y', strtotime($main_trip_start_date));
                $main_trip_returndate = date('d/m/Y', strtotime($main_trip_end_date));
                $going_from_cityid = $ProposalData[0]['SourcePlaceSysId'];
                $going_from_cityname = $ProposalData[0]['SourcePlaces'];
                $totaladult = 0;
                $totalchild = 0;
                $totalInfant = 0;
                $Adultextrabed = $Childextrabed = $Childwithoutbed = $Adultwithoutbed = 0;
                $roomjson = array();
                for ($k = 1; $k <= count($roomjsonArr); $k++) {
                    $roomjsonArr[$k]['departuredate'] = $main_trip_departuredate;
                    $roomjsonArr[$k]['returndate'] = !empty($noOfNights) ? $main_trip_returndate : '';
                    $totaladult = $totaladult + $roomjsonArr[$k]['Adult'];
                    $totalchild = $totalchild + $roomjsonArr[$k]['Child'];
                    $totalInfant = $totalInfant + $roomjsonArr[$k]['Infant'];
                    if (isset($roomjsonArr[$k]['adult_type']) && trim($roomjsonArr[$k]['adult_type']) == 'single') {
                        $SingleOAdult++;
                    }
                    if (isset($roomjsonArr[$k]['AdultBedType']) && trim($roomjsonArr[$k]['AdultBedType']) == 'extrabed') {
                        $Adultextrabed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_1']) == 'extrabed') {
                        $Childextrabed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_2']) == 'extrabed') {
                        $Childextrabed++;
                    }
                    if (isset($roomjsonArr[$k]['AdultBedType']) && trim($roomjsonArr[$k]['AdultBedType']) == 'withoutbed') {
                        $Adultwithoutbed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_1']) == 'withoutbed') {
                        $Childwithoutbed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_2']) == 'withoutbed') {
                        $Childwithoutbed++;
                    }
                }
                $roomjson = json_encode($roomjsonArr);
                $totaltraveller = $totaladult + $totalchild;
            } else {
                $searchResult = $travelplandata[0]; //$sessionPackageSearchData->searchData;
                $going_from_cityid = $searchResult['SourcePlaceSysId'];
                $going_from_cityname = $searchResult['SourcePlaces'];
                $main_trip_start_date = $searchResult['StartDate']->format('Y-m-d');
                $main_trip_end_date = date('Y-m-d', strtotime($main_trip_start_date . " + $noOfNights days"));
                $main_trip_departuredate = date('d/m/Y', strtotime($main_trip_start_date));
                $main_trip_returndate = date('d/m/Y', strtotime($main_trip_end_date));
                $cust_name = ucfirst(stripslashes($searchResult['FirstName']));
                $AgentRemark = !empty($searchResult['leadRemark']);
                $roomjson = $searchResult['RoomInfoJson'];
                $roomjsonArr = json_decode($roomjson, 1);
                $totaladult = 0;
                $totalchild = 0;
                $totalInfant = 0;
                $Adultextrabed = $Childextrabed = $Childwithoutbed = $Adultwithoutbed = $SingleOAdult = 0;
                $roomjson = array();
                for ($k = 1; $k <= count($roomjsonArr); $k++) {
                    $roomjsonArr[$k]['departuredate'] = $main_trip_departuredate;
                    $roomjsonArr[$k]['returndate'] = !empty($noOfNights) ? $main_trip_returndate : '';
                    $totaladult = $totaladult + $roomjsonArr[$k]['Adult'];
                    $totalchild = $totalchild + $roomjsonArr[$k]['Child'];
                    $totalInfant = $totalInfant + $roomjsonArr[$k]['Infant'];
                    if (isset($roomjsonArr[$k]['adult_type']) && trim($roomjsonArr[$k]['adult_type']) == 'single') {
                        $SingleOAdult++;
                    }
                    if (isset($roomjsonArr[$k]['AdultBedType']) && trim($roomjsonArr[$k]['AdultBedType']) == 'extrabed') {
                        $Adultextrabed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_1']) == 'extrabed') {
                        $Childextrabed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_2']) == 'extrabed') {
                        $Childextrabed++;
                    }
                    if (isset($roomjsonArr[$k]['AdultBedType']) && trim($roomjsonArr[$k]['AdultBedType']) == 'withoutbed') {
                        $Adultwithoutbed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_1']) == 'withoutbed') {
                        $Childwithoutbed++;
                    }
                    if (trim($roomjsonArr[$k]['ChildBedType_2']) == 'withoutbed') {
                        $Childwithoutbed++;
                    }
                }
                $roomjson = json_encode($roomjsonArr);
                $totaltraveller = $totaladult + $totalchild;
            }

            if ($postData['queryType'] == 1) {
                $roomCount = !empty($postData['roomCount']) ? $postData['roomCount'] : 1;
                $roomGroupArray[$roomCount]['Adult'] = $postData['group_pax_Single_Occupancy'] + $postData['group_pax_Double_Twin_Occupancy'] + $postData['group_pax_Extra_With_Bed'];
                $roomGroupArray[$roomCount]['Child'] = $postData['group_pax_Extra_Child_With_Bed'] + $postData['group_pax_Extra_Child_Without_Bed'];
                $roomGroupArray[$roomCount]['Infant'] = $postData['group_pax_Infant'];
                $roomGroupArray[$roomCount]['group_pax_Single_Occupancy'] = $postData['group_pax_Single_Occupancy'];
                $roomGroupArray[$roomCount]['group_pax_Double_Twin_Occupancy'] = $postData['group_pax_Double_Twin_Occupancy'];
                $roomGroupArray[$roomCount]['group_pax_Extra_With_Bed'] = $postData['group_pax_Extra_With_Bed'];
                $roomGroupArray[$roomCount]['group_pax_Extra_Child_With_Bed'] = $postData['group_pax_Extra_Child_With_Bed'];
                $roomGroupArray[$roomCount]['group_pax_Extra_Child_Without_Bed'] = $postData['group_pax_Extra_Child_Without_Bed'];
                $roomGroupArray[$roomCount]['group_pax_Infant'] = $postData['group_pax_Infant'];
                $roomGroupArray[$roomCount]['departuredate'] = $main_trip_departuredate;
                $roomGroupArray[$roomCount]['returndate'] = !empty($noOfNights) ? $main_trip_returndate : '';
                $roomjson = json_encode($roomGroupArray);
            }

            $where = "TPSysId = " . $tpsysID;
            $updatetravelplan = array(
                'UpdateDate' => $currentDate,
                'PKqueryType' => !empty($postData['queryType']) ? $postData['queryType'] : 0,
                'IsPriceShared' => 1,
                'PackSpecType' => 4,
                'Countries' => !empty($countriesIds) ? $countriesIds : 0,
                'IsDraft' => ($postData['submitType'] == 'draft') ? 0 : 1,
                'SelectPricingType' => !empty($postData['SelectPricing']) ? $postData['SelectPricing'] : 'Overall',
            );
            if ($_SESSION['AgencyUser']['user']->IsOps == 1 && $postData['submitType'] != 'draft') {
                $updatetravelplan['IsOperationalLead'] = 2;
            }

            $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplan, $where);
            $options = isset($postData['destination']) && is_array($postData['destination']) ? count($postData['destination']) : 0;
            if ($ProposalTPSysId > 0 && $postData['PackageType'] == 'Text') {
                $postData['destination'][1] = array(); // this is required for email text edit case
            }
            $IsOnlySightseeingPkg = 0;
            /* Code  By Mangal For Only Sightseeing Share 25/09/2019 Start */
            if (isset($postData['onlySightseeing']) && $postData['onlySightseeing'] == 1) {
                $mi = 1;
                $checkDesArr = array();
                foreach ($postData['hidden_destination_withoutcountry'][1] as $hKey => $hVal) {
                    if (!in_array($hVal, $checkDesArr)) {
                        $postData['destination'][1][$mi] = $hVal;
                        $checkDesArr[] = $hVal;
                        $mi++;
                    }
                }
                $options = count($postData['destination']);
                $IsOnlySightseeingPkg = 1;
            }
            /* Code  By Mangal For Only Sightseeing Share 25/09/2019 End */
            $endVersionId = $VersionId + 1 + $options;
            //echo "<pre>";print_r($endVersionId);die;
            $versionArray = array();
            for ($i = $VersionId + 1; $i < $endVersionId; $i++) {
                $versionArray[$i] = $tpsysID;
            }
            $RouteSysIdDWAllArray = $getTransferSightseeingDayWise = $getTransferSightseeingRouteWise = array();
            if ($EconomyMask == 6 && $IsDayWiseItinerary == 1) {
                $RouteSysIdDWAll = (isset($postData['RouteSysIdDW'])) ? $postData['RouteSysIdDW'] : array();

                foreach ($RouteSysIdDWAll as $rskey => $rsvalue) {
                    $RouteSysIdDWAllArray = array_merge($RouteSysIdDWAllArray, $rsvalue);
                }

                $RouteSysIdDWAllUnique = array_unique(array_filter($RouteSysIdDWAllArray));
                if (!empty($RouteSysIdDWAllUnique)) {
                    $getTransferSightseeing = $objTransportsRoutes->getTransportsRoutesSightseeingIncluded($RouteSysIdDWAllUnique);
                    $daymani = 1;
                    $CheckRouteSightSysId = array();
                    foreach ($getTransferSightseeing['destination'] as $tdKey => $tdValue) {
                        if ($tdValue['TransportSubType'] == '1') {
                            for ($mani = 1; $mani <= $tdValue['nights']; $mani++) {
                                foreach ($getTransferSightseeing['sightseeing'] as $tsKey => $tsValue) {
                                    if ($tdValue['DestSysId'] . '_' . $mani . '_' . $tdValue['RouteDestSysId'] == $tsValue['DestSysId'] . '_' . $tsValue['Sequence'] . '_' . $tsValue['RouteDestSysId'] && $tdValue['RouteSysId'] == $tsValue['RouteSysId']) {
                                        $getTransferSightseeingDayWise[$daymani][] = $tsValue;
                                        $CheckRouteSightSysId[] = $tsValue['RouteSightSysId'];
                                    }
                                }
                                $daymani++;
                            }
                        }
                    }

                    foreach ($getTransferSightseeing['sightseeing'] as $tsKey => $tsValue) {
                        $TransportSubType = explode(',', $tsValue['TransportSubType']);
                        if (in_array(2, $TransportSubType)) {
                            $getTransferSightseeingRouteWise[$tsValue['RouteSysId']][] = $tsValue;
                        }
                    }
                }
            }
            
            if (isset($postData['destination']) && is_array($postData['destination'])) {
                foreach ($postData['destination'] as $optionKey => $destinationArray) {
                    $CurrencyType = isset($postData['option' . $optionKey . 'CurrencyType']) ? (int)$postData['option' . $optionKey . 'CurrencyType'] : 1;
                    $HotelCostCurrency = (isset($postData['HotelCostCurrency'][$optionKey]) && !empty($postData['HotelCostCurrency'][$optionKey])) ? $postData['HotelCostCurrency'][$optionKey] : array();
                    $getMultipleConvertionRate = array();
                    $ComponentCurrencyType = $HotelCostCurrency;
                    $othersCurrency = array_filter($ComponentCurrencyType, function($val) use ($CurrencyType) {
                        return $val !== $CurrencyType;
                    });
                    $ExchangeRateMaarkup = $this->agencyDetails['ExchangeRateMaarkup'];
                    if(!empty($othersCurrency)){
                        $getMultipleConvertionRate = $TblCurrency->getMultipleConvertionRate($ComponentCurrencyType,$CurrencyType,$ExchangeRateMaarkup);
                    } 
                    $HotelVoucherStatus = $FlightVoucherStatus = $SightseeingVoucherStatus = $TransferVoucherStatus = $OtherVoucherStatus = $VisaVoucherStatus = 0;
                    $checkDuplicateSightseeingSeq = $TransferIncludedSightseeingFixTransSysId = array();
                    $VersionId++;
                    $GSTApplicableOn = $postData['option' . $optionKey . 'pricingGST'];
                    $packageCost = (float) $postData['op' . $optionKey . 'Total_Sales_Price'];
                    $AgencyMarkUp = (float) $postData['op' . $optionKey . 'Mark_Up'];
                    $ServiceFee = (isset($postData['op' . $optionKey . 'ServiceFee'])) ? (int) $postData['op' . $optionKey . 'ServiceFee'] : 0;
                    $AdvancedPaymentOption = $postData['option' . $optionKey . 'Advancedpricing'];
                    $AgencyExtraMarkUp = 0;
                    $AgencyDiscount = isset($postData['op' . $optionKey . 'Discount']) ? (float) $postData['op' . $optionKey . 'Discount'] : 0;
                    $Advance_Tcs = isset($postData['op' . $optionKey . 'Advance_Tcs']) ? (float) $postData['op' . $optionKey . 'Advance_Tcs'] : 0;
                    $intProductType = 9;
                    $intProductGeoType = 1; // 1 For Domestic, 2 For International
                    
                    $arrInputData = array(
                        "GSTApplicableOn" => $GSTApplicableOn,
                        "intProductType" => $intProductType,
                        "intProductGeoType" => $intProductGeoType,
                        "Cost" => (float) $postData['op' . $optionKey . 'Total'] + (float) $postData['op' . $optionKey . 'Mark_Up'],
                        "AgencyMarkUp" => $AgencyMarkUp,
                        "AgencyExtraMarkUp" => $AgencyExtraMarkUp,
                        "AgencyDiscount" => $AgencyDiscount
                    );
                    $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);

                    $netPriceArrayServiceTax = 0;
                    if ($arrGSTCalculations['TaxType'] == 1) {
                        $netPriceArrayServiceTax = $arrGSTCalculations['GSTAmount'];
                        //$netPriceArrayServiceTax = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($arrGSTCalculations['MyCost'], $arrGSTCalculations['TaxRate']);
                    }
                    $AgencyMarkupArrayServiceTax = 0;
                    if ($arrGSTCalculations['TaxType'] == 2) {
                        $AgencyMarkupArrayServiceTax = $arrGSTCalculations['GSTAmount'];
                        //$AgencyMarkupArrayServiceTax = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($arrGSTCalculations['AgencyMarkUp'], $arrGSTCalculations['TaxRate']);
                    }
                    $planbookingID = 'QS/' . date('y');
                    $EmailContent = isset($postData['EmailContent']) ? $this->_HtmlPurifier->filter($postData['EmailContent']) : '';
                    $FlightContent = isset($postData['FlightContent']) ? $this->_HtmlPurifier->filter($postData['FlightContent']) : '';
                    $flightDetailAdultCost = (isset($postData['op' . $optionKey . 'FlightAdultCost']) && $postData['op' . $optionKey . 'FlightAdultCost'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightAdultCost']) : '';
                    $flightDetailChildCost = (isset($postData['op' . $optionKey . 'FlightChildCost']) && $postData['op' . $optionKey . 'FlightChildCost'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightChildCost']) : '';
                    $flightDetailInfantCost = (isset($postData['op' . $optionKey . 'FlightInfantCost']) && $postData['op' . $optionKey . 'FlightInfantCost'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightInfantCost']) : '';
                    $flightDetailCost = (isset($postData['op' . $optionKey . 'FlightCost']) && $postData['op' . $optionKey . 'FlightCost'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightCost']) : '';
                    $flightDetailMarkup = (isset($postData['op' . $optionKey . 'FlightMarkup']) && $postData['op' . $optionKey . 'FlightMarkup'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightMarkup']) : '';
                    $flightDetailGst = (isset($postData['option' . $optionKey . 'pricingGSTFlight']) && $postData['option' . $optionKey . 'pricingGSTFlight'] != 0) ? $this->_HtmlPurifier->filter($postData['option' . $optionKey . 'pricingGSTFlight']) : '';
                    $flightDetailTotal = (isset($postData['op' . $optionKey . 'FlightCostTotal']) && $postData['op' . $optionKey . 'FlightCostTotal'] != 0) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'FlightCostTotal']) : '';
                    $IsShareCombinedFlightPricing = isset($postData['IsShareCombinedFlightPricing']) ? (int) $postData['IsShareCombinedFlightPricing'] : 0;
                    $IsShareCombinedVisaPricing = isset($postData['IsShareCombinedVisaPricing']) ? (int) $postData['IsShareCombinedVisaPricing'] : 0;
                    $isShareWithFlight = (isset($flightDetailTotal) && !empty($flightDetailTotal)) ? 1 : 0;
                    $flightType = (isset($postData['flightType']) && !empty($postData['flightType'])) ? (int) $postData['flightType'] : 1;
                    $CHeckFlightContent = (isset($postData['FlightContent']) && !empty($postData['FlightContent'])) ? $postData['FlightContent'] : '';
                    if ($isShareWithFlight == 0) {
                        if (!empty($CHeckFlightContent)) {
                            $isShareWithFlight = 1;
                        }
                    }

                    if ($flightType == 1) {
                        $flightSupplier = isset($postData['flight_supplier_textbased']) ? trim($postData['flight_supplier_textbased']) : '';
                        $flightSupplierSysId = isset($postData['flight_supplier_textbased_id']) ? (int) ($postData['flight_supplier_textbased_id']) : 0;
                    } else {
                        $flightSupplier = isset($postData['flight_supplier_detailed']) ? trim($postData['flight_supplier_detailed']) : '';
                        $flightSupplierSysId = isset($postData['flight_supplier_detailed_id']) ? (int) ($postData['flight_supplier_detailed_id']) : 0;
                    }
                    $flightPriceArray = json_encode(array('flightDetailAdultCost' => $flightDetailAdultCost, 'flightDetailChildCost' => $flightDetailChildCost, 'flightDetailInfantCost' => $flightDetailInfantCost, 'flightDetailCost' => $flightDetailCost, 'flightDetailMarkup' => $flightDetailMarkup, 'flightDetailGst' => $flightDetailGst, 'flightDetailTotal' => $flightDetailTotal, 'IsShareCombinedFlightPricing' => $IsShareCombinedFlightPricing, 'supplierName' => $flightSupplier, 'supplierSysId' => $flightSupplierSysId));
                    $CabContent = isset($postData['CabContent']) ? $this->_HtmlPurifier->filter($postData['CabContent']) : '';
                    $VisaContent = isset($postData['VisaContent']) ? $this->_HtmlPurifier->filter($postData['VisaContent']) : '';

                    $visaDetailAdultCost = (isset($postData['op' . $optionKey . 'VisaAdultCost'])) ? $postData['op' . $optionKey . 'VisaAdultCost'] : 0;
                    $visaDetailChildCost = isset($postData['op' . $optionKey . 'VisaChildCost']) ? $postData['op' . $optionKey . 'VisaChildCost'] : 0;
                    $visaDetailInfantCost = isset($postData['op' . $optionKey . 'VisaInfantCost']) ? $postData['op' . $optionKey . 'VisaInfantCost'] : 0;
                    $visaDetailCost = isset($postData['op' . $optionKey . 'VisaCost']) ? $postData['op' . $optionKey . 'VisaCost'] : 0;
                    $visaDetailMarkup = isset($postData['op' . $optionKey . 'VisaMarkup']) ? $postData['op' . $optionKey . 'VisaMarkup'] : 0;
                    $visaDetailGst = isset($postData['option' . $optionKey . 'pricingGSTVisa']) ? $postData['option' . $optionKey . 'pricingGSTVisa'] : 0;
                    $visaDetailTotal = isset($postData['op' . $optionKey . 'VisaCostTotal']) ? $postData['op' . $optionKey . 'VisaCostTotal'] : 0;
                    $visa_supplier_type = isset($postData['visa_supplier_type']) ? trim($postData['visa_supplier_type']) : '';
                    $visa_supplier_type_id = isset($postData['visa_supplier_type_id']) ? (int) ($postData['visa_supplier_type_id']) : 0;

                    $isShareWithVisa = (isset($visaDetailTotal) && !empty($visaDetailTotal)) ? 1 : 0;
                    $visaPriceArray = json_encode(array('visaDetailAdultCost' => $visaDetailAdultCost, 'visaDetailChildCost' => $visaDetailChildCost, 'visaDetailInfantCost' => $visaDetailInfantCost, 'visaDetailCost' => $visaDetailCost, 'visaDetailMarkup' => $visaDetailMarkup, 'visaDetailGst' => $visaDetailGst, 'visaDetailTotal' => $visaDetailTotal, 'ShareCombined' => $IsShareCombinedVisaPricing, 'visa_supplier_type' => $visa_supplier_type, 'visa_supplier_type_id' => $visa_supplier_type_id));

                    $hotelDetailCost = (isset($postData['op' . $optionKey . 'HotelCost']) && $postData['op' . $optionKey . 'HotelCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'HotelCost']) : 0;
                    $hotelDetailMarkup = (isset($postData['op' . $optionKey . 'HotelMarkup']) && $postData['op' . $optionKey . 'HotelMarkup'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'HotelMarkup']) : 0;
                    $hotelDetailTotal = (isset($postData['op' . $optionKey . 'HotelCostTotal']) && $postData['op' . $optionKey . 'HotelCostTotal'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'HotelCostTotal']) : 0;
                    $hotelPriceArray = json_encode(array('hotelDetailCost' => $hotelDetailCost, 'hotelDetailMarkup' => $hotelDetailMarkup, 'hotelDetailTotal' => $hotelDetailTotal));

                    $transportAdultCost = (isset($postData['op' . $optionKey . 'TransportAdultCost']) && $postData['op' . $optionKey . 'TransportAdultCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'TransportAdultCost']) : 0;
                    $transportChildCost = (isset($postData['op' . $optionKey . 'TransportChildCost']) && $postData['op' . $optionKey . 'TransportChildCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'TransportChildCost']) : 0;
                    $transportDetailCost = (isset($postData['op' . $optionKey . 'TransportCost']) && $postData['op' . $optionKey . 'TransportCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'TransportCost']) : 0;
                    $transportDetailMarkup = (isset($postData['op' . $optionKey . 'TransportMarkup']) && $postData['op' . $optionKey . 'TransportMarkup'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'TransportMarkup']) : 0;
                    $transportDetailTotal = (isset($postData['op' . $optionKey . 'TransportCostTotal']) && $postData['op' . $optionKey . 'TransportCostTotal'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'TransportCostTotal']) : 0;
                    $transportPriceArray = json_encode(array('transportAdultCost' => $transportAdultCost, 'transportChildCost' => $transportChildCost, 'transportDetailCost' => $transportDetailCost, 'transportDetailMarkup' => $transportDetailMarkup, 'transportDetailTotal' => $transportDetailTotal));

                    $sightseeingAdultCost = (isset($postData['op' . $optionKey . 'SightseeingAdultCost']) && $postData['op' . $optionKey . 'SightseeingAdultCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingAdultCost']) : 0;
                    $sightseeingChildCost = (isset($postData['op' . $optionKey . 'SightseeingChildCost']) && $postData['op' . $optionKey . 'SightseeingChildCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingChildCost']) : 0;
                    $sightseeingInfantCost = (isset($postData['op' . $optionKey . 'SightseeingInfantCost']) && $postData['op' . $optionKey . 'SightseeingInfantCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingInfantCost']) : 0;
                    $sightseeingDetailCost = (isset($postData['op' . $optionKey . 'SightseeingCost']) && $postData['op' . $optionKey . 'SightseeingCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingCost']) : 0;
                    $sightseeingDetailMarkup = (isset($postData['op' . $optionKey . 'SightseeingMarkup']) && $postData['op' . $optionKey . 'SightseeingMarkup'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingMarkup']) : 0;
                    $sightseeingDetailTotal = (isset($postData['op' . $optionKey . 'SightseeingCostTotal']) && $postData['op' . $optionKey . 'SightseeingCostTotal'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'SightseeingCostTotal']) : 0;
                    $sightseeingPriceArray = json_encode(array('sightseeingAdultCost' => $sightseeingAdultCost, 'sightseeingChildCost' => $sightseeingChildCost, 'sightseeingInfantCost' => $sightseeingInfantCost, 'sightseeingDetailCost' => $sightseeingDetailCost, 'sightseeingDetailMarkup' => $sightseeingDetailMarkup, 'sightseeingDetailTotal' => $sightseeingDetailTotal));
                    
                    
                    $mealAdultCost = (isset($postData['op' . $optionKey . 'MealAdultCost']) && $postData['op' . $optionKey . 'MealAdultCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealAdultCost']) : 0;
                    $mealChildCost = (isset($postData['op' . $optionKey . 'MealChildCost']) && $postData['op' . $optionKey . 'MealChildCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealChildCost']) : 0;
                    $mealInfantCost = (isset($postData['op' . $optionKey . 'MealInfantCost']) && $postData['op' . $optionKey . 'MealInfantCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealInfantCost']) : 0;
                    $mealDetailCost = (isset($postData['op' . $optionKey . 'MealCost']) && $postData['op' . $optionKey . 'MealCost'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealCost']) : 0;
                    $mealDetailMarkup = (isset($postData['op' . $optionKey . 'MealMarkup']) && $postData['op' . $optionKey . 'MealMarkup'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealMarkup']) : 0;
                    $mealDetailTotal = (isset($postData['op' . $optionKey . 'MealCostTotal']) && $postData['op' . $optionKey . 'MealCostTotal'] != 0) ? (float) $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'MealCostTotal']) : 0;
                    $mealPriceArray = json_encode(array('mealAdultCost' => $mealAdultCost, 'mealChildCost' => $mealChildCost, 'mealInfantCost' => $mealInfantCost, 'mealDetailCost' => $mealDetailCost, 'mealDetailMarkup' => $mealDetailMarkup, 'mealDetailTotal' => $mealDetailTotal));
            
                    
                    $otherTitle = isset($postData['otherTitle']) ? json_encode($postData['otherTitle']) : '';
                    $otherDescription = isset($postData['otherDescription']) ? json_encode($postData['otherDescription']) : '';
                    if ($EconomyMask == 6 && $IsDayWiseItinerary == 1) {
                        $EmailContent = '';
                    }
                    $finalEmailContent = json_encode(array('EmailContent' => trim($EmailContent), 'FlightContent' => $FlightContent, 'flightPriceArray' => $flightPriceArray, 'visaPriceArray' => $visaPriceArray, 'CabContent' => $CabContent, 'VisaContent' => $VisaContent, 'otherTitle' => $otherTitle, 'otherDescription' => $otherDescription, 'hotelPriceArray' => $hotelPriceArray, 'transportPriceArray' => $transportPriceArray, 'sightseeingPriceArray' => $sightseeingPriceArray, 'mealPriceArray' => $mealPriceArray, 'displayFlightBreakup' => $displayFlightBreakup, 'displayHotelBreakup' => $displayHotelBreakup, 'displayTransferBreakup' => $displayTransferBreakup, 'displaySightseeingBreakup' => $displaySightseeingBreakup, 'displayVisaBreakup' => $displayVisaBreakup, 'ShareModifyRemark' => $ShareModifyRemark, 'ModificationRemark' => $ModificationRemark));
                    $Details = (!empty($OverviewDetails) && $EconomyMask == 6 && $IsDayWiseItinerary == 1) ? $OverviewDetails : '';
                    $FullServiceTax = (float) $netPriceArrayServiceTax + (float) $AgencyMarkupArrayServiceTax;
                    $IsHotelOnlyPackage = (isset($postData['PlanType']) && $postData['PlanType'] == 2) ? 1 : 0;
                    $NetPriceN = (!empty($postData['op' . $optionKey . 'Total_Sales_Price']) && is_numeric($postData['op' . $optionKey . 'Total_Sales_Price'])) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'Total_Sales_Price']) : 0;
                    $customertravelpaln = array(
                        'VersionId' => $VersionId,
                        'PlanBookingId' => $planbookingID,
                        'MasterTPSysId' => $tpsysID,
                        'AgencySysId' => $travelplandata[0]['AgencySysId'],
                        'AgentSysId' => $agentsysID,
                        'StatusType' => (in_array($postData['submitType'], array('draft', 'view'))) ? 16 : 4, //---------------NTW for draft--------------
                        'CustomerSysId' => $travelplandata[0]['CustomerSysId'],
                        'PlanType' => (isset($postData['PlanType'])) ? (int) $postData['PlanType'] : 5,
                        'MinPax' => $travelplandata[0]['MinPax'],
                        'PackRangeType' => $travelplandata[0]['PackRangeType'],
                        'Title' => $destinatioPlacesForTitle . ' trip details for ' . trim($travelplandata[0]['FirstName']),
                        'EconomyMask' => $EconomyMask, // 6 7 is only for quick package (6 == quick package , 7 = quick package email text only)//$travelplandata[0]['EconomyMask'],
                        'PackTypeMask' => $travelplandata[0]['PackTypeMask'],
                        'InclCatMask' => $travelplandata[0]['InclCatMask'],
                        'InclMask' => !empty($inclmask) ? $inclmask : 0,
                        'ExclusionMask' => $travelplandata[0]['ExclusionMask'],
                        'PackSpecType' => 4, //1 for itinerary, 2 for only hotel , 3 for dynamic , 4 for this
                        'SeasonMask' => $travelplandata[0]['SeasonMask'],
                        'GeoType' => $travelplandata[0]['GeoType'],
                        'DestinationPlaces' => !empty($destinatioPlaces) ? $destinatioPlaces : '',
                        'DestinationPlacesSysId' => !empty($destinationIds) ? (int) $destinationIds : 0,
                        'Cities' => !empty($destinatioPlaces) ? $destinatioPlaces : '',
                        'CityIds' => !empty($destinationIds) ? $destinationIds : 0,
                        'SourcePlaceSysId' => isset($going_from_cityid) ? $going_from_cityid : '',
                        'SourcePlaces' => isset($going_from_cityname) ? $going_from_cityname : '',
                        'IsFixDatePlan' => $travelplandata[0]['IsFixDatePlan'],
                        'IsFixPlan' => $travelplandata[0]['IsFixPlan'],
                        'Details' => $Details,
                        'ImageTN' => $travelplandata[0]['ImageTN'],
                        'ImgForList' => $travelplandata[0]['ImgForList'],
                        'ImgeDetails' => $travelplandata[0]['ImgeDetails'],
                        'StartDate' => !empty($main_trip_start_date) ? $main_trip_start_date : $currentDate,
                        'ValidTill' => !empty($main_trip_end_date) ? $main_trip_end_date : $currentDate,
                        'PkgSellValidTill' => $PkgSellValidTill,
                        'Price' => (!empty($postData['op' . $optionKey . 'Total']) && is_numeric($postData['op' . $optionKey . 'Total'])) ? $this->_HtmlPurifier->filter($postData['op' . $optionKey . 'Total']) : 0,
                        'XServiceTaxAmount' => (float) $netPriceArrayServiceTax,
                        'GTXServiceTaxAmount' => 0,
                        'AgentServiceTaxAmount' => (float) $AgencyMarkupArrayServiceTax,
                        'AgentsCustomServiceTaxAmount' => 0,
                        'ServiceTaxOnCustomDiscount' => 0,
                        'DiscountMsg' => '',
                        'DiscountType' => 0,
                        'DiscountVal' => isset($postData['op' . $optionKey . 'Discount']) ? (float) $postData['op' . $optionKey . 'Discount'] : 0,
                        'AdvBookingPercent' => isset($AdvancedPaymentOption) ? $AdvancedPaymentOption : 10, //TBD
                        'AdvBookingDays' => 30, //TBD
                        'NetPrice' => $NetPriceN,
                        'MarkUp' => !empty($postData['op' . $optionKey . 'Mark_Up']) ? $this->_HtmlPurifier->filter((float) $postData['op' . $optionKey . 'Mark_Up']) : 0,
                        'MinPrice' => 0,
                        'TotalMinDays' => $travelplandata[0]['TotalMinDays'],
                        'TotalMaxDays' => $travelplandata[0]['TotalMaxDays'],
                        'Hotels' => 0,
                        'InventoryType' => 5,
                        'CreatorSysId' => $agentsysID,
                        'PopularPlaces' => $travelplandata[0]['PopularPlaces'],
                        'Countries' => !empty($countriesIds) ? $countriesIds : 0,
                        'IsInsuranceExist' => $travelplandata[0]['IsInsuranceExist'],
                        'RoomInfoJson' => $this->_HtmlPurifier->filter($roomjson),
                        'ProposalEmailTo' => $ProposalEmailTo, //---------------NTW for draft--------------
                        'CreateDate' => $currentDate,
                        'UpdateDate' => $currentDate,
                        'IsActive' => 1,
                        'IsAprooved' => 1,
                        'SupplierSysId' => (int) $SupplierSysId,
                        'Readymade' => 1,
                        'ApproveDate' => '1900-01-01',
                        'IsMarkForDel' => '0',
                        'IsAprooved' => '1',
                        'CurrencyType' => isset($CurrencyType) ? $CurrencyType : 1,
                        'EmailText' => (isset($finalEmailContent) && $finalEmailContent != '') ? $finalEmailContent : '',
                        'EmailDestination' => !empty($destinatioPlaces) ? $destinatioPlaces : '',
                        'AgentRemark' => !empty($AgentRemark) ? $this->_HtmlPurifier->filter($AgentRemark) : '', //TBD
                        'IsActive' => 1,
                        'IsAprooved' => 1,
                        'IsMarkForDel' => $travelplandata[0]['IsMarkForDel'] ? $travelplandata[0]['IsMarkForDel'] : '0',
                        'TPId' => '0',
                        'IsPriceShared' => 1, // to detect withprice or without price true = If price shared , false = price range shared
                        'GSTSharedMode' => !empty($GSTApplicableOn) ? $this->_HtmlPurifier->filter($GSTApplicableOn) : 0, // (1 for 5% on total Cost, 2 for 18% on Service Fee) to detect what type and how much tax will apply to customer
                        'SACCode' => 440063, // default value 440063 for Tour Oprators..
                        'IsB2BProposal' => trim($travelplandata[0]['IsB2BAgent']) ? trim($travelplandata[0]['IsB2BAgent']) : 0,
                        'B2BAgencySysId' => 0, //trim($GTXNetworkAgencySysId),
                        'IsShared' => (in_array($postData['submitType'], array('draft', 'view'))) ? 0 : 1,
                        'IsDraft' => ($postData['submitType'] == 'draft') ? 0 : 1,
                        'NoofNight' => !empty($noOfNights) ? $noOfNights : 0,
                        'DestinationCovered' => !empty($postData['DestinationCovered']) ? $postData['DestinationCovered'] : '',
                        'MultiOptions' => ($postData['PackageType'] != 'Text') ? json_encode(array($optionKey => $versionArray)) : '',
                        'PKqueryType' => !empty($postData['queryType']) ? $postData['queryType'] : 0,
                        'SelectPricingType' => !empty($postData['SelectPricing']) ? $postData['SelectPricing'] : 'Overall',
                        'SearchString' => !empty($pkgSearhString) ? $pkgSearhString : '',
                        'LeadSourceSysId' => !empty($travelplandata[0]['LeadSourceSysId']) ? $travelplandata[0]['LeadSourceSysId'] : 0,
                        'IsOnlySightseeingPkg' => $IsOnlySightseeingPkg,
                        'isShareWithFlight' => $isShareWithFlight,
                        'ShareCombinedFlightPricing' => $IsShareCombinedFlightPricing,
                        'packagePdf' => ($pdfFileName != '') ? $pdfFileName : $packagePdfValue,
                        'IsHotelOnlyPackage' => (isset($postData['PlanType']) && $postData['PlanType'] == 2) ? 1 : 0, // added for quick hotel package
                        'IsDayWiseItinerary' => $IsDayWiseItinerary,
                        'InternalRemarks' => $InternalRemark,
                        'OpsAgentSysId' => ($_SESSION['AgencyUser']['user']->IsOps == 1) ? $this->intLoggedinUserId : '',
                        'IsOperationalLead' => ($_SESSION['AgencyUser']['user']->IsOps == 1) ? 2 : 0,
                    );

                    if (isset($travelplandata[0]['IsB2BProposal']) && $travelplandata[0]['IsB2BProposal'] == 3) {
                        $customertravelpaln['IsB2BProposal'] = $travelplandata[0]['IsB2BProposal'];
                        $customertravelpaln['B2BAgencySysId'] = $travelplandata[0]['B2BAgencySysId'];
                    }

                    $tpproposalID = $this->_crmcusttravelplan->addCustomerTravelPlan($customertravelpaln);
                    if ($RefTPSysId > 0) {
                        $customertravelpalnMapping = array(
                            'TPSysId' => $tpproposalID,
                            'RefTPSysId' => $RefTPSysId,
                            'ExpectedClosureDate' => $customertravelpaln['StartDate'],
                            'ExpectedValue' => $customertravelpaln['NetPrice'],
                            'IsCoupon' => 0,
                        );
                        $objPackage->insertData('TB_Agency_Customer_TravelPlan_Mapping', $customertravelpalnMapping);
                    }
                    //                                       echo "<pre>";print_r($customertravelpaln);
                    $IsInclusions = isset($postData['IsInclusions']) ? (int) $postData['IsInclusions'] : 0;
                    $IsExclusions = isset($postData['IsExclusions']) ? (int) $postData['IsExclusions'] : 0;
                    $IsCancellationPolicy = isset($postData['IsCancellationPolicy']) ? (int) $postData['IsCancellationPolicy'] : 0;
                    $IsTravelBasics = isset($postData['IsTravelBasics']) ? (int) $postData['IsTravelBasics'] : 0;
                    $IsTermsAndConditions = isset($postData['IsTermsAndConditions']) ? (int) $postData['IsTermsAndConditions'] : 0;
                    $IsBookingTerms = isset($postData['IsBookingTerms']) ? (int) $postData['IsBookingTerms'] : 0;
                    $IsWhyUseUs = isset($postData['IsWhyUseUs']) ? (int) $postData['IsWhyUseUs'] : 0;
                    $IsREFUNDPOLICY = isset($postData['IsREFUNDPOLICY']) ? (int) $postData['IsREFUNDPOLICY'] : 0;

                    $tncdata = array(
                        'AgencySysId' => $travelplandata[0]['AgencySysId'],
                        'TPIntSysId' => $tpproposalID,
                        'Inclusions' => (!empty($postData['Inclusions']) && $IsInclusions == 1) ? $this->_HtmlPurifier->filter($postData['Inclusions']) : '',
                        'Exclusions' => (!empty($postData['Exclusions']) && $IsExclusions == 1) ? $this->_HtmlPurifier->filter($postData['Exclusions']) : '',
                        'CancellationPolicy' => (!empty($postData['CancellationPolicy']) && $IsCancellationPolicy == 1) ? $this->_HtmlPurifier->filter($postData['CancellationPolicy']) : '',
                        'TravelBasics' => (!empty($postData['TravelBasics']) && $IsTravelBasics == 1) ? $this->_HtmlPurifier->filter($postData['TravelBasics']) : '',
                        'TermsAndConditions' => (!empty($postData['TermsAndConditions']) && $IsTermsAndConditions == 1) ? $this->_HtmlPurifier->filter($postData['TermsAndConditions']) : '',
                        'BookingTerms' => (!empty($postData['BookingTerms']) && $IsBookingTerms == 1) ? $this->_HtmlPurifier->filter($postData['BookingTerms']) : '',
                        'WhyUseUs' => (!empty($postData['WhyUseUs']) && $IsWhyUseUs == 1) ? $this->_HtmlPurifier->filter($postData['WhyUseUs']) : '',
                        'REFUNDPOLICY' => (!empty($postData['REFUNDPOLICY']) && $IsREFUNDPOLICY == 1) ? $this->_HtmlPurifier->filter($postData['REFUNDPOLICY']) : '',
                        'IsInclusions' => $IsInclusions,
                        'IsExclusions' => $IsExclusions,
                        'IsCancellationPolicy' => $IsCancellationPolicy,
                        'IsTravelBasics' => $IsTravelBasics,
                        'IsTermsAndConditions' => $IsTermsAndConditions,
                        'IsBookingTerms' => $IsBookingTerms,
                        'IsWhyUseUs' => $IsWhyUseUs,
                        'IsREFUNDPOLICY' => $IsREFUNDPOLICY,
                        'CreateDate' => $currentDate,
                        'UpdateDate' => $currentDate,
                        'IsMarkForDel' => '0',
                        'IsActive' => '1'
                    );
                    //                    echo "<pre>";print_r($tncdata);die; 
                    $this->_crmcustomertravelTerm->addCustomerTerm($tncdata);

                    if ($travelplandata[0]['IsB2BAgent'] == 1) {
                        $MarketPlaceId = 2;
                        $MarketPlace = 'MY B2B';
                    } else {
                        $MarketPlaceId = 1;
                        $MarketPlace = 'MY B2C';
                    }
                    if (is_numeric($postData['op' . $optionKey . 'Total'])) {
                        if ($postData['SelectPricing'] == 'PP') {
                            $netCost = (float) $postData['op' . $optionKey . 'Total'] + (float) $postData['op' . $optionKey . 'Mark_Up'];
                            $Quad_Sharing = isset($postData['op' . $optionKey . 'Quad_Sharing']) ? (float) $postData['op' . $optionKey . 'Quad_Sharing'] : 0;
                            $Quint_Sharing = isset($postData['op' . $optionKey . 'Quint_Sharing']) ? (float) $postData['op' . $optionKey . 'Quint_Sharing'] : 0;
                            $Hexa_Sharing = isset($postData['op' . $optionKey . 'Hexa_Sharing']) ? (float) $postData['op' . $optionKey . 'Hexa_Sharing'] : 0;
                            $costPerperson = isset($postData['op' . $optionKey . 'Double_Twin_Occupancy']) ? (float) $postData['op' . $optionKey . 'Double_Twin_Occupancy'] : 0;
                            $PricePerPerson = (float) $postData['op' . $optionKey . 'Total'] / $totaltraveller;
                            $Infant = (float) $postData['op' . $optionKey . 'Infant'];
                            $Single_Occupancy = (float) $postData['op' . $optionKey . 'Single_Occupancy'];
                            $Extra_With_Bed = (float) $postData['op' . $optionKey . 'Extra_With_Bed'];
                            $Extra_Child_With_Bed = (float) $postData['op' . $optionKey . 'Extra_Child_With_Bed'];
                            $Extra_Child_Without_Bed = (float) $postData['op' . $optionKey . 'Extra_Child_Without_Bed'];
                        } else {
                            $netCost = (float) $postData['op' . $optionKey . 'Total'] + (float) $postData['op' . $optionKey . 'Mark_Up'];
                            $costPerperson = (float) $postData['op' . $optionKey . 'Total'] / $totaltraveller;
                            $PricePerPerson = $costPerperson;
                            $Infant = $Extra_With_Bed = $Extra_Child_With_Bed = $Extra_Child_Without_Bed = '0';
                            $Single_Occupancy = $costPerperson;
                        }
                        //$ExchangeRate = $objPackage->currencyExchangeRate($CurrencyType, 1);
                        $IsMarkupPercent = isset($postData['IsMarkupPercent']) ? (int) $postData['IsMarkupPercent'] : 0;
                        $MarkupPercent = isset($postData['MarkupPercent']) ? (float) $postData['MarkupPercent'] : 0;
                        $travelmarketpriceArray = array(
                            'TPIntSysId' => $tpproposalID,
                            'MarkType' => ($IsMarkupPercent == 1 && $MarkupPercent > 0) ? 'FixedPercent' : 'FixedAmount',
                            'MarketPlaceId' => $MarketPlaceId,
                            'MarketPlace' => $MarketPlace,
                            'AgencySysId' => $travelplandata[0]['AgencySysId'],
                            'Permission' => 1,
                            'MarkPercent' => ($IsMarkupPercent == 1 && $MarkupPercent > 0) ? $MarkupPercent : (float) $postData['op' . $optionKey . 'Mark_Up'],
                            'CostPPDO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostFourO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostSixO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostEightO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostTenO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostTwelveO' => !empty($costPerperson) ? $costPerperson : 0,
                            'CostInfent' => !empty($Infant) ? $Infant : 0,
                            'CostPerPerson' => !empty($costPerperson) ? $costPerperson : 0,
                            'PricePerPerson' => !empty($PricePerPerson) ? $PricePerPerson : 0,
                            'TotalCost' => !empty($netCost) ? $netCost : 0,
                            'CostPPSO' => !empty($Single_Occupancy) ? $Single_Occupancy : 0,
                            'AdultCostExtraBed' => !empty($Extra_With_Bed) ? $Extra_With_Bed : 0,
                            'CostExtraBed' => !empty($Extra_Child_With_Bed) ? $Extra_Child_With_Bed : 0,
                            'CostChildWithoutBed' => !empty($Extra_Child_Without_Bed) ? $Extra_Child_Without_Bed : 0,
                            'FixedDepartureInventory' => 0,
                            //                            'CostPPTO' => 0,
                            'PackCategoryId' => 1,
                            'Tax' => 'Included',
                            'ExcludedPercent' => 0,
                            'FromDate' => $main_trip_start_date,
                            'TourType' => 1,
                            'ToDate' => $main_trip_end_date,
                            'CurrencyType' => isset($CurrencyType) ? $CurrencyType : 1,
                            'CreateDate' => $currentDate,
                            'UpdateDate' => $currentDate,
                            'IsMarkForDel' => '0',
                            'IsActive' => '1',
                            'Discount' => isset($postData['op' . $optionKey . 'Discount']) ? (float) $postData['op' . $optionKey . 'Discount'] : 0,
                            'CostQuad' => $Quad_Sharing,
                            'CostQuint' => $Quint_Sharing,
                            'CostHexa' => $Hexa_Sharing
                        );
                        //                        if($travelplandata[0]['AgencySysId'] == 10383) {
                        //                        echo "<pre>";print_r($travelmarketpriceArray);exit;
                        //                        }


                        $travelitenramarketwsierate = $this->_crmcustomertravelMarketPlaces->addCustomerTravelMarketRate($travelmarketpriceArray);
                        $travelpriceArray = array(
                            'TPSysId' => $tpproposalID,
                            'MasterRefId' => '0',
                            'MarketPlaceId' => $MarketPlaceId,
                            'CurrencyType' => isset($CurrencyType) ? $CurrencyType : 1,
                            'CostInfent' => $postData['op' . $optionKey . 'Infant'],
                            'CostSO' => !empty($postData['op' . $optionKey . 'Single_Occupancy']) ? $postData['op' . $optionKey . 'Single_Occupancy'] : 0,
                            //                            'CostTO' => 0,
                            'AdultCostExtraBed' => !empty($postData['op' . $optionKey . 'Extra_With_Bed']) ? $postData['op' . $optionKey . 'Extra_With_Bed'] : 0,
                            'CostExtraBed' => !empty($postData['op' . $optionKey . 'Extra_Child_With_Bed']) ? $postData['op' . $optionKey . 'Extra_Child_With_Bed'] : 0,
                            'CostWithoutBed' => !empty($postData['op' . $optionKey . 'Extra_Child_Without_Bed']) ? $postData['op' . $optionKey . 'Extra_Child_Without_Bed'] : 0,
                            'CostDO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostFourO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostSixO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostEightO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostTenO' => !empty($costPerperson) ? $costPerperson : 0,
                            //                            'CostTwelveO' => !empty($costPerperson) ? $costPerperson : 0,
                            'FixedDepartureInventory' => 0,
                            'StartDate' => $main_trip_start_date,
                            'ValidTill' => $main_trip_end_date,
                            'IsAprooved' => '1',
                            'CreateDate' => $currentDate,
                            'UpdateDate' => $currentDate,
                            'IsMarkForDel' => '0',
                            'IsActive' => '1',
                            'TourType' => 1,
                            'Discount' => isset($postData['op' . $optionKey . 'Discount']) ? (float) $postData['op' . $optionKey . 'Discount'] : 0,
                            'CostQuad' => $Quad_Sharing,
                            'CostQuint' => $Quint_Sharing,
                            'CostHexa' => $Hexa_Sharing
                        );
                        $this->_crmcustomertravelPlanRate->addCustomerTravelPlanRate($travelpriceArray);

                        $roomwisepricing = isset($postData['op' . $optionKey . 'roomwisepricing']) ? $postData['op' . $optionKey . 'roomwisepricing'] : array();

                        if (!empty($roomwisepricing) && $IsHotelOnlyPackage == 1 && trim($postData['SelectPricing']) == 'RoomWise') {
                            foreach ($roomwisepricing as $rpkey => $rpvalue) {
                                $Adults = isset($roomjsonArr[$rpkey + 1]['Adult']) ? (int) $roomjsonArr[$rpkey + 1]['Adult'] : 0;
                                $Childs = isset($roomjsonArr[$rpkey + 1]['Child']) ? (int) $roomjsonArr[$rpkey + 1]['Child'] : 0;
                                $Infant = isset($roomjsonArr[$rpkey + 1]['Infant']) ? (int) $roomjsonArr[$rpkey + 1]['Infant'] : 0;
                                $extrabed = $withoutbed = 0;
                                if (isset($roomjsonArr[$rpkey + 1]['AdultBedType']) && trim($roomjsonArr[$rpkey + 1]['AdultBedType']) == 'extrabed') {
                                    $extrabed++;
                                }
                                if (trim($roomjsonArr[$rpkey + 1]['ChildBedType_1']) == 'extrabed') {
                                    $extrabed++;
                                }
                                if (trim($roomjsonArr[$rpkey + 1]['ChildBedType_2']) == 'extrabed') {
                                    $extrabed++;
                                }

                                if (isset($roomjsonArr[$rpkey + 1]['AdultBedType']) && trim($roomjsonArr[$rpkey + 1]['AdultBedType']) == 'withoutbed') {
                                    $withoutbed++;
                                }
                                if (trim($roomjsonArr[$rpkey + 1]['ChildBedType_1']) == 'withoutbed') {
                                    $withoutbed++;
                                }
                                if (trim($roomjsonArr[$rpkey + 1]['ChildBedType_2']) == 'withoutbed') {
                                    $withoutbed++;
                                }

                                $roomNameqw = isset($postData["room"][$optionKey . '_1']) ? trim($postData["room"][$optionKey . '_1']) : '';
                                $RoomWiseData = array(
                                    'RoomName' => $roomNameqw,
                                    'RoomOrder' => $rpkey + 1,
                                    'NoOfNight' => (int) $noOfNights,
                                    'Adult' => $Adults,
                                    'Child' => $Childs,
                                    'Infant' => $Infant,
                                    'ExtraBed' => $extrabed,
                                    'ExtraWithoutBed' => $withoutbed,
                                    'Cost' => (float) $rpvalue,
                                    'TotalCost' => (float) $rpvalue * (int) $noOfNights,
                                    'CreatedDate' => $currentDate,
                                    'UpdatedDate' => $currentDate,
                                    'IsActive' => 1,
                                    'IsMarkForDelete' => 0,
                                    'CurrencyType' => isset($CurrencyType) ? $CurrencyType : 1,
                                    'TPRateSheetSysId' => $travelitenramarketwsierate,
                                    'TPSysId' => $tpproposalID,
                                );
                                $objPackage->insertData('TB_Agency_Customer_TravelPlan_RoomWise_Market_Rate', $RoomWiseData);
                            }
                        }
                    }
                    $sequence = 1;
                    if ($postData['PackageType'] == 'Quick') {
                        foreach ($destinationArray as $key => $destination) {
                            $hid = 0;
                            $checkN = 0;
                            $IshotelSelf = isset($postData['IshotelSelf'][$optionKey][$key]) ? 0 : 1;
                            $noofnightHotel = isset($postData['noofnight']) ? (int) $postData['noofnight'][$optionKey][$key] : 0;
                            $maxSequence = $noofnightHotel + (int) $sequence;
                            $explodeFromDateIti = explode('/', $postData['CheckIn'][$optionKey][$key]);
                            $fromdateiti = $explodeFromDateIti[2] . '-' . $explodeFromDateIti[1] . '-' . $explodeFromDateIti[0];
                            $todateiti = date('Y-m-d', strtotime($fromdateiti . " + $noofnightHotel days"));
                            for ($i = $sequence; $i <= $maxSequence; $i++) {
                                $travelitenaryarray = array(
                                    'TPSysId' => $tpproposalID,
                                    'Sequence' => $i,
                                    'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                    'Title' => isset($postData['daywiseTitle'][$i]) ? $postData['daywiseTitle'][$i] : '',
                                    'Details' => isset($postData['daywiseDescriptions'][$i]) ? $postData['daywiseDescriptions'][$i] : '',
                                    'InclMask' => !empty($inclmask) ? $inclmask : 0,
                                    'ExclusionMask' => $travelplandata[0]['ExclusionMask'],
                                    'InclCatMask' => $travelplandata[0]['InclCatMask'],
                                    'PackTypeMask' => $travelplandata[0]['PackTypeMask'],
                                    'InclCatMask' => $travelplandata[0]['InclCatMask'],
                                    'ImageTN' => 0,
                                    'ImgForList' => 0,
                                    'ImgeDetails' => 0,
                                    'Rating' => 0,
                                    'TotalMinDays' => (int) $sequence,
                                    'TotalMaxDays' => (int) $maxSequence,
                                    'Hotels' => $IshotelSelf,
                                    'PopularPlaces' => 0,
                                    'CitySysId' => $postData['hidden_destination_id'][$optionKey][$key],
                                    'Cities' => $postData['hidden_destination_withoutcountry'][$optionKey][$key],
                                    'Countries' => $postData['hidden_country_id'][$optionKey][$key],
                                    'IsMarkForDel' => 0,
                                    'IsActive' => 1,
                                    'MealPlanInclude' => (isset($postData['MealPlanInclude'][$i]) && !empty($postData['MealPlanInclude'][$i])) ? implode(',', $postData['MealPlanInclude'][$i]) : '',
                                    'StartDate' => !empty($postData['CheckIn'][$optionKey][$key]) ? $fromdateiti : '',
                                    'EndDate' => $todateiti,
                                );
                                $destination_cities_arr[] = $destination;
                                $lasttravelitenaryID = $this->_crmcustomertravelItenary->addCustomerTravelItenary($travelitenaryarray);
                                $tpitenrayplacesArray = array(
                                    'TPSysId' => $tpproposalID,
                                    'TPIntSysId' => $lasttravelitenaryID,
                                    'Sequence' => $i,
                                    'PlaceSysId' => $postData['hidden_destination_id'][$optionKey][$key],
                                    'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                    'IsMarkForDel' => 0,
                                    'IsActive' => 1,
                                );
                                $travelitenrayplaces = $this->_crmcustomertravelItenaryPlaces->addCustomerTravelItenaryPlaces($tpitenrayplacesArray);
                                $hid = isset($postData['hidden_selected_hotel_id'][$optionKey][$key]) ? (int) $postData['hidden_selected_hotel_id'][$optionKey][$key] : 0;
                                $similar_hotel = isset($postData['similar_hotel'][$optionKey][$key]) ? (int) $postData['similar_hotel'][$optionKey][$key] : 0;
                                $htitle = isset($postData['hotel_name'][$optionKey][$key]) ? $postData['hotel_name'][$optionKey][$key] : '';
                                if (empty($hid)) {
                                    $htitle_check = trim(str_replace(['(Internal)', 'Internal'], '', trim($htitle)));
                                    $HotelArray = $objPackage->getHotelbynameAndCityId($htitle_check, (int) $postData['hidden_destination_id'][$optionKey][$key]);
                                    if (empty($HotelArray)) {
                                        $newAccomodation = array(
                                            'IsAgentSpec' => '1',
                                            'ICSourceSysId' => $travelplandata[0]['AgencySysId'],
                                            'Title' => isset($htitle) ? trim($htitle) : '',
                                            'AliasAndMeta' => '',
                                            'ShortName' => '',
                                            'PlaceSysId_XRef' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? trim($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                            'Icon' => '',
                                            'ThumnailImg' => '',
                                            'DetailImg' => '',
                                            'Stars' => '0',
                                            'Rating' => '0',
                                            'Popularity' => '0',
                                            'AwardRecognizations' => '',
                                            'PropertyType' => '0',
                                            'EconomyType' => '0',
                                            'AccoAminitiesMask' => '',
                                            'MaxPaxCount' => '0',
                                            'RoomCounts' => '0',
                                            'Brief' => '',
                                            'CheckinTime' => '',
                                            'CheckOutTime' => '',
                                            'IsDayLightApp' => '',
                                            'GeoLat' => '0',
                                            'GeoLong' => '0',
                                            'Address' => '',
                                            'PinCode' => '0',
                                            'CitySysId' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? trim($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                            'ZoneSysId' => '0',
                                            'ZoneType' => '0',
                                            'StateSysId' => '0',
                                            'ContSysId' => !empty($postData['hidden_country_id'][$optionKey][$key]) ? trim($postData['hidden_country_id'][$optionKey][$key]) : '0',
                                            'UpdateDate' => $currentDate,
                                            'ApproveDate' => '1900-01-01',
                                            'ApproveBy' => '0',
                                            'CreateDate' => $currentDate,
                                            'IsApproved' => '0',
                                            'IsActive' => '1',
                                            'IsMarkForDel' => '0',
                                        );
                                        $objHotel = new Travel_Model_TblHotel();
                                        $hid = $intLastInsertId = $objHotel->addAccomodation($newAccomodation, $hotel_chain = '1');
                                    } else { // this case occurs when same hotel added on next day
                                        $hid = $HotelArray['AccomSysId'];
                                    }
                                }

                                $explodeFromDate = explode('/', $postData['CheckIn'][$optionKey][$key]);
                                $fromdate = $explodeFromDate[2] . '-' . $explodeFromDate[1] . '-' . $explodeFromDate[0];
                                $todate = date('Y-m-d', strtotime($fromdate . " + $noofnightHotel days"));
                                if ($hid > 0) {
                                    $HotelTotalPax = $totaltraveller + $totalInfant;
                                    if ($htitle != "") {
                                        $HotelDetailsArray = $objPackage->GetInventoryHotelBYO(trim($hid));
                                        $roomType = isset($postData["roomtype"][$optionKey . '_' . $key]) ? (int) $postData["roomtype"][$optionKey . '_' . $key] : 0;
                                        $roomName = isset($postData["room"][$optionKey . '_' . $key]) ? trim($postData["room"][$optionKey . '_' . $key]) : '';
                                        if (empty($roomType)) {
                                            $quickRoom = explode("~", $roomName);
                                            if (is_array($quickRoom) && count($quickRoom) > 1) {
                                                $roomType = isset($quickRoom[0]) ? (int) $quickRoom[0] : 0;
                                                $roomName = isset($quickRoom[1]) ? trim($quickRoom[1]) : '';
                                            }
                                        }
                                        $mealType = isset($postData["meal_type_" . $optionKey . "_" . $key]) ? (int) $postData["meal_type_" . $optionKey . "_" . $key] : 0; //[$key];
                                        $HotelCostTotal = isset($postData['HotelCostTotal'][$optionKey][$key]) ? (float) $postData['HotelCostTotal'][$optionKey][$key] : 0;
                                        $HotelTax = isset($postData['HotelTax'][$optionKey][$key]) ? (int) $postData['HotelTax'][$optionKey][$key] : 0;
                                        $HotelTaxTotal = isset($postData['HotelTaxTotal'][$optionKey][$key]) ? (int) $postData['HotelTaxTotal'][$optionKey][$key] : 0;
                                        $HotelCostFinal = isset($postData['HotelCostFinal'][$optionKey][$key]) ? (float) $postData['HotelCostFinal'][$optionKey][$key] : 0;
                                        $HotelMarkupTotal = isset($postData['HotelMarkupTotal'][$optionKey][$key]) ? (float) $postData['HotelMarkupTotal'][$optionKey][$key] : 0;
                                        if ($HotelCostFinal == 0) {
                                            $HotelCostFinal = $HotelCostTotal + $HotelMarkupTotal;
                                        }
                                        $GSTAmountHotel = 0;
                                        if ($arrGSTCalculations['TaxType'] == 1) {
                                            $GSTAmountHotel = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($HotelCostFinal, $arrGSTCalculations['TaxRate']);
                                        }
                                        if ($arrGSTCalculations['TaxType'] == 2) {
                                            $GSTAmountHotel = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($HotelMarkupTotal, $arrGSTCalculations['TaxRate']);
                                        }
                                        $HotelCostCurrency = isset($postData['HotelCostCurrency'][$optionKey][$key]) ? (int) $postData['HotelCostCurrency'][$optionKey][$key] : $CurrencyType;
                                        $ConversionRate = 1;
                                        if($HotelCostCurrency != $CurrencyType){
                                            $ConversionRate = isset($getMultipleConvertionRate[$HotelCostCurrency.'-'.$CurrencyType]['Rate']) ? (float)$getMultipleConvertionRate[$HotelCostCurrency.'-'.$CurrencyType]['Rate'] : 1;
                                        } 
                                        $travelitenaryaccomArray = array(
                                            'InvnItemSysId' => '0',
                                            'XrefInvtSysId' => '0',
                                            'SourceSysId' => (isset($postData['hotelType'][$optionKey][$key]) && !empty($postData['hotelType'][$optionKey][$key])) ? 1 : 0,
                                            'TPIntSysId' => $lasttravelitenaryID,
                                            'SupplierSysId' => (isset($postData['HotelCostSupplierId'][$optionKey][$key]) && !empty($postData['HotelCostSupplierId'][$optionKey][$key])) ? (int) $postData['HotelCostSupplierId'][$optionKey][$key] : (int) $SupplierSysId,
                                            'SeqId' => $i,
                                            'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                            'AccoSysId' => (int) $hid,
                                            'Title' => isset($htitle) ? $htitle : '',
                                            'RoomType' => !empty($roomType) ? trim($roomType) : '0',
                                            'RoomTypeStr' => !empty($roomName) ? substr(trim($roomName), 0, 50) : '',
                                            'MealPlanType' => !empty($mealType) ? trim($mealType) : '0',
                                            'RoomNumber' => '0',
                                            'CheckInTime' => '00:00:00',
                                            'CheckOutTime' => '00:00:00',
                                            'XRefCityId' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? trim($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                            'FromDate' => !empty($postData['CheckIn'][$optionKey][$key]) ? $fromdate : '',
                                            'ToDate' => $todate,
                                            'TotalNights' => $noofnightHotel,
                                            'TotalPax' => $HotelTotalPax ? $HotelTotalPax : '0',
                                            'StarRating' => ($HotelDetailsArray[0]['Stars'] > 0) ? (int) $HotelDetailsArray[0]['Stars'] : 0,
                                            'TotalCostGen' => '0',
                                            'TotalCostSO' => isset($postData['HotelCostSO'][$optionKey][$key]) ? (float) $postData['HotelCostSO'][$optionKey][$key] : 0,
                                            'TotalCostDO' => isset($postData['HotelCostDO'][$optionKey][$key]) ? (float) $postData['HotelCostDO'][$optionKey][$key] : 0,
                                            'TotalCostTO' => isset($postData['HotelCostEB'][$optionKey][$key]) ? (float) $postData['HotelCostEB'][$optionKey][$key] : 0,
                                            'TotalCostExtraBed' => isset($postData['HotelCostCWB'][$optionKey][$key]) ? (float) $postData['HotelCostCWB'][$optionKey][$key] : 0,
                                            'TotalCostWithoutBed' => isset($postData['HotelCostCWOB'][$optionKey][$key]) ? (float) $postData['HotelCostCWOB'][$optionKey][$key] : 0,
                                            'TotalCostInfant' => isset($postData['HotelCostInfant'][$optionKey][$key]) ? (float) $postData['HotelCostInfant'][$optionKey][$key] : 0,
                                            'Discounts' => '0',
                                            'TaxPercent' => $HotelTax,
                                            'Taxes' => $HotelTaxTotal,
                                            'CurrencyType' => $HotelCostCurrency,
                                            'IsSelectedOnPkg' => 1,
                                            'CreateDate' => $currentDate,
                                            'UpdateDate' => $currentDate,
                                            'IsMarkForDel' => '0',
                                            'IsActive' => '1',
                                            'TotalCost' => $HotelCostTotal,
                                            'Discounts' => 0,
                                            'NetCost' => $HotelCostFinal,
                                            'XServiceTaxAmount' => $GSTAmountHotel,
                                            'GTXServiceTaxAmount' => 0,
                                            'AgentServiceTaxAmount' => 0,
                                            'AgentsCustomServiceTaxAmount' => 0,
                                            'MarkUp' => $HotelMarkupTotal,
                                            'GTXMarkup' => 0,
                                            'AgencyMarkUp' => 0,
                                            'AccoSimilarHotel' => $similar_hotel,
                                            'CostQuad' => isset($postData['HotelQuadCostAdult'][$optionKey][$key]) ? (float) $postData['HotelQuadCostAdult'][$optionKey][$key] : 0,
                                            'CostQuint' => isset($postData['HotelQuintCostAdult'][$optionKey][$key]) ? (float) $postData['HotelQuintCostAdult'][$optionKey][$key] : 0,
                                            'CostHexa' => isset($postData['HotelHexaCostAdult'][$optionKey][$key]) ? (float) $postData['HotelHexaCostAdult'][$optionKey][$key] : 0,
                                            'AdultPax' => $totaladult ? (int) $totaladult - $Adultextrabed : 0,
                                            'ChildPax' => $Childextrabed ? $Childextrabed : 0,
                                            'InfantPax' => $totalInfant ? $totalInfant : 0,
                                            'ExtraAdult' => $Adultextrabed,
                                            'ChildNoBed' => $Childwithoutbed,
                                            'NoOfRoom' => is_array($roomjsonArr) ? count($roomjsonArr) : null,
                                            'SingleOAdult' => $SingleOAdult,
                                            'SCurrencyType' => isset($CurrencyType) ? $CurrencyType : 0,
                                            'ConversionRate' => $ConversionRate,
                                        );
                                        
                                        if (($travelplandata[0]['AgencySysId'] == 2656 || $travelplandata[0]['AgencySysId'] == 21) || date('Y-m-d') >= '2025-06-25') {
                                            $AccoSysId = $travelitenaryaccomArray['AccoSysId'];
                                            $AgencySysId = $travelitenaryaccomArray['AgencySysId'];
                                            $FromDate = $travelitenaryaccomArray['FromDate'];
                                            $ToDate = $travelitenaryaccomArray['ToDate'];
                                            $XRefCityId = $travelitenaryaccomArray['XRefCityId'];
                                            $RoomType = $travelitenaryaccomArray['RoomType'];
                                            $RoomTypeStr = $travelitenaryaccomArray['RoomTypeStr'];
                                            $MealPlanType = $travelitenaryaccomArray['MealPlanType'];
                                            $checkHotelData = $this->_crmcusttravelplanItenaryAccom->checkHotelDetailsInAccom($tpproposalID, $AccoSysId, $AgencySysId, $FromDate, $ToDate, $XRefCityId, $RoomType, $RoomTypeStr, $MealPlanType);
                                            if (empty($checkHotelData)) {
                                                $tplanitenaryaccomdataID = $this->_crmcusttravelplanItenaryAccom->addCustomerTravelPlanAccom($travelitenaryaccomArray);
                                                $PromotionType = isset($postData["promotion_type_" . $optionKey . "_" . $key]) ? trim($postData["promotion_type_" . $optionKey . "_" . $key]) : '';
                                                if (isset($PromotionType) && !empty($PromotionType) && $checkN == 0) {
                                                    $PromotionDetails = isset($postData['promotionDetail'][$PromotionType]) ? json_decode(base64_decode($postData['promotionDetail'][$PromotionType]), 1) : '';
                                                    $promotionsData[] = array(
                                                        'InvnSysId' => $tplanitenaryaccomdataID,
                                                        'PromotionTitle' => isset($PromotionDetails['PromotionName']) ? trim($PromotionDetails['PromotionName']) : '',
                                                        'PromotionCode' => isset($PromotionDetails['PromotionCode']) ? trim($PromotionDetails['PromotionCode']) : '',
                                                        'Comment' => '',
                                                        'PromotionType' => isset($PromotionDetails['PromotionType']) ? (int) $PromotionDetails['PromotionType'] : 0,
                                                        'PromotionValue' => isset($PromotionDetails['PromotionValue']) ? (int) $PromotionDetails['PromotionValue'] : 0,
                                                        'PromotionSysId' => isset($PromotionDetails['AccomPromotionsSysId']) ? (int) $PromotionDetails['AccomPromotionsSysId'] : 0,
                                                    );
                                                }
                                            }
                                        } else {
                                            $tplanitenaryaccomdataID = $this->_crmcusttravelplanItenaryAccom->addCustomerTravelPlanAccom($travelitenaryaccomArray);
                                            $PromotionType = isset($postData["promotion_type_" . $optionKey . "_" . $key]) ? trim($postData["promotion_type_" . $optionKey . "_" . $key]) : '';
                                            if (isset($PromotionType) && !empty($PromotionType) && $checkN == 0) {
                                                $PromotionDetails = isset($postData['promotionDetail'][$PromotionType]) ? json_decode(base64_decode($postData['promotionDetail'][$PromotionType]), 1) : '';
                                                $promotionsData[] = array(
                                                    'InvnSysId' => $tplanitenaryaccomdataID,
                                                    'PromotionTitle' => isset($PromotionDetails['PromotionName']) ? trim($PromotionDetails['PromotionName']) : '',
                                                    'PromotionCode' => isset($PromotionDetails['PromotionCode']) ? trim($PromotionDetails['PromotionCode']) : '',
                                                    'Comment' => '',
                                                    'PromotionType' => isset($PromotionDetails['PromotionType']) ? (int) $PromotionDetails['PromotionType'] : 0,
                                                    'PromotionValue' => isset($PromotionDetails['PromotionValue']) ? (int) $PromotionDetails['PromotionValue'] : 0,
                                                    'PromotionSysId' => isset($PromotionDetails['AccomPromotionsSysId']) ? (int) $PromotionDetails['AccomPromotionsSysId'] : 0,
                                                );
                                            }
                                        }
                                        $HotelVoucherStatus = 1;
                                    }
                                }

                                if ($IsDayWiseItinerary == 1 && ($i < $maxSequence || (count($destinationArray) == $key))) {
                                    $daywiseSightseeing = (isset($postData['daywiseSightseeing'][$i]) && !in_array($i, $checkDuplicateSightseeingSeq)) ? $postData['daywiseSightseeing'][$i] : array();
                                    //                                    echo "<pre>";print_r($postData);die;

                                    foreach ($daywiseSightseeing as $ssKey => $ssVal) {
                                        $daywiseSightseeingArray = explode('__', $ssVal);
                                        $sstid = $daywiseSightseeingArray[0];
                                        $sstitle = $daywiseSightseeingArray[1];
                                        $sscity = isset($daywiseSightseeingArray[2]) ? (int) $daywiseSightseeingArray[2] : 0;
                                        if (empty($sstitle)) {
                                            $SCityId = !empty($postData['hidden_destination_id'][$optionKey][$key]) ? trim($postData['hidden_destination_id'][$optionKey][$key]) : '0';
                                            $SightArray = $objPackage->getSightbyname(trim($daywiseSightseeingArray[0]), $SCityId, $this->intLoggedinUserAgencySysId);
                                            if (empty($SightArray)) {
                                                $insertss = array(
                                                    'IsAgentSpec' => '1',
                                                    'AgentSysId' => $this->intLoggedinUserId,
                                                    'ICSourceSysId' => $this->intLoggedinUserAgencySysId,
                                                    'StartPlaceSysId' => '0',
                                                    'EndPlaceSysId' => '0',
                                                    'Title' => trim($daywiseSightseeingArray[0]),
                                                    'synonyms' => '0',
                                                    'WriteUp' => '',
                                                    'DifficultyLevel' => '0',
                                                    'AliasAndMeta' => '0',
                                                    'SSGrType' => '0',
                                                    'SSType' => '0',
                                                    'SSIncMask' => '0',
                                                    'DurationInMin' => '0',
                                                    'DurationStr' => '0',
                                                    'Icon' => '',
                                                    'ThumnailImg' => '0',
                                                    'DetailImg' => '0',
                                                    'MinPax' => '0',
                                                    'MaxPax' => '0',
                                                    'PeakMothMask' => '0',
                                                    'LeanMonthMask' => '0',
                                                    'SilentMonthMask' => '0',
                                                    'IsTransferInc' => '0',
                                                    'IsKidAllowed' => '0',
                                                    'IsTeenAllowed' => '0',
                                                    'IsAdultAllowed' => '0',
                                                    'IsPetAllowed' => '0',
                                                    'IsTrxAllowed' => '0',
                                                    'IsPickAllowed' => '0',
                                                    'StartAgeYr' => '0',
                                                    'EndAgeYr' => '0',
                                                    'Rating' => '0',
                                                    'Popularity' => '0',
                                                    'ThingsToCarry' => '0',
                                                    'AwardRecognizations' => '0',
                                                    'BookingType' => '0',
                                                    'DifficultyType' => '0',
                                                    'DaysWeekMask' => '0',
                                                    'StartLocalTime' => '',
                                                    'EndLocalTime' => '',
                                                    'TimeSlots' => '0',
                                                    'IsDayLightApp' => '0',
                                                    'Address' => '',
                                                    'latitude' => '0',
                                                    'longitude' => '0',
                                                    'PinCode' => '0',
                                                    'CitySysId' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? trim($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                                    'ZoneSysId' => '0',
                                                    'ZoneType' => '0',
                                                    'StateSysId' => '0',
                                                    'ContSysId' => !empty($postData['hidden_country_id'][$optionKey][$key]) ? trim($postData['hidden_country_id'][$optionKey][$key]) : '0',
                                                    'PickUpLocation' => '0',
                                                    'PrimaryContact' => '0',
                                                    'SecondaryContact' => '0',
                                                    'OtherContacts' => '0',
                                                    'UpdateDate' => $currentDate,
                                                    'ApproveDate' => '1900-01-01',
                                                    'ApproveBy' => '0',
                                                    'CreateDate' => $currentDate,
                                                    'IsApproved' => '0',
                                                    'IsActive' => '1',
                                                    'IsMarkForDel' => '0'
                                                );
                                                $intLastInsertIdSS = $objSightseeing->addSightseeingDetails($insertss);
                                                $sstid = $intLastInsertIdSS;
                                                $sstitle = trim($daywiseSightseeingArray[0]);
                                            } else {
                                                $sstid = $SightArray['SSSysId'];
                                                $sstitle = trim($daywiseSightseeingArray[0]);
                                            }
                                        }

                                        $tpitenraysightseeingArray = array(
                                            'InvnItemSysId' => $lasttravelitenaryID,
                                            'SupplierSysId' => (int) $SupplierSysId,
                                            'XrefInvnItemSysId' => '0',
                                            'SeqId' => $i,
                                            'CityId' => ($sscity > 0) ? $sscity : (!empty($postData['hidden_destination_id'][$optionKey][$key]) ? (int) $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][$key]) : '0'),
                                            'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                            'SSSysId' => isset($sstid) ? (int) $sstid : 0,
                                            'Title' => isset($sstitle) ? $sstitle : '',
                                            'Type' => 'Included',
                                            'FromDate' => !empty($postData['CheckIn'][$optionKey][$key]) ? $fromdate : '',
                                            'ToDate' => $main_trip_end_date,
                                            'BookingType' => '0',
                                            'Qty' => '0',
                                            'IfAnyOffer' => '0',
                                            'OfferMsg' => '0',
                                            'OfferImage' => '0',
                                            'IxFixedDateInven' => '0',
                                            'CreateDate' => $currentDate,
                                            'UpdateDate' => $currentDate,
                                            'IsMarkForDelete' => '0',
                                            'IsActive' => '1',
                                            'RoomInfoJson' => '',
                                            'Cost' => 0,
                                            'KidsCost' => 0,
                                        );
                                        //echo "<pre>";print_r($tpitenraysightseeingArray);die;
                                        $travelitenraysightssing = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenraysightseeingArray);
                                        $SightseeingVoucherStatus = 1;
                                    }

                                    /* Paid Sightseeing Start */
                                    $SightseeingVehicleArray = array();
                                    $paidSightseeing = (isset($postData['sightseeingDW'][$i]) && !in_array($i, $checkDuplicateSightseeingSeq)) ? $postData['sightseeingDW'][$i] : array();
                                    $plusday = $i - 1;

                                    $start_date = date('Y-m-d', strtotime($main_trip_start_date . " + $plusday days"));
                                    if (!empty($paidSightseeing)) {

                                        foreach ($paidSightseeing as $psKey => $psValue) {
                                            if (!empty($psValue)) {
                                                $GetValue = explode("__", $psValue);
                                                $SightId = isset($GetValue[0]) ? (int) $GetValue[0] : 0;
                                                $SightTitle = $GetValue[1];
                                                $SightCity = isset($GetValue[2]) ? (int) $GetValue[2] : 0;
                                                if ($SightId > 0) {
                                                    $sightseeingTime = (isset($postData['time'][$i][$psKey]) && !empty($postData['time'][$i][$psKey])) ? trim($postData['time'][$i][$psKey]) : '';

                                                    $sightseeingpaxType = isset($postData['paxType'][$i][$psKey]) ? (int) $postData['paxType'][$i][$psKey] : 0;
                                                    $sightseeingpaxTypeChild = isset($postData['paxTypeChild'][$i][$psKey]) ? (int) $postData['paxTypeChild'][$i][$psKey] : 0;

                                                    $sightseeingTotalAdultCost = (isset($postData['sightseeingAdultCost'][$i][$psKey]) && $sightseeingpaxType > 0) ? (int) $postData['sightseeingAdultCost'][$i][$psKey] * $sightseeingpaxType : 0;
                                                    $sightseeingTotalChildCostTotal = (isset($postData['sightseeingChildCost'][$i][$psKey]) && $sightseeingpaxTypeChild > 0) ? (int) $postData['sightseeingChildCost'][$i][$psKey] * $sightseeingpaxTypeChild : 0;
                                                    $sightseeingTotalAdultMarkup = (isset($postData['sightseeingAdultMarkup'][$i][$psKey]) && $sightseeingpaxType > 0) ? (int) $postData['sightseeingAdultMarkup'][$i][$psKey] * $sightseeingpaxType : 0;
                                                    $sightseeingTotalChildMarkup = (isset($postData['sightseeingChildMarkup'][$i][$psKey]) && $sightseeingpaxTypeChild > 0) ? (int) $postData['sightseeingChildMarkup'][$i][$psKey] * $sightseeingpaxTypeChild : 0;

                                                    $sightseeingCost = $sightseeingTotalAdultCost + $sightseeingTotalChildCostTotal;
                                                    $sightseeingMarkup = $sightseeingTotalAdultMarkup + $sightseeingTotalChildMarkup;

                                                    $PaidsightseeingArray = array(
                                                        'InvnItemSysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                        'SupplierSysId' => !empty($postData['paidSightSupplierId'][$i][$psKey]) ? (int) $this->_HtmlPurifier->filter($postData['paidSightSupplierId'][$i][$psKey]) : (int) $SupplierSysId,
                                                        'XrefInvnItemSysId' => '0',
                                                        'SeqId' => $i,
                                                        'CityId' => ($SightCity > 0) ? $SightCity : (!empty($postData['hidden_destination_id'][$optionKey][$key]) ? (int) $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][$key]) : '0'),
                                                        'AgencySysId' => $travelplandata[0]['AgencySysId'] ? $travelplandata[0]['AgencySysId'] : 0,
                                                        'SSSysId' => $SightId,
                                                        'Title' => $SightTitle,
                                                        'Type' => isset($postData['sightseeingType'][$i][$psKey + 1]) ? trim($postData['sightseeingType'][$i][$psKey + 1]) : 'Included',
                                                        'CurrencyType' => isset($postData['sightseeingCurrencyType'][$i][$psKey]) ? (int) $postData['sightseeingCurrencyType'][$i][$psKey] : 0,
                                                        'Cost' => $sightseeingCost,
                                                        'Markup' => $sightseeingMarkup,
                                                        'TotalCost' => (int) $postData['totalAmountSightseeing'][$i][$psKey],
                                                        'AdultCost' => !empty($postData['sightseeingAdultCost'][$i][$psKey]) ? (int) $postData['sightseeingAdultCost'][$i][$psKey] : 0,
                                                        'AdultMarkup' => !empty($postData['sightseeingAdultMarkup'][$i][$psKey]) ? (int) $postData['sightseeingAdultMarkup'][$i][$psKey] : 0,
                                                        'KidsCost' => !empty($postData['sightseeingChildCost'][$i][$psKey]) ? (int) $postData['sightseeingChildCost'][$i][$psKey] : 0,
                                                        'ChildMarkup' => !empty($postData['sightseeingChildMarkup'][$i][$psKey]) ? (int) $postData['sightseeingChildMarkup'][$i][$psKey] : 0,
                                                        'FromDate' => $start_date . ' ' . $sightseeingTime,
                                                        'ToDate' => $start_date . ' ' . $sightseeingTime,
                                                        'BookingType' => '0',
                                                        'PriceType' => (isset($postData['OptionalSightseeingType'][$i][$psKey]) && !empty($postData['OptionalSightseeingType'][$i][$psKey])) ? (int) $postData['OptionalSightseeingType'][$i][$psKey] : 1,
                                                        'Qty' => !empty($postData['sightseeingVehicleQty'][$i][$psKey]) ? (int) $postData['sightseeingVehicleQty'][$i][$psKey] : 1,
                                                        'IfAnyOffer' => '0',
                                                        'OfferMsg' => '0',
                                                        'OfferImage' => '0',
                                                        'IxFixedDateInven' => '0',
                                                        'CreateDate' => $currentDate,
                                                        'UpdateDate' => $currentDate,
                                                        'IsMarkForDelete' => '0',
                                                        'IsActive' => '1',
                                                        'AdultPax' => !empty($postData['paxType'][$i][$psKey]) ? (int) $postData['paxType'][$i][$psKey] : 0,
                                                        'ChildPax' => !empty($postData['paxTypeChild'][$i][$psKey]) ? (int) $postData['paxTypeChild'][$i][$psKey] : 0,
                                                    );

                                                    $SightseeingVersinId = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($PaidsightseeingArray);
                                                    if (isset($postData['RouteVechSysId'][$i][$psKey]) && !empty($postData['RouteVechSysId'][$i][$psKey])) {
                                                        $SightseeingVehicleArray[] = [
                                                            'XrefItemSysId' => $SightseeingVersinId,
                                                            'AgencySysId' => $travelplandata[0]['AgencySysId'] ? $travelplandata[0]['AgencySysId'] : 0,
                                                            'TPSysId' => $tpproposalID,
                                                            'TPIntSysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                            'SupplierSysId' => !empty($postData['SSVehicleSupplierId'][$i][$psKey]) ? (int) $this->_HtmlPurifier->filter($postData['SSVehicleSupplierId'][$i][$psKey]) : (int) $SupplierSysId,
                                                            'AreaSysId' => !empty($postData['AreaSysId'][$i][$psKey]) ? (int) ($postData['AreaSysId'][$i][$psKey]) : 0,
                                                            'VehicleTypeSysId' => !empty($postData['RouteVechSysId'][$i][$psKey]) ? (int) ($postData['RouteVechSysId'][$i][$psKey]) : 0,
                                                            'RouteVechSysId' => !empty($postData['RouteVechSysId'][$i][$psKey]) ? (int) ($postData['RouteVechSysId'][$i][$psKey]) : 0,
                                                            'FromPlace' => !empty($postData['SSAreaName'][$i][$psKey]) ? trim($postData['SSAreaName'][$i][$psKey]) : '',
                                                            'ToPlace' => ($SightTitle != '') ? trim($SightTitle) : 'Sightseeing Transfer',
                                                            'SourceCityId' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? (int) $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                                            'DestCityId' => !empty($postData['hidden_destination_id'][$optionKey][$key]) ? (int) $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][$key]) : '0',
                                                            'Type_Text' => !empty($postData['SSVehicleName'][$i][$psKey]) ? $this->_HtmlPurifier->filter($postData['SSVehicleName'][$i][$psKey]) : '',
                                                            'FromDate' => !empty($start_date) ? trim($start_date) : '',
                                                            'ToDate' => !empty($start_date) ? trim($start_date) : '',
                                                            'Capacity' => !empty($postData['SSVehicleCapacity'][$i][$psKey]) ? (int) ($postData['SSVehicleCapacity'][$i][$psKey]) : 0,
                                                            'VehicleQty' => (isset($postData['VehicleQty'][$i][$psKey])) ? (int) $postData['VehicleQty'][$i][$psKey] : 1,
                                                            'CurrencyType' => isset($postData['sightseeingCurrencyType'][$i][$psKey]) ? (int) $postData['sightseeingCurrencyType'][$i][$psKey] : 0,
                                                        ];

                                                        //                                                    echo "<pre>";print_r($SightseeingVehicleArray);die('heyy');
                                                    }

                                                    if (isset($postData['sightseeingType'][$i][$psKey + 1]) && trim($postData['sightseeingType'][$i][$psKey + 1]) == 'Optional') {
                                                        $travelitenaryservices = array(
                                                            'TPIntSysId' => $tpproposalID,
                                                            'OtherSrvSysId' => (int) $SightseeingVersinId,
                                                            'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                                            'SupplierSysId' => !empty($postData['paidSightSupplierId'][$i][$psKey]) ? (int) $this->_HtmlPurifier->filter($postData['paidSightSupplierId'][$i][$psKey]) : (int) $SupplierSysId,
                                                            'ServiceTitle' => $SightTitle,
                                                            'ServiceType' => 5,
                                                            'Comment' => '',
                                                            'CurrencyType' => isset($postData['sightseeingCurrencyType'][$i][$psKey]) ? (int) $postData['sightseeingCurrencyType'][$i][$psKey] : 0,
                                                            'RateType' => 1,
                                                            'PaxCount' => 1,
                                                            'Cost' => (int) $postData['sightseeingAdultCost'][$i][$psKey] + (int) $postData['sightseeingChildCost'][$i][$psKey],
                                                            'Markup' => (int) $postData['sightseeingAdultMarkup'][$i][$psKey] + (int) $postData['sightseeingChildMarkup'][$i][$psKey],
                                                            'TotalAdult' => (int) $totaladult,
                                                            'TotalChild' => (int) $totalchild,
                                                            'AdultCost' => !empty($postData['sightseeingAdultCost'][$i][$psKey]) ? (int) $postData['sightseeingAdultCost'][$i][$psKey] + (int) $postData['sightseeingAdultMarkup'][$i][$psKey] : 0,
                                                            'ChildCost' => !empty($postData['sightseeingChildCost'][$i][$psKey]) ? (int) $postData['sightseeingChildCost'][$i][$psKey] + (int) $postData['sightseeingChildMarkup'][$i][$psKey] : 0,
                                                            'IsOptionalServices' => 1,
                                                            'IsCostInclInTP' => 1, // for mendatory = 0
                                                            'CreateDate' => $currentDate,
                                                            'UpdateDate' => $currentDate,
                                                            'IsMarkForDelete' => 0,
                                                            'IsApproved' => 1,
                                                            'IsActive' => 1,
                                                            'ItenarySysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                        );
                                                        $lasttravelitenaryotherservices[] = $objPackage->insertData('TB_Agency_Customer_TravelPlan_OtherServices', $travelitenaryservices);
                                                        $OtherVoucherStatus = 1;
                                                    }
                                                }
                                            }
                                        }
                                        $SightseeingVoucherStatus = 1;
                                    }
                                    /* Paid Sightseeing End */
                                    /*  sightseeing vehicle start */
                                    if (!empty($SightseeingVehicleArray)) {
                                        foreach ($SightseeingVehicleArray as $svKey => $svValue) {
                                            $XrefItemSysIdS = $svValue['XrefItemSysId'] ? $svValue['XrefItemSysId'] : 0;
                                            if ($XrefItemSysIdS > 0) {
                                                $SSVehicledata = array(
                                                    'XrefItemSysId' => $svValue['XrefItemSysId'] ? $svValue['XrefItemSysId'] : 0,
                                                    'AgencySysId' => $svValue['AgencySysId'] ? $svValue['AgencySysId'] : 0,
                                                    'TPSysId' => $svValue['TPSysId'],
                                                    'TPIntSysId' => $svValue['TPIntSysId'] ? $svValue['TPIntSysId'] : 0,
                                                    'SupplierSysId' => !empty($svValue['SupplierSysId']) ? (int) $this->_HtmlPurifier->filter($svValue['SupplierSysId']) : (int) $SupplierSysId,
                                                    'Type' => 'Included',
                                                    'IsIncluded' => '1',
                                                    'VehSysId' => 0,
                                                    'VehicleTypeSysId' => !empty($svValue['VehicleTypeSysId']) ? (int) ($svValue['VehicleTypeSysId']) : 0,
                                                    'RouteSysId' => 0,
                                                    'RouteVechSysId' => !empty($svValue['RouteVechSysId']) ? (int) ($svValue['RouteVechSysId']) : 0,
                                                    'TransId' => 1,
                                                    'TransType' => ' ',
                                                    'TransTypeCat' => ' ',
                                                    'FromPlace' => trim($svValue['FromPlace']),
                                                    'ToPlace' => ($svValue['ToPlace'] != '') ? trim($svValue['ToPlace']) : 'Sightseeing Transfer',
                                                    'SourceCityId' => !empty($svValue['SourceCityId']) ? (int) $this->_HtmlPurifier->filter($svValue['SourceCityId']) : '0',
                                                    'DestCityId' => !empty($svValue['DestCityId']) ? (int) $this->_HtmlPurifier->filter($svValue['DestCityId']) : '0',
                                                    'Type_Text' => !empty($svValue['Type_Text']) ? $this->_HtmlPurifier->filter($postData['Type_Text']) : '',
                                                    'FromDate' => !empty($svValue['FromDate']) ? trim($svValue['FromDate']) : '',
                                                    'ToDate' => !empty($svValue['ToDate']) ? trim($svValue['ToDate']) : '',
                                                    'CostPerson' => 0,
                                                    'TotalPrice' => 0,
                                                    'TotalMarkup' => 0,
                                                    'NetCost' => 0,
                                                    'CurrencyType' => !empty($svValue['CurrencyType']) ? (int) $svValue['CurrencyType'] : 0,
                                                    'Capacity' => !empty($svValue['Capacity']) ? (int) ($svValue['Capacity']) : 0,
                                                    'CreateDate' => $currentDate,
                                                    'IsMarkForDel' => '0',
                                                    'Sequence' => $i,
                                                    'IsActive' => '1',
                                                    'VehicleQty' => (isset($svValue['VehicleQty'])) ? (int) $svValue['VehicleQty'] : 1,
                                                    'IsGroup' => 1,
                                                    'XRefVoucherNo' => 0,
                                                    'IsDisplay' => 1,
                                                    'TransportCategory' => 11,
                                                    'AreaSysId' => (isset($svValue['AreaSysId'])) ? (int) $svValue['AreaSysId'] : 0,
                                                );
                                                try {
                                                    $objPackage->insertData('TB_Agency_Customer_Trans_Fixed', $SSVehicledata);
                                                } catch (Zend_Exception $e) {
                                                    echo $e->getMessage();
                                                    die;
                                                }
                                                $TransferVoucherStatus = 1;
                                            }
                                        }
                                    }

                                    /* end sightseeing vehicle */

                                    /* Day wise transport start */
                                    $TransferIncludedSightseeingArray = array();
                                    $categoryTransportDW = (isset($postData['categoryTransportDW'][$i])) ? $postData['categoryTransportDW'][$i] : array();
                                    foreach ($categoryTransportDW as $dtKey => $dtValue) {
                                        $RouteSysIdDW = (isset($postData['RouteSysIdDW'][$i][$dtKey])) ? (int) $postData['RouteSysIdDW'][$i][$dtKey] : 0;
                                        $RouteVechSysIdDW = (isset($postData['RouteVechSysIdDW'][$i][$dtKey])) ? $postData['RouteVechSysIdDW'][$i][$dtKey] : '';
                                        if (!empty($dtValue) && !empty($RouteVechSysIdDW)) {
                                            $transportCurrencyTypeDW = (isset($postData['transportCurrencyTypeDW'][$i][$dtKey])) ? $postData['transportCurrencyTypeDW'][$i][$dtKey] : 0;
                                            $directNoOfCarDW = (isset($postData['directNoOfCarDW'][$i][$dtKey])) ? $postData['directNoOfCarDW'][$i][$dtKey] : 0;
                                            $capacityTransportDW = (isset($postData['capacityTransportDW'][$i][$dtKey])) ? $postData['capacityTransportDW'][$i][$dtKey] : 0;
                                            $transportVehicleCostDW = (isset($postData['transportVehicleCostDW'][$i][$dtKey])) ? $postData['transportVehicleCostDW'][$i][$dtKey] : 0;
                                            $transportVehicleMarkupDW = (isset($postData['transportVehicleMarkupDW'][$i][$dtKey])) ? $postData['transportVehicleMarkupDW'][$i][$dtKey] : 0;
                                            $transportSupplierNameDW = (isset($postData['transportSupplierNameDW'][$i][$dtKey])) ? $postData['transportSupplierNameDW'][$i][$dtKey] : 0;
                                            $transportSupplierIdDW = (isset($postData['transportSupplierIdDW'][$i][$dtKey])) ? $postData['transportSupplierIdDW'][$i][$dtKey] : (int) $SupplierSysId;
                                            $transportTotalCostDW = (isset($postData['transportTotalCostDW'][$i][$dtKey])) ? $postData['transportTotalCostDW'][$i][$dtKey] : 0;
                                            $transferTypeDW = (isset($postData['transferTypeDW'][$i][$dtKey])) ? (int) $postData['transferTypeDW'][$i][$dtKey] : 0;
                                            $pickupAreaDW = (isset($postData['pickupAreaDW'][$i][$dtKey])) ? $postData['pickupAreaDW'][$i][$dtKey] : '';
                                            $dropAreaDW = (isset($postData['dropAreaDW'][$i][$dtKey])) ? $postData['dropAreaDW'][$i][$dtKey] : '';
                                            $TransportSourceCityIdDW = (isset($postData['TransportSourceCityIdDW'][$i][$dtKey])) ? (int) $postData['TransportSourceCityIdDW'][$i][$dtKey] : 0;
                                            $TransportDestCityIdDW = (isset($postData['TransportDestCityIdDW'][$i][$dtKey])) ? (int) $postData['TransportDestCityIdDW'][$i][$dtKey] : 0;
                                            $TransportTotalNightDW = (isset($postData['TransportTotalNightDW'][$i][$dtKey])) ? (int) $postData['TransportTotalNightDW'][$i][$dtKey] : 0;
                                            $TransportTotalNightDWLess = ($TransportTotalNightDW > 0) ? $TransportTotalNightDW - 1 : 0;
                                            $RouteVechSysIdDWExplode = explode('__', $RouteVechSysIdDW);
                                            if (isset($RouteVechSysIdDWExplode[0]) && (!isset($RouteVechSysIdDWExplode[1]) || empty($RouteVechSysIdDWExplode[1]))) {
                                                $RouteVechSysIdDWExplode[1] = $RouteVechSysIdDWExplode[0];
                                                $RouteVechSysIdDWExplode[0] = 0;
                                            }
                                            $categoryTransportDWExplode = explode('_', $dtValue);
                                            if (isset($categoryTransportDWExplode[1])) {
                                                $dtValue = $categoryTransportDWExplode[1];
                                            }

                                            if ($i == 1 && $dtValue == 1 && $RouteSysIdDW == 0 && $RouteVechSysIdDWExplode[0] == 0 && $TransportTotalNightDW == 0) {
                                                $TransportTotalNightDWLess = $noOfNights;
                                            }
                                            $transport_end_date = date('Y-m-d', strtotime($start_date . " + $TransportTotalNightDWLess days"));

                                            $pickupAreaDWExplode = explode('__', $pickupAreaDW);
                                            $dropAreaDWExplode = explode('__', $dropAreaDW);
                                            $FromPlace = (isset($pickupAreaDWExplode[1])) ? $pickupAreaDWExplode[1] : ((isset($pickupAreaDWExplode[0])) ? $pickupAreaDWExplode[0] : '');
                                            $ToPlace = (isset($dropAreaDWExplode[1])) ? $dropAreaDWExplode[1] : ((isset($dropAreaDWExplode[0])) ? $dropAreaDWExplode[0] : '');
                                            $dataTransport = array(
                                                'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                                'TPSysId' => $tpproposalID,
                                                'TPIntSysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                'SupplierSysId' => $transportSupplierIdDW,
                                                'Type' => 'Included',
                                                'IsIncluded' => '1',
                                                'VehSysId' => isset($RouteVechSysIdDWExplode[0]) ? (int) $RouteVechSysIdDWExplode[0] : 0,
                                                'VehicleTypeSysId' => 0,
                                                'RouteSysId' => $RouteSysIdDW,
                                                'RouteVechSysId' => isset($RouteVechSysIdDWExplode[0]) ? (int) $RouteVechSysIdDWExplode[0] : 0,
                                                'TransId' => '1',
                                                'TransType' => ' ',
                                                'FromPlace' => $FromPlace,
                                                'ToPlace' => $ToPlace,
                                                'SourceCityId' => $TransportSourceCityIdDW,
                                                'DestCityId' => $TransportDestCityIdDW,
                                                'Type_Text' => isset($RouteVechSysIdDWExplode[1]) ? trim($RouteVechSysIdDWExplode[1]) : '',
                                                'FromDate' => $start_date,
                                                'ToDate' => $transport_end_date,
                                                'CostPerson' => 0,
                                                'CostChild' => 0,
                                                'TotalPrice' => (float) $transportVehicleCostDW,
                                                'TotalMarkup' => (float) $transportVehicleMarkupDW,
                                                'Taxes' => 0,
                                                'NetCost' => (float) $transportTotalCostDW,
                                                'AreaSysId' => 0,
                                                'CurrencyType' => $transportCurrencyTypeDW,
                                                'Capacity' => $capacityTransportDW,
                                                'CreateDate' => $currentDate,
                                                'IsMarkForDel' => '0',
                                                'Sequence' => $i,
                                                'IsActive' => '1',
                                                'VehicleQty' => !empty($directNoOfCarDW) ? (int) ($directNoOfCarDW) : 0,
                                                'IsGroup' => (isset($dtValue) && ($dtValue == 3)) ? 0 : 1,
                                                'XRefVoucherNo' => 0,
                                                'IsDisplay' => 1,
                                                'TransportCategory' => $dtValue,
                                                'TransTypeCat' => $transferTypeDW,
                                            );
                                            //echo"<pre>";print_r($dataTransport);die('dd');
                                            $FixTransSysId = $objPackage->insertData('TB_Agency_Customer_Trans_Fixed', $dataTransport);
                                            $TransferVoucherStatus = 1;
                                            if (isset($getTransferSightseeingRouteWise[$RouteSysIdDW]) && !empty($getTransferSightseeingRouteWise[$RouteSysIdDW])) {
                                                foreach ($getTransferSightseeingRouteWise[$RouteSysIdDW] as $incTSKey => $incTSValue) {
                                                    $incTSValue['SupplierSysId'] = $transportSupplierIdDW;
                                                    $incTSValue['FixTransSysId'] = $FixTransSysId;
                                                    $TransferIncludedSightseeingArray[] = $incTSValue;
                                                }
                                            }

                                            $TransferIncludedSightseeingFixTransSysId[$RouteSysIdDW]['FixTransSysId'] = $FixTransSysId;
                                            $TransferIncludedSightseeingFixTransSysId[$RouteSysIdDW]['SupplierSysId'] = $transportSupplierIdDW;
                                        }
                                    }
                                    //                                    echo "<pre>";print_r($getTransferSightseeingDayWise);die;
                                    if (isset($getTransferSightseeingDayWise[$i]) && !empty($getTransferSightseeingDayWise[$i])) {
                                        foreach ($getTransferSightseeingDayWise[$i] as $tincSKey => $tincValue) {
                                            $tpitenrayTsightseeingArray = array(
                                                'InvnItemSysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                'SupplierSysId' => (isset($TransferIncludedSightseeingFixTransSysId[$tincValue['RouteSysId']]['SupplierSysId']) && (int) $TransferIncludedSightseeingFixTransSysId[$tincValue['RouteSysId']]['SupplierSysId'] > 0) ? (int) $TransferIncludedSightseeingFixTransSysId[$tincValue['RouteSysId']]['SupplierSysId'] : (int) $SupplierSysId,
                                                'XrefInvnItemSysId' => 0,
                                                'XrefTransSysId' => (isset($TransferIncludedSightseeingFixTransSysId[$tincValue['RouteSysId']]['FixTransSysId'])) ? (int) $TransferIncludedSightseeingFixTransSysId[$tincValue['RouteSysId']]['FixTransSysId'] : 0,
                                                'SeqId' => $i,
                                                'CityId' => $tincValue['DestSysId'],
                                                'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                                'SSSysId' => (int) $tincValue['SSSysId'],
                                                'Title' => trim($tincValue['SightSeeingName']),
                                                'Type' => 'Included',
                                                'FromDate' => !empty($start_date) ? trim($start_date) : '',
                                                'ToDate' => !empty($start_date) ? trim($start_date) : '',
                                                'BookingType' => '0',
                                                'Qty' => '0',
                                                'IfAnyOffer' => '0',
                                                'OfferMsg' => '0',
                                                'OfferImage' => '0',
                                                'IxFixedDateInven' => '0',
                                                'CreateDate' => $currentDate,
                                                'UpdateDate' => $currentDate,
                                                'IsMarkForDelete' => '0',
                                                'IsActive' => '1',
                                                'RoomInfoJson' => '',
                                                'Cost' => 0,
                                                'KidsCost' => 0,
                                            );

                                            $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenrayTsightseeingArray);
                                            $SightseeingVoucherStatus = 1;
                                        }
                                    }
                                    if (!empty($TransferIncludedSightseeingArray)) {
                                        foreach ($TransferIncludedSightseeingArray as $tincSKey => $tincValue) {
                                            $tpitenrayTsightseeingArray = array(
                                                'InvnItemSysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                'SupplierSysId' => $tincValue['SupplierSysId'],
                                                'XrefInvnItemSysId' => 0,
                                                'XrefTransSysId' => (int) $tincValue['FixTransSysId'],
                                                'SeqId' => $i,
                                                'CityId' => $tincValue['DestSysId'],
                                                'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                                'SSSysId' => (int) $tincValue['SSSysId'],
                                                'Title' => trim($tincValue['SightSeeingName']),
                                                'Type' => 'Included',
                                                'FromDate' => !empty($start_date) ? trim($start_date) : '',
                                                'ToDate' => !empty($start_date) ? trim($start_date) : '',
                                                'BookingType' => '0',
                                                'Qty' => '0',
                                                'IfAnyOffer' => '0',
                                                'OfferMsg' => '0',
                                                'OfferImage' => '0',
                                                'IxFixedDateInven' => '0',
                                                'CreateDate' => $currentDate,
                                                'UpdateDate' => $currentDate,
                                                'IsMarkForDelete' => '0',
                                                'IsActive' => '1',
                                                'RoomInfoJson' => '',
                                                'Cost' => 0,
                                                'KidsCost' => 0,
                                            );
                                            //echo "<pre>";print_r($tpitenrayTsightseeingArray);die;
                                            $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenrayTsightseeingArray);
                                            $SightseeingVoucherStatus = 1;
                                        }
                                    }


                                    /* Day wise transport end */
                                    error_reporting(E_ALL);
                                    //                                    echo "<pre>";print_r($postData);die;
                                    /* Day wise Meal start */
                                    $ARR_MEAL_CATEGORY = unserialize(ARR_MEAL_CATEGORY);
                                    $ARR_MEAL_TYPE = unserialize(ARR_MEAL_TYPE);
                                    $mealsOptionsDW = (isset($postData['mealsOptionsDW'][$i])) ? $postData['mealsOptionsDW'][$i] : array();
                                    foreach ($mealsOptionsDW as $dmKey => $dmValue) {
                                        if (!empty($dmValue)) {
                                            $MealSupplierSysId = (isset($postData['mealsSupplierSysId'][$i][$dmKey])) ? $postData['mealsSupplierSysId'][$i][$dmKey] : 0;
                                            $mealsCategoryDW = (isset($postData['mealsCategoryDW'][$i][$dmKey])) ? $postData['mealsCategoryDW'][$i][$dmKey] : 0;
                                            $mealsCategoryHtml = (isset($ARR_MEAL_CATEGORY[$mealsCategoryDW])) ? $ARR_MEAL_CATEGORY[$mealsCategoryDW] : '';
                                            $mealsTypeDW = (isset($postData['mealsTypeDW'][$i][$dmKey])) ? $postData['mealsTypeDW'][$i][$dmKey] : 0;
                                            $mealsTypeHtml = (isset($ARR_MEAL_TYPE[$mealsTypeDW])) ? $ARR_MEAL_TYPE[$mealsTypeDW] : '';

                                            $mealsOptionsE = explode('~~', $dmValue);
                                            if (isset($mealsOptionsE[1])) {
                                                $CommentMeal = trim($mealsOptionsE[1]) . ' (' . $mealsTypeHtml . ')';
                                            } else {
                                                $CommentMeal = trim($mealsOptionsE[0]) . ' (' . $mealsTypeHtml . ')';
                                            }

                                            $saveMealData = array(
                                                'OtherSrvSysId' => (isset($mealsOptionsE[0])) ? (int) $mealsOptionsE[0] : 0,
                                                'TPIntSysId' => $tpproposalID,
                                                'ItenarySysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                                'CustomerSysId' => $travelplandata[0]['CustomerSysId'],
                                                'SupplierSysId' => !empty($MealSupplierSysId) ? (int) $MealSupplierSysId : 0,
                                                'ServiceTitle' => $mealsCategoryHtml,
                                                'ServiceType' => 41,
                                                'Comment' => trim($CommentMeal),
                                                'CurrencyType' => (isset($postData['mealsCurrencyTypeDW'][$i][$dmKey]) && !empty($postData['mealsCurrencyTypeDW'][$i][$dmKey])) ? $this->_HtmlPurifier->filter($postData['mealsCurrencyTypeDW'][$i][$dmKey]) : 0,
                                                'RateType' => 0,
                                                'PaxCount' => 0,
                                                'TotalItem' => 1,
                                                'Cost' => (isset($postData['mealsCost'][$i][$dmKey]) && !empty($postData['mealsCost'][$i][$dmKey])) ? $postData['mealsCost'][$i][$dmKey] : 0,
                                                'IsOptionalServices' => 0,
                                                'IsCostInclInTP' => 0,
                                                'IsActive' => '1',
                                                'IsMarkForDelete' => 0,
                                                'IsApproved' => '1',
                                                'CreateDate' => $currentDate,
                                                'UpdateDate' => $currentDate,
                                                'XRefVoucherNo' => 0,
                                                'IsIncludedInPackage' => 1,
                                                'IsSelected' => 1,
                                                'TotalItem' => 1,
                                                'TotalAdult' => 0,
                                                'TotalChild' => 0,
                                                'AdultCost' => 0,
                                                'ChildCost' => 0,
                                            );
                                            //                                            echo "<pre>";print_r($saveMealData);die;
                                            $updateId = $objPackage->insertData('TB_Agency_Customer_TravelPlan_OtherServices', $saveMealData);
                                        }
                                    }
                                    /* Day wise Meal end */




                                    $checkDuplicateSightseeingSeq[] = $i;

                                    $insertItDescArr = array();
                                    $objItineraryDescription = new Travel_Model_TblItineraryDescription();
                                    $startCityId_ = isset($postData['startCityId'][$i]) ? $postData['startCityId'][$i] : 0;
                                    $endCityId_ = isset($postData['endCityId'][$i]) ? $postData['endCityId'][$i] : 0;
                                    $saveasmaster = isset($postData['saveasmaster'][$i]) ? $postData['saveasmaster'][$i] : 0;
                                    $daywiseTitle = isset($postData['daywiseTitle'][$i]) ? $postData['daywiseTitle'][$i] : '';
                                    $daywiseDescriptions = isset($postData['daywiseDescriptions'][$i]) ? $postData['daywiseDescriptions'][$i] : '';
                                    if ($saveasmaster == 1 && (int) $startCityId_ != 0 && (int) $endCityId_ != 0 && trim($daywiseTitle) != '' && $daywiseDescriptions != '') {
                                        $insertItDescArr = array(
                                            'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                            'StartCity' => (int) $startCityId_,
                                            'DestinationCity' => (int) $endCityId_,
                                            'Title' => $daywiseTitle,
                                            'Description' => $daywiseDescriptions,
                                            'Iswebsite' => 0,
                                            'IsActive' => 1,
                                            'IsMarkForDel' => 0,
                                        );
                                        try {
                                            $ItineraryId = $objItineraryDescription->addItineraryDescription($insertItDescArr);
                                        } catch (Zend_Exception $e) {
                                            echo $e->getMessage();
                                            exit;
                                        }
                                    }
                                }
                                $checkN++;
                            }
                            $sequence = $maxSequence;

                            /*                             * ****************Activity****************************** */
                        }

                        /*                         * ****************Sightseen****************************** */
                        if (((isset($postData["sightseeing"]) && is_array($postData["sightseeing"])) || (isset($postData["sightseeingpvt"]) && is_array($postData["sightseeingpvt"]))) && $IsDayWiseItinerary == 0) {

                            for ($q = 0; $q < count($postData["sightseeing"]); $q++) {

                                $rdtarr1 = array();
                                $rdtarr1 = (isset($postData["sightseeing"][$q]) && !is_array($postData["sightseeing"][$q])) ? explode("__", $postData["sightseeing"][$q]) : '';
                                $sscity = isset($rdtarr1[2]) ? (int) $rdtarr1[2] : 0;
                                if (is_array($rdtarr1) && is_numeric($rdtarr1[0])) {
                                    $sstid = isset($rdtarr1[0]) ? (int) $rdtarr1[0] : 0;
                                    $sstitle = isset($rdtarr1[1]) ? $rdtarr1[1] : '';
                                } else {
                                    $SCityId = !empty($postData['hidden_destination_id'][$optionKey][1]) ? $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][1]) : '0';
                                    $SightArray = $objPackage->getSightbyname(trim($rdtarr1[0]), $SCityId, $this->intLoggedinUserAgencySysId);
                                    if (empty($SightArray)) {
                                        $insertss = array(
                                            'IsAgentSpec' => '1',
                                            'AgentSysId' => $agentsysID,
                                            'ICSourceSysId' => $travelplandata[0]['AgencySysId'],
                                            'StartPlaceSysId' => '0',
                                            'EndPlaceSysId' => '0',
                                            'Title' => isset($rdtarr1[0]) ? $rdtarr1[0] : '',
                                            'synonyms' => '0',
                                            'WriteUp' => '',
                                            'DifficultyLevel' => '0',
                                            'AliasAndMeta' => '0',
                                            'SSGrType' => '0',
                                            'SSType' => '0',
                                            'SSIncMask' => '0',
                                            'DurationInMin' => '0',
                                            'DurationStr' => '0',
                                            'Icon' => '',
                                            'ThumnailImg' => '0',
                                            'DetailImg' => '0',
                                            'MinPax' => '0',
                                            'MaxPax' => '0',
                                            'PeakMothMask' => '0',
                                            'LeanMonthMask' => '0',
                                            'SilentMonthMask' => '0',
                                            'IsTransferInc' => '0',
                                            'IsKidAllowed' => '0',
                                            'IsTeenAllowed' => '0',
                                            'IsAdultAllowed' => '0',
                                            'IsPetAllowed' => '0',
                                            'IsTrxAllowed' => '0',
                                            'IsPickAllowed' => '0',
                                            'StartAgeYr' => '0',
                                            'EndAgeYr' => '0',
                                            'Rating' => '0',
                                            'Popularity' => '0',
                                            'ThingsToCarry' => '0',
                                            'AwardRecognizations' => '0',
                                            'BookingType' => '0',
                                            'DifficultyType' => '0',
                                            'DaysWeekMask' => '0',
                                            'StartLocalTime' => '',
                                            'EndLocalTime' => '',
                                            'TimeSlots' => '0',
                                            'IsDayLightApp' => '0',
                                            'Address' => '',
                                            'latitude' => '0',
                                            'longitude' => '0',
                                            'PinCode' => '0',
                                            'CitySysId' => $SCityId,
                                            'ZoneSysId' => '0',
                                            'ZoneType' => '0',
                                            'StateSysId' => '0',
                                            'ContSysId' => !empty($postData['hidden_country_id'][$optionKey][1]) ? trim($postData['hidden_country_id'][$optionKey][1]) : '0',
                                            'PickUpLocation' => '0',
                                            'PrimaryContact' => '0',
                                            'SecondaryContact' => '0',
                                            'OtherContacts' => '0',
                                            'UpdateDate' => $currentDate,
                                            'ApproveDate' => '1900-01-01',
                                            'ApproveBy' => '0',
                                            'CreateDate' => $currentDate,
                                            'IsApproved' => '0',
                                            'IsActive' => '1',
                                            'IsMarkForDel' => '0'
                                        );
                                        //                                        echo "<pre>";print_r($postData);die;
                                        $objSightseeing = new Travel_Model_TblSightseeing();
                                        $intLastInsertId = $objSightseeing->addSightseeingDetails($insertss);
                                        $sstid = isset($intLastInsertId) ? $intLastInsertId : 0;
                                        $sstitle = isset($rdtarr1[0]) ? $rdtarr1[0] : '';
                                    } else {
                                        $sstid = $SightArray['SSSysId'];
                                        $sstitle = isset($rdtarr1[0]) ? $rdtarr1[0] : '';
                                    }
                                }
                                $RoomInfiJsonArr = array();
                                $RoomInfiJson = '';
                                $FromDate = $currentDate;
                                $Cost = 0;
                                $KidsCost = 0;
                                /* Code  By Mangal For Only Sightseeing Share 25/09/2019 Start */
                                if (isset($postData['onlySightseeing']) && $postData['onlySightseeing'] == 1) {
                                    $RoomInfiJsonArr = [
                                        'sightseeingDate' => $postData['sightseeingDate'][$q],
                                        'citySysId' => $postData['hidden_destination_id'][$optionKey][$q + 1],
                                        'cityName' => $postData['hidden_destination_withoutcountry'][$optionKey][$q + 1],
                                        'hidden_country_id' => $postData['hidden_country_id'][$optionKey][$q + 1],
                                        'sightseeingType' => $postData['sightseeingType'][$q],
                                        'perAdultPrice' => $postData['perAdultPrice'][$q],
                                        'noofAdults' => $postData['noofAdults'][$q],
                                        'adultPrice' => $postData['adultPrice'][$q],
                                        'perChildPrice' => $postData['perChildPrice'][$q],
                                        'noofChild' => $postData['noofChild'][$q],
                                        'childPrice' => $postData['childPrice'][$q],
                                        'MarkupPerAdultPrice' => $postData['MarkupPerAdultPrice'][$q],
                                        'MarkupPerChildPrice' => $postData['MarkupPerChildPrice'][$q],
                                    ];
                                    $sightseeingDate = explode('/', $postData['sightseeingDate'][$q]);
                                    $FromDate = $sightseeingDate[2] . '-' . $sightseeingDate[1] . '-' . $sightseeingDate[0];
                                    $Cost = $postData['perAdultPrice'][$q];
                                    $KidsCost = $postData['perChildPrice'][$q];
                                    $RoomInfiJson = json_encode($RoomInfiJsonArr);
                                }
                                /* Code  By Mangal For Only Sightseeing Share 25/09/2019 End */
                                $tpitenraysightseeingArray = array(
                                    'InvnItemSysId' => $lasttravelitenaryID,
                                    'SupplierSysId' => (int) $SupplierSysId,
                                    'XrefInvnItemSysId' => '0',
                                    'SeqId' => 2,
                                    'CityId' => ($sscity > 0) ? $sscity : (!empty($postData['hidden_destination_id'][$optionKey][1]) ? $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][1]) : '0'),
                                    'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                    'SSSysId' => isset($sstid) ? $sstid : 0,
                                    'Title' => isset($sstitle) ? $sstitle : '',
                                    'Type' => 'Included',
                                    'FromDate' => $FromDate,
                                    'ToDate' => $currentDate,
                                    'BookingType' => '0',
                                    'PriceType' => (isset($postData["sightseeingType"][$q])) ? (int) $postData["sightseeingType"][$q] : 0,
                                    'Qty' => '0',
                                    'IfAnyOffer' => '0',
                                    'OfferMsg' => '0',
                                    'OfferImage' => '0',
                                    'IxFixedDateInven' => '0',
                                    'CreateDate' => $currentDate,
                                    'UpdateDate' => $currentDate,
                                    'IsMarkForDelete' => '0',
                                    'IsActive' => '1',
                                    'RoomInfoJson' => $RoomInfiJson,
                                    'Cost' => (float) $Cost,
                                    'KidsCost' => (float) $KidsCost,
                                );

                                $travelitenraysightssing = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenraysightseeingArray);
                            }
                            if (is_array($postData["sightseeingpvt"])) {
                                for ($q = 0; $q < is_array(count($postData["sightseeingpvt"])); $q++) {
                                    $rdtarr1 = array();
                                    $rdtarr1 = explode("__", $postData["sightseeingpvt"][$q]);
                                    $sscity = isset($rdtarr1[2]) ? (int) $rdtarr1[2] : 0;
                                    if (is_array($rdtarr1) && is_numeric($rdtarr1[0])) {
                                        $sstid = isset($rdtarr1[0]) ? (int) $rdtarr1[0] : 0;
                                        $sstitle = isset($rdtarr1[1]) ? $rdtarr1[1] : '';
                                    } else {
                                        $SCityId = !empty($postData['hidden_destination_id'][$optionKey][1]) ? $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][1]) : '0';
                                        $SightArray = $objPackage->getSightbyname(trim($rdtarr1[0]), $SCityId, $this->intLoggedinUserAgencySysId);
                                        if (empty($SightArray)) {
                                            $insertss = array(
                                                'IsAgentSpec' => '1',
                                                'AgentSysId' => $agentsysID,
                                                'ICSourceSysId' => $travelplandata[0]['AgencySysId'],
                                                'StartPlaceSysId' => '0',
                                                'EndPlaceSysId' => '0',
                                                'Title' => isset($rdtarr1[0]) ? $rdtarr1[0] : '',
                                                'synonyms' => '0',
                                                'WriteUp' => '',
                                                'DifficultyLevel' => '0',
                                                'AliasAndMeta' => '0',
                                                'SSGrType' => '0',
                                                'SSType' => '0',
                                                'SSIncMask' => '0',
                                                'DurationInMin' => '0',
                                                'DurationStr' => '0',
                                                'Icon' => '',
                                                'ThumnailImg' => '0',
                                                'DetailImg' => '0',
                                                'MinPax' => '0',
                                                'MaxPax' => '0',
                                                'PeakMothMask' => '0',
                                                'LeanMonthMask' => '0',
                                                'SilentMonthMask' => '0',
                                                'IsTransferInc' => '0',
                                                'IsKidAllowed' => '0',
                                                'IsTeenAllowed' => '0',
                                                'IsAdultAllowed' => '0',
                                                'IsPetAllowed' => '0',
                                                'IsTrxAllowed' => '0',
                                                'IsPickAllowed' => '0',
                                                'StartAgeYr' => '0',
                                                'EndAgeYr' => '0',
                                                'Rating' => '0',
                                                'Popularity' => '0',
                                                'ThingsToCarry' => '0',
                                                'AwardRecognizations' => '0',
                                                'BookingType' => '0',
                                                'DifficultyType' => '0',
                                                'DaysWeekMask' => '0',
                                                'StartLocalTime' => '',
                                                'EndLocalTime' => '',
                                                'TimeSlots' => '0',
                                                'IsDayLightApp' => '0',
                                                'Address' => '',
                                                'latitude' => '0',
                                                'longitude' => '0',
                                                'PinCode' => '0',
                                                'CitySysId' => $SCityId,
                                                'ZoneSysId' => '0',
                                                'ZoneType' => '0',
                                                'StateSysId' => '0',
                                                'ContSysId' => !empty($postData['hidden_country_id'][$optionKey][1]) ? trim($postData['hidden_country_id'][$optionKey][1]) : '0',
                                                'PickUpLocation' => '0',
                                                'PrimaryContact' => '0',
                                                'SecondaryContact' => '0',
                                                'OtherContacts' => '0',
                                                'UpdateDate' => $currentDate,
                                                'ApproveDate' => '1900-01-01',
                                                'ApproveBy' => '0',
                                                'CreateDate' => $currentDate,
                                                'IsApproved' => '0',
                                                'IsActive' => '1',
                                                'IsMarkForDel' => '0'
                                            );
                                            //                                        echo "<pre>";print_r($postData);die;
                                            $objSightseeing = new Travel_Model_TblSightseeing();
                                            $intLastInsertId = $objSightseeing->addSightseeingDetails($insertss);
                                            $sstid = isset($intLastInsertId) ? $intLastInsertId : 0;
                                            $sstitle = isset($rdtarr1[0]) ? $rdtarr1[0] : '';
                                        } else {
                                            $sstid = $SightArray['SSSysId'];
                                            $sstitle = isset($rdtarr1[0]) ? $rdtarr1[0] : '';
                                        }
                                    }
                                    $RoomInfiJsonArr = array();
                                    $RoomInfiJson = '';
                                    $FromDate = $currentDate;
                                    $Cost = 0;
                                    $KidsCost = 0;
                                    /* Code  By Mangal For Only Sightseeing Share 25/09/2019 Start */
                                    if (isset($postData['onlySightseeing']) && $postData['onlySightseeing'] == 1) {
                                        $RoomInfiJsonArr = [
                                            'sightseeingDate' => $postData['sightseeingDate'][$q],
                                            'citySysId' => $postData['hidden_destination_id'][$optionKey][$q + 1],
                                            'cityName' => $postData['hidden_destination_withoutcountry'][$optionKey][$q + 1],
                                            'hidden_country_id' => $postData['hidden_country_id'][$optionKey][$q + 1],
                                            'sightseeingType' => $postData['sightseeingType'][$q],
                                            'perAdultPrice' => $postData['perAdultPrice'][$q],
                                            'noofAdults' => $postData['noofAdults'][$q],
                                            'adultPrice' => $postData['adultPrice'][$q],
                                            'perChildPrice' => $postData['perChildPrice'][$q],
                                            'noofChild' => $postData['noofChild'][$q],
                                            'childPrice' => $postData['childPrice'][$q],
                                            'MarkupPerAdultPrice' => $postData['MarkupPerAdultPrice'][$q],
                                            'MarkupPerChildPrice' => $postData['MarkupPerChildPrice'][$q],
                                        ];
                                        $sightseeingDate = explode('/', $postData['sightseeingDate'][$q]);
                                        $FromDate = $sightseeingDate[2] . '-' . $sightseeingDate[1] . '-' . $sightseeingDate[0];
                                        $Cost = $postData['perAdultPrice'][$q];
                                        $KidsCost = $postData['perChildPrice'][$q];
                                        $RoomInfiJson = json_encode($RoomInfiJsonArr);
                                    }
                                    /* Code  By Mangal For Only Sightseeing Share 25/09/2019 End */
                                    $tpitenraysightseeingArray = array(
                                        'InvnItemSysId' => $lasttravelitenaryID,
                                        'SupplierSysId' => (int) $SupplierSysId,
                                        'XrefInvnItemSysId' => '0',
                                        'SeqId' => 2,
                                        'CityId' => ($sscity > 0) ? $sscity : (!empty($postData['hidden_destination_id'][$optionKey][1]) ? $this->_HtmlPurifier->filter($postData['hidden_destination_id'][$optionKey][1]) : '0'),
                                        'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                        'SSSysId' => isset($sstid) ? $sstid : 0,
                                        'Title' => isset($sstitle) ? $sstitle : '',
                                        'Type' => 'Included',
                                        'FromDate' => $FromDate,
                                        'ToDate' => $currentDate,
                                        'BookingType' => '0',
                                        'PriceType' => (isset($postData["sightseeingType"][$q])) ? (int) $postData["sightseeingType"][$q] : 0,
                                        'Qty' => '0',
                                        'IfAnyOffer' => '0',
                                        'OfferMsg' => '0',
                                        'OfferImage' => '0',
                                        'IxFixedDateInven' => '0',
                                        'CreateDate' => $currentDate,
                                        'UpdateDate' => $currentDate,
                                        'IsMarkForDelete' => '0',
                                        'IsActive' => '1',
                                        'RoomInfoJson' => $RoomInfiJson,
                                        'Cost' => (float) $Cost,
                                        'KidsCost' => (float) $KidsCost,
                                    );

                                    $travelitenraysightssing = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenraysightseeingArray);
                                }
                            }
                            $SightseeingVoucherStatus = 1;
                        }
                    }
                    if (isset($postData['TransType']) && is_array($postData['TransType']) && count($postData['TransType']) > 0) {
                        foreach ($postData['TransType'] as $transId => $transPort) {
                            foreach ($postData['FromCity'][$transId] as $key => $value) {
                                if (!empty($value)) {
                                    $FromCityHIDDENIDArr = explode('__', $postData['FromCityHIDDENID'][$transId][$key]);
                                    $ToCityHIDDENIDArr = explode('__', $postData['ToCityHIDDENID'][$transId][$key]);
                                    $explodestartdateAll = explode(' ', $postData['FromDate'][$transId][$key]);
                                    $explodestartdate = explode('/', $explodestartdateAll[0]);
                                    $fromdate = $explodestartdate[2] . '-' . $explodestartdate[1] . '-' . $explodestartdate[0] . " " . $explodestartdateAll[1];
                                    $explodeenddateAll = explode(' ', $postData['ToDate'][$transId][$key]);
                                    $explodeenddate = explode('/', $explodeenddateAll[0]);
                                    $todate = $explodeenddate[2] . '-' . $explodeenddate[1] . '-' . $explodeenddate[0] . " " . $explodeenddateAll[1];

                                    $FromCityLocation = (isset($postData['FromCityLocation'][$transId][$key]) && !empty($postData['FromCityLocation'][$transId][$key])) ? trim($postData['FromCityLocation'][$transId][$key]) : (isset($FromCityHIDDENIDArr[1]) ? trim($FromCityHIDDENIDArr[1]) : '');
                                    $ToCityLocation = (isset($postData['ToCityLocation'][$transId][$key]) && !empty($postData['ToCityLocation'][$transId][$key])) ? trim($postData['ToCityLocation'][$transId][$key]) : (isset($ToCityHIDDENIDArr[1]) ? trim($ToCityHIDDENIDArr[1]) : '');
                                    $RouteVechSysId = (isset($postData['RouteVechSysId'][$transId][$key]) && !empty($postData['RouteVechSysId'][$transId][$key])) ? trim($postData['RouteVechSysId'][$transId][$key]) : 0;
                                    $RouteSysId = (isset($postData['RouteSysId'][$transId][$key]) && !empty($postData['RouteSysId'][$transId][$key])) ? trim($postData['RouteSysId'][$transId][$key]) : 0;
                                    $dropArea = (isset($postData['dropArea'][$transId][$key]) && !empty($postData['dropArea'][$transId][$key])) ? trim($postData['dropArea'][$transId][$key]) : 0;
                                    $transferType = (isset($postData['transferType'][$transId][$key]) && !empty($postData['transferType'][$transId][$key])) ? trim($postData['transferType'][$transId][$key]) : 0;
                                    $categoryTransport = (isset($postData['categoryTransport'][$transId][$key]) && !empty($postData['categoryTransport'][$transId][$key])) ? trim($postData['categoryTransport'][$transId][$key]) : 0;
                                    $categoryTransportExplode = explode('_', $categoryTransport);
                                    if (isset($categoryTransportExplode[1])) {
                                        $categoryTransport = $categoryTransportExplode[1];
                                    }

                                    $dropAreaExplode = explode('__', $dropArea);
                                    if (isset($dropAreaExplode[1])) {
                                        $ToCityLocation = trim($dropAreaExplode[1]);
                                    }
                                    $AreaSysId = (isset($dropAreaExplode[0]) && $dropAreaExplode[0] > 0) ? (int) $dropAreaExplode[0] : 0;
                                    $costTransport = (isset($postData['costTransport'][$transId][$key]) && !empty($postData['costTransport'][$transId][$key])) ? (int) ($postData['costTransport'][$transId][$key]) : 0;
                                    $currencyTransport = (isset($postData['currencyTransport'][$transId][$key]) && !empty($postData['currencyTransport'][$transId][$key])) ? (int) ($postData['currencyTransport'][$transId][$key]) : 0;
                                    $taxTransportAmt = (isset($postData['taxTransportAmt'][$transId][$key]) && !empty($postData['taxTransportAmt'][$transId][$key])) ? (int) ($postData['taxTransportAmt'][$transId][$key]) : 0;

                                    $markupTransport = (isset($postData['markupTransport'][$transId][$key]) && !empty($postData['markupTransport'][$transId][$key])) ? (int) ($postData['markupTransport'][$transId][$key]) : 0;
                                    $totalTransport = (isset($postData['totalTransport'][$transId][$key]) && !empty($postData['totalTransport'][$transId][$key])) ? (int) ($postData['totalTransport'][$transId][$key]) : 0;
                                    $supplierIdTransport = (isset($postData['supplierIdTransport'][$transId][$key]) && !empty($postData['supplierIdTransport'][$transId][$key])) ? (int) ($postData['supplierIdTransport'][$transId][$key]) : (int) $SupplierSysId;
                                    $vehicleName = (isset($postData['vehicleName'][$transId][$key]) && !empty($postData['vehicleName'][$transId][$key])) ? ($postData['vehicleName'][$transId][$key]) : '';
                                    $Type = (($vehicleName != '') ? $vehicleName : !empty($postData['Type'][$transId][$key])) ? $this->_HtmlPurifier->filter($postData['Type'][$transId][$key]) : '';

                                    $data = array(
                                        'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                        'TPSysId' => $tpproposalID,
                                        'TPIntSysId' => $lasttravelitenaryID,
                                        'Type' => 'Included',
                                        'IsIncluded' => '1',
                                        'VehSysId' => $RouteVechSysId,
                                        'VehicleTypeSysId' => 0,
                                        'RouteSysId' => $RouteSysId,
                                        'RouteVechSysId' => $RouteVechSysId,
                                        'TransId' => !empty($transId) ? $this->_HtmlPurifier->filter($transId) : ' ',
                                        'TransType' => !empty($transPort) ? $this->_HtmlPurifier->filter($transPort) : ' ',
                                        'FromPlace' => !empty($FromCityLocation) ? $this->_HtmlPurifier->filter($FromCityLocation) : '',
                                        'ToPlace' => !empty($ToCityLocation) ? $this->_HtmlPurifier->filter($ToCityLocation) : '',
                                        'SourceCityId' => !empty($FromCityHIDDENIDArr) ? $this->_HtmlPurifier->filter($FromCityHIDDENIDArr[0]) : '',
                                        'DestCityId' => !empty($ToCityHIDDENIDArr) ? $this->_HtmlPurifier->filter($ToCityHIDDENIDArr[0]) : '',
                                        'Type_Text' => $Type,
                                        'FromDate' => !empty($fromdate) ? $fromdate : '',
                                        'ToDate' => !empty($todate) ? $todate : '',
                                        'CostPerson' => 0,
                                        'CostChild' => 0,
                                        'TotalPrice' => $costTransport + $taxTransportAmt,
                                        'TotalMarkup' => $markupTransport,
                                        'Taxes' => $taxTransportAmt,
                                        'NetCost' => $totalTransport,
                                        'AreaSysId' => $AreaSysId,
                                        'Capacity' => 0,
                                        'CreateDate' => $currentDate,
                                        'IsMarkForDel' => '0',
                                        'Sequence' => 0,
                                        'IsActive' => '1',
                                        'VehicleQty' => 0,
                                        'IsGroup' => 0,
                                        'XRefVoucherNo' => 0,
                                        'TransportCategory' => $categoryTransport,
                                        'TransTypeCat' => $transferType,
                                        'SupplierSysId' => $supplierIdTransport,
                                        'CurrencyType' => $currencyTransport,
                                    );
                                    $updateId = $objPackage->insertData('TB_Agency_Customer_Trans_Fixed', $data);
                                    $TransferVoucherStatus = 1;
                                }
                            }
                        }
                    }
                    $totalNoofPax = (int) $postData['totalAdult'] + ((int) $flightDetailChildCost > 0 ? (int) $postData['totalChild'] : 0) + ((int) $flightDetailInfantCost > 0 ? (int) $postData['totalInfant'] : 0);
                    $adultMarkup = ((float) $flightDetailMarkup / (int) $totalNoofPax) * (int) ($postData['totalAdult']);
                    $childMarkup = ((int) $flightDetailChildCost > 0) ? (((float) $flightDetailMarkup / (int) $totalNoofPax) * (int) ($postData['totalChild'])) : 0;
                    $infantMarkup = ((int) $flightDetailInfantCost > 0) ? (((float) $flightDetailMarkup / (int) $totalNoofPax) * (int) ($postData['totalInfant'])) : 0;
                    $totalFlightGST = (int) $flightDetailTotal - (int) $flightDetailCost - (int) $flightDetailMarkup;
                    $adultGST = ((float) $totalFlightGST / (int) $totalNoofPax) * (int) ($postData['totalAdult']);
                    $childGST = ((int) $flightDetailChildCost > 0) ? (((float) $totalFlightGST / (int) $totalNoofPax) * (int) ($postData['totalChild'])) : 0;
                    $infantGST = ((int) $flightDetailInfantCost > 0) ? (((float) $totalFlightGST / (int) $totalNoofPax) * (int) ($postData['totalInfant'])) : 0;
                    $package_flightdetails = array(
                        'textbased' => 'textbased',
                        'supplier_type' => $flightSupplier,
                        'supplier_type_id' => $flightSupplierSysId,
                        'flighttext' => $FlightContent,
                        'adult_pax' => $postData['totalAdult'],
                        'adult_cost_pp' => $flightDetailAdultCost,
                        'adult_markup' => $adultMarkup,
                        'adult_gst' => $adultGST,
                        'adult_total' => ((int) $flightDetailAdultCost * (int) $postData['totalAdult']) + $adultMarkup + $adultGST,
                        'totalcost_wom' => $flightDetailCost,
                        'total_markup' => $flightDetailMarkup,
                        'total_gst' => $totalFlightGST,
                        'totalflightcost' => $flightDetailTotal,
                    );
                    if ($postData['totalChild'] > 0) {
                        $package_flightdetails['child_pax'] = $postData['totalChild'];
                        $package_flightdetails['child_cost_pp'] = $flightDetailChildCost;
                        $package_flightdetails['child_markup'] = $childMarkup;
                        $package_flightdetails['child_gst'] = $childGST;
                        $package_flightdetails['child_total'] = ((int) $flightDetailChildCost * (int) $postData['totalChild']) + $childMarkup + $childGST;
                    }
                    if ($postData['totalInfant'] > 0) {
                        $package_flightdetails['infant_pax'] = $postData['totalInfant'];
                        $package_flightdetails['infant_cost_pp'] = $flightDetailInfantCost;
                        $package_flightdetails['infant_markup'] = $infantMarkup;
                        $package_flightdetails['infant_gst'] = $infantGST;
                        $package_flightdetails['infant_total'] = ((int) $flightDetailInfantCost * (int) $postData['totalInfant']) + $infantMarkup + $infantGST;
                    }


                    //                    echo "<pre>";print_r($package_flightdetails);die;
                    $_SESSION['package_flightdetails'] = $package_flightdetails;
                    $TPSysId = (isset($postData['TPSysId']) && !empty($postData['TPSysId'])) ? (int) $postData['TPSysId'] : 0;
                    $ProposalTPSysId = (isset($postData['ProposalTPSysId']) && !empty($postData['ProposalTPSysId'])) ? (int) $postData['ProposalTPSysId'] : 0;
                    $flightType = (isset($postData['flightType']) && !empty($postData['flightType'])) ? (int) $postData['flightType'] : 1;
                    $textbased = (isset($postData['textbased']) && !empty($postData['textbased'])) ? (int) $postData['textbased'] : 0;

                    if ($isShareWithFlight == 1) {
                        $tripType = (isset($postData['tripType']) && !empty($postData['tripType'])) ? (int) $postData['tripType'] : 0;
                        $refundable = (isset($postData['refundable']) && !empty($postData['refundable'])) ? (int) $postData['refundable'] : 0;
                        if ($flightType == 2) {

                            if ($tripType == 1) {
                                $airline_name[0] = isset($postData['airline_name'][0]) ? $postData['airline_name'][0] : array();
                            } else {
                                $airline_name[1] = isset($postData['airline_name'][1]) ? $postData['airline_name'][1] : array();
                                $airline_name[2] = isset($postData['airline_name'][2]) ? $postData['airline_name'][2] : array();
                            }
                        } else {
                            $airline_name = array(0 => '');
                            $tripType = 0;
                        }

                        $flightCost = [];
                        $encodedata = [];
                        $TPIntSysIdForFlight = $lasttravelitenaryID;

                        foreach ($airline_name as $anKey => $anValue) {
                            $sourceairportcode_name = $destairportcode_name = '';
                            $airportSourceCityId = $airportDestCityId = 0;
                            if ($flightType == 2) {
                                $departure_date_oneway = isset($postData['departure_date_oneway'][$anKey]) ? explode(' ', trim($postData['departure_date_oneway'][$anKey])) : '';
                                $arrival_date_oneway = isset($postData['arrival_date_oneway'][$anKey]) ? explode(' ', trim($postData['arrival_date_oneway'][$anKey])) : '';
                                $sourceairportcode_name = isset($postData['source_place_id'][$anKey]) ? trim($postData['source_place_id'][$anKey]) : '';
                                $airportSourceCityId = isset($package_flightdetails['sourceCityId'][$anKey]) ? trim($package_flightdetails['sourceCityId'][$anKey]) : 0;
                                $destairportcode_name = isset($package_flightdetails['destination_place_id'][$anKey]) ? trim($package_flightdetails['destination_place_id'][$anKey]) : '';
                                $airportDestCityId = isset($package_flightdetails['destinationCityId'][$anKey]) ? trim($package_flightdetails['destinationCityId'][$anKey]) : 0;

                                $flightJson = [
                                    'supplier_type' => $flightSupplier,
                                    'supplier_type_id' => $flightSupplierSysId,
                                    'FlightNo' => isset($postData['airlineNo'][$anKey]) ? trim($postData['airlineNo'][$anKey]) : '',
                                    'AirlineName' => trim($anValue),
                                    'hidden_selected_airline_sys_id' => isset($postData['hidden_selected_airline_sys_id'][$anKey]) ? (int) $postData['hidden_selected_airline_sys_id'][$anKey] : '',
                                    'departureCity' => isset($postData['source_place'][$anKey]) ? trim($postData['source_place'][$anKey]) : '',
                                    'depaartureDate' => isset($departure_date_oneway[0]) ? trim($departure_date_oneway[0]) : '',
                                    'depaartureTime' => isset($departure_date_oneway[1]) ? trim($departure_date_oneway[1]) : '',
                                    'arrivalCity' => isset($postData['destination_place'][$anKey]) ? trim($postData['destination_place'][$anKey]) : '',
                                    'arrivalDate' => isset($arrival_date_oneway[0]) ? trim($arrival_date_oneway[0]) : '',
                                    'arrivalTime' => isset($arrival_date_oneway[1]) ? trim($arrival_date_oneway[1]) : '',
                                    'stops' => isset($postData['stops'][$anKey]) ? trim($postData['stops'][$anKey]) : '',
                                    'stopOver' => isset($postData['stopOver'][$anKey]) ? trim($postData['stopOver'][$anKey]) : '',
                                    'duration' => isset($postData['duration'][$anKey]) ? trim($postData['duration'][$anKey]) : '',
                                    'currencyTypes' => isset($postData['currencyTypes'][$tripType - 1]) ? trim($postData['currencyTypes'][$tripType - 1]) : '',
                                    'FareClass' => isset($postData['FareClass'][$anKey]) ? trim($postData['FareClass'][$anKey]) : '',
                                    'Baggage' => isset($postData['Baggage'][$anKey]) ? trim($postData['Baggage'][$anKey]) : '',
                                    'CabinBaggage' => isset($postData['CabinBaggage'][$anKey]) ? trim($postData['CabinBaggage'][$anKey]) : '',
                                    'refundableFlight' => $refundable,
                                    'totalFightCost' => isset($postData['total_cost'][$anKey]) ? trim($postData['total_cost'][$anKey]) : '',
                                    'totalFightMarkup' => isset($postData['total_markup'][$anKey]) ? trim($postData['total_markup'][$anKey]) : '',
                                    'totalTax' => isset($postData['total_gst'][$anKey]) ? trim($postData['total_gst'][$anKey]) : '',
                                    'totalFightCostWithMarkup' => isset($postData['grand_total'][$anKey]) ? trim($postData['grand_total'][$anKey]) : '',
                                    'fareRules' => isset($postData['fareRuleOneWay']) ? trim($postData['fareRuleOneWay']) : '',
                                    'adult_pax' => isset($postData['adults_count_oneWay'][$anKey]) ? trim($postData['adults_count_oneWay'][$anKey]) : '',
                                    'adult_cost_pp' => isset($postData['costAd'][$anKey]) ? trim($postData['costAd'][$anKey]) : '',
                                    'adult_markup' => isset($postData['markupAd'][$anKey]) ? trim($postData['markupAd'][$anKey]) : '',
                                    'adult_gst' => isset($postData['gstAd'][$anKey]) ? trim($postData['gstAd'][$anKey]) : '',
                                    'adult_total' => isset($postData['totalAd'][$anKey]) ? trim($postData['totalAd'][$anKey]) : '',
                                    'child_pax' => isset($postData['child_count_oneWay'][$anKey]) ? trim($postData['child_count_oneWay'][$anKey]) : '',
                                    'child_cost_pp' => isset($postData['costCh'][$anKey]) ? trim($postData['costCh'][$anKey]) : '',
                                    'child_markup' => isset($postData['markupCh'][$anKey]) ? trim($postData['markupCh'][$anKey]) : '',
                                    'child_gst' => isset($postData['gstCh'][$anKey]) ? trim($postData['gstCh'][$anKey]) : '',
                                    'child_total' => isset($postData['totalCh'][$anKey]) ? trim($postData['totalCh'][$anKey]) : '',
                                    'infant_pax' => isset($postData['infant_count_oneWay'][$anKey]) ? trim($postData['infant_count_oneWay'][$anKey]) : '',
                                    'infant_cost_pp' => isset($postData['costIn'][$anKey]) ? trim($postData['costIn'][$anKey]) : '',
                                    'infant_markup' => isset($postData['markupIn'][$anKey]) ? trim($postData['markupIn'][$anKey]) : '',
                                    'infant_gst' => isset($postData['gstIn'][$anKey]) ? trim($postData['gstIn'][$anKey]) : '',
                                    'infant_total' => isset($postData['totalIn'][$anKey]) ? trim($postData['totalIn'][$anKey]) : '',
                                    'totalcost_wom' => isset($postData['total_cost'][$anKey]) ? trim($postData['total_cost'][$anKey]) : '',
                                    'total_markup' => isset($postData['total_markup'][$anKey]) ? trim($postData['total_markup'][$anKey]) : '',
                                    'total_gst' => isset($postData['total_gst'][$anKey]) ? trim($postData['total_gst'][$anKey]) : '',
                                    'totalflightcost' => isset($postData['grand_total'][$anKey]) ? trim($postData['grand_total'][$anKey]) : '',
                                    'source_place_Code' => isset($postData['source_place_id'][$anKey]) ? trim($postData['source_place_id'][$anKey]) : '',
                                    'destination_place_Code' => isset($postData['destination_place_id'][$anKey]) ? trim($postData['destination_place_id'][$anKey]) : '',
                                    'GstTaxFlight' => 0,
                                ];
                                $flightCost[] = $flightJson;
                                $package_flightdetailsFinal = array_merge($package_flightdetails, $flightJson);
                                $_SESSION['package_flightdetails'] = $package_flightdetailsFinal;
                                $tripType = $anKey + 1;
                            } else {
                                $package_flightdetailsFinal = $package_flightdetails;
                            }
                            //                            echo "<pre>";print_r($postData['currencyTypes']);die;
                            $LocalFromTime = (isset($package_flightdetailsFinal['depaartureDate']) && !empty($package_flightdetailsFinal['depaartureDate'])) ? explode('/', $package_flightdetailsFinal['depaartureDate']) : '';
                            $LocalFromTime1 = (!empty($LocalFromTime)) ? trim($LocalFromTime[2] . '-' . $LocalFromTime[1] . '-' . $LocalFromTime[0] . ' ' . (isset($package_flightdetailsFinal['depaartureTime']) ? trim($package_flightdetailsFinal['depaartureTime']) : '')) : '';

                            $LocalToTime = (isset($package_flightdetailsFinal['arrivalDate']) && !empty($package_flightdetailsFinal['arrivalDate'])) ? explode('/', $package_flightdetailsFinal['arrivalDate']) : '';
                            $LocalToTime1 = (!empty($LocalToTime)) ? trim($LocalFromTime[2] . '-' . $LocalFromTime[1] . '-' . $LocalFromTime[0] . ' ' . (isset($package_flightdetailsFinal['arrivalTime']) ? trim($package_flightdetailsFinal['arrivalTime']) : '')) : '';

                            //echo "<pre>";print_r($package_flightdetailsFinal);die;
                            $encodedata[] = $package_flightdetailsFinal;
                            $travelitenaryaccomairArray = array(
                                'TPIntSysId' => (int) $TPIntSysIdForFlight,
                                'SeqId' => 0,
                                'InvnItemSysId' => 0,
                                'AgencySysId' => $travelplandata[0]['AgencySysId'],
                                'IsFromAPI' => 0,
                                'SourceSysId' => 0,
                                'SupplierSysId' => (int) $flightSupplierSysId,
                                'TripType' => $tripType,
                                'CurrencyType' => !empty($package_flightdetailsFinal['currencyTypes']) ? (int) $package_flightdetailsFinal['currencyTypes'] : 0,
                                'Cost' => !empty($package_flightdetailsFinal['totalcost_wom']) ? (float) $package_flightdetailsFinal['totalcost_wom'] : 0,
                                'TotalCost' => !empty($package_flightdetailsFinal['totalflightcost']) ? (float) $package_flightdetailsFinal['totalflightcost'] : 0,
                                'FlightNumber' => isset($package_flightdetailsFinal['FlightNo']) ? (int) $package_flightdetailsFinal['FlightNo'] : 0,
                                'AirlineSysId' => isset($package_flightdetailsFinal['hidden_selected_airline_sys_id']) ? (int) $package_flightdetailsFinal['hidden_selected_airline_sys_id'] : 0,
                                'ICSourceSysId' => 0,
                                'IsFromAgency' => 0,
                                'LocalFromTime' => $LocalFromTime1,
                                'LocalToTime' => $LocalToTime1,
                                'FromUTCTime' => '',
                                'ToUTCTime' => '',
                                'FlightCabinClass' => '',
                                'AdultPax' => !empty($postData['totalAdult']) ? (float) $postData['totalAdult'] : 0,
                                'ChildPax' => !empty($postData['totalChild']) ? (float) $postData['totalChild'] : 0,
                                'InfentPax' => !empty($postData['totalInfant']) ? (float) $postData['totalInfant'] : 0,
                                'TotalPax' => $postData['totalAdult'] + $postData['totalChild'] + $postData['totalInfant'],
                                'IsSelectedOnPkg' => 0,
                                'IsDirect' => 0,
                                'DayLightSavingDiff' => 0,
                                'FlyingMinutes' => 0,
                                'SourcePlaceSysId' => $airportSourceCityId,
                                'DestPlaceSysId' => $airportDestCityId,
                                'SourceAirportCode' => $sourceairportcode_name,
                                'DestAirportCode' => $destairportcode_name,
                                'AirportHaultMinutes' => 0,
                                'StopCount' => 0,
                                'Stops' => !empty($package_flightdetailsFinal['stops']) ? $package_flightdetailsFinal['stops'] : 0,
                                'Rating' => 0,
                                'FllightFeatureMask' => 0,
                                'UpdatedByISSysId' => 0,
                                'CreatedByISSysId' => 0,
                                'ImageTN' => 0,
                                'ImgForList' => 0,
                                'ImgeDetails' => 0,
                                'UpdateDate' => $currentDate,
                                'CreateDate' => $currentDate,
                                'ApproveBy' => 0,
                                'ApprovalDate' => $currentDate,
                                'IsApproved' => 1,
                                'IsActive' => 1,
                                'IsMarkForDel' => 0,
                                'encodedata' => json_encode($package_flightdetailsFinal),
                                'XRefBookingId' => 0,
                                'XRefPNR' => 0,
                                'XRefCancellationlId' => 0,
                                'APIBookingRes' => 0,
                                'APICancellationRes' => 0,
                                'Discount' => 0,
                                'XServiceTaxAmount' => 0,
                                'GTXServiceTaxAmount' => 0,
                                'AgentServiceTaxAmount' => 0,
                                'AgentsCustomServiceTaxAmount' => isset($package_flightdetailsFinal['total_gst']) ? (float) $package_flightdetailsFinal['total_gst'] : 0,
                                'MarkUp' => isset($package_flightdetailsFinal['total_markup']) ? (float) $package_flightdetailsFinal['total_markup'] : 0,
                                'AgencyMarkUp' => 0,
                                'GTXMarkup' => 0,
                                'GTXCommission' => 0,
                                'AgencyCommission' => 0,
                                'Taxes' => 0,
                                'TDS' => 0,
                                'DiscountMsg' => 0,
                                'IsFixedTransport' => 0,
                                'AirlineRefPNR' => 0
                            );
                            if ($flightType == 1) {
                                try {
                                    $airId = $objPackage->insertData('TB_Agency_Customer_TravelPlan_Air', $travelitenaryaccomairArray);
                                    echo "<pre>";
                                    print_r($airId);
                                } catch (Zend_Exception $e) {
                                    $e->getMessage();
                                    file_content_put("error/package_search_" . time() . '.txt', json_encode($travelitenaryaccomairArray));
                                }
                            }
                        }

                        if ($flightType == 2) {
                            $BookingDataAPI = $this->SetFlightData($encodedata, $postData);
                        }

                        // echo "<pre>";
                        // print_r($encodedata);
                        // echo "<pre>";
                        // print_r($postData);
                        // die;
                        if (!empty($BookingDataAPI)) {
                            try {
                                $TempBookingData = [];
                                foreach ($BookingDataAPI['FlightBookingData'] as $keFl => $value) {
                                    $encodedataSET = (isset($encodedata[$keFl]) && !empty($encodedata[$keFl])) ? ($encodedata[$keFl]) : [];
                                    if ($keFl == 0) {
                                        $encodedataSET['BookingDataAPI'] = $BookingDataAPI;
                                    }

                                    $TempBookingData[$keFl] = $value;
                                    $TempBookingData[$keFl]['TPIntSysId'] = $TPIntSysIdForFlight;
                                    $TempBookingData[$keFl]['SupplierSysId'] = (int) $flightSupplierSysId;
                                    $TempBookingData[$keFl]['encodedata'] = (isset($encodedataSET) && !empty($encodedataSET)) ? json_encode($encodedataSET) : '';
                                }
                                $BookingDataAPI['FlightBookingData'] = $TempBookingData;
                                $BookingDataAPI['ProposalID'] = $tpproposalID;
                                $BookingDataAPI['email'] = isset($travelplandata[0]['EmailId']) ? $travelplandata[0]['EmailId'] : '';
                                $BookingDataAPI['mobile'] = isset($travelplandata[0]['Contacts']) ? $travelplandata[0]['Contacts'] : '';

                                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                                $URL = $this->baseUrl . '/gtxwebservices/flight-api';
                                $GENERATE_FLIGHT_QUERY = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($BookingDataAPI, $getData, $URL);
                                // echo "<pre>";
                                // print_r($GENERATE_FLIGHT_QUERY);
                                // print_r($BookingDataAPI);
                                // die;
                            } catch (Zend_Exception $e) {
                                $e->getMessage();
                                file_content_put("error/package_search_" . time() . '.txt', json_encode($travelitenaryaccomairArray));
                            }
                        }
                    }
                    //                    echo "<pre>"; print_r($postData); die;
                    //                    start misc
                    if ($postData['PlanType'] == 24 && $postData['PackageType'] == 'Text') {
                        $miscArr = isset($postData['MiscItemCF']) ? $postData['MiscItemCF'] : [];
                        foreach ($miscArr as $misKy => $miscVal) {
                            $expoValue = explode('__', $miscVal);
                            $miscId = $expoValue['0'];
                            $miscTitle = $expoValue['1'];
                            $time = !empty($postData['time'][$misKy]) ? $postData['time'][$misKy] : '';
                            $dateObj = new DateTime($currentDate);
                            $timeObj = new DateTime($time);
                            $hour = $timeObj->format('H');
                            $minute = $timeObj->format('i');
                            $second = $timeObj->format('s');
                            $dateObj->setTime($hour, $minute, $second);
                            $mergedDateTime = $dateObj->format('Y-m-d H:i:s');
                            $MiscItemTypeSeq = isset($postData['MiscItemTypeSeq'][$misKy]) ? $postData['MiscItemTypeSeq'][$misKy] : 0;
                            $miscData = array(
                                'OtherSrvSysId' => $miscId ? $miscId : 0,
                                'TPIntSysId' => $tpproposalID,
                                'ItenarySysId' => $lasttravelitenaryID ? $lasttravelitenaryID : 0,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => !empty($postData['paidMiscSupplierId'][$misKy]) ? $this->_HtmlPurifier->filter($postData['paidMiscSupplierId'][$misKy]) : '0',
                                'ServiceTitle' => !empty($miscTitle) ? $miscTitle : '',
                                'ServiceType' => 100,
                                'Comment' => !empty($postData['miscDesc'][$misKy]) ? $postData['miscDesc'][$misKy] : '',
                                'CurrencyType' => !empty($postData['MiscItemCurrencyType'][$misKy]) ? $this->_HtmlPurifier->filter($postData['MiscItemCurrencyType'][$misKy]) : 0,
                                'RateType' => !empty($postData['OptionalMiscItemType'][$misKy]) ? $postData['OptionalMiscItemType'][$misKy] : 0,
                                'PaxCount' => 0,
                                'TotalItem' => 1,
                                'Cost' => !empty($postData['MiscItemCost'][$misKy]) ? $postData['MiscItemCost'][$misKy] : 0,
                                'IsOptionalServices' => ($MiscItemTypeSeq > 0 && isset($postData['MiscItemType'][$MiscItemTypeSeq])) ? 1 : 0,
                                'IsSelected' => ($MiscItemTypeSeq > 0 && isset($postData['MiscItemType'][$MiscItemTypeSeq])) ? 0 : 1,
                                'IsCostInclInTP' => 0,
                                'IsActive' => '1',
                                'IsMarkForDelete' => 0,
                                'IsApproved' => '1',
                                'CreateDate' => $mergedDateTime,
                                'UpdateDate' => $mergedDateTime,
                                'XRefVoucherNo' => 0,
                                'IsIncludedInPackage' => 1,
                                'TotalItem' => !empty($postData['quantity'][$misKy]) ? (int) $postData['quantity'][$misKy] : 1,
                                'Markup' => !empty($postData['MiscItemMarkup'][$misKy]) ? (int) $postData['MiscItemMarkup'][$misKy] : 0,
                                'Discount' => !empty($postData['MiscItemdiscount'][$misKy]) ? (int) $postData['MiscItemdiscount'][$misKy] : 0,
                                'TotalCost' => !empty($postData['totalAmountMiscItem'][$misKy]) ? (int) $postData['totalAmountMiscItem'][$misKy] : 0,
                                'Description' => !empty($postData['saccodetext'][$misKy]) ? (int) $postData['saccodetext'][$misKy] : 0,
                                'AdultCost' => !empty($postData['MiscItemAdultCost'][$misKy]) ? (float) $postData['MiscItemAdultCost'][$misKy] : 0,
                                'ChildCost' => !empty($postData['MiscItemChildCost'][$misKy]) ? (float) $postData['MiscItemChildCost'][$misKy] : 0,
                            );

                            $updateId = $objPackage->insertData('TB_Agency_Customer_TravelPlan_OtherServices', $miscData);
                        }
                    }


                    $Total_Sales_Price = isset($postData['op' . $optionKey . 'Total_Sales_Price']) ? (int) $postData['op' . $optionKey . 'Total_Sales_Price'] : 0;
                    $Total_Price = isset($postData['op' . $optionKey . 'Total']) ? (int) $postData['op' . $optionKey . 'Total'] : 0;
                    $Total_Cost_with_GST = isset($postData['op' . $optionKey . 'Total_Cost_with_GST']) ? (int) $postData['op' . $optionKey . 'Total_Cost_with_GST'] : 0;
                    if ($tpproposalID > 0) {
                        if ((int) $hotelDetailTotal > 0) {

                            $GSTAmountHotel = 0;
                            if ($arrGSTCalculations['TaxType'] == 1) {
                                $GSTAmountHotel = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($hotelDetailTotal, $arrGSTCalculations['TaxRate']);
                            }
                            if ($arrGSTCalculations['TaxType'] == 2) {
                                $GSTAmountHotel = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($hotelDetailMarkup, $arrGSTCalculations['TaxRate']);
                            }

                            $addonHotelData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 2,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Hotel',
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => $GSTApplicableOn,
                                'Tax' => $GSTAmountHotel,
                                'Cost' => (float) $hotelDetailCost,
                                'Markup' => (float) $hotelDetailMarkup,
                                'TotalCost' => (float) ($hotelDetailTotal + $GSTAmountHotel),
                                'IsActive' => 1,
                                'IsApplyTax' => 0,
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonHotelData);
                        }

                        if ((int) $transportDetailTotal > 0) {

                            $GSTAmountTransport = 0;
                            if ($arrGSTCalculations['TaxType'] == 1) {
                                $GSTAmountTransport = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($transportDetailTotal, $arrGSTCalculations['TaxRate']);
                            }
                            if ($arrGSTCalculations['TaxType'] == 2) {
                                $GSTAmountTransport = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($transportDetailMarkup, $arrGSTCalculations['TaxRate']);
                            }

                            $addonTransportData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 11,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Transfer',
                                'AdultCount' => !empty($postData['totalAdult']) ? (float) $postData['totalAdult'] : 0,
                                'ChildCount' => !empty($postData['totalChild']) ? (float) $postData['totalChild'] : 0,
                                'InfentCount' => !empty($postData['totalInfant']) ? (float) $postData['totalInfant'] : 0,
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => $GSTApplicableOn,
                                'Tax' => $GSTAmountTransport,
                                'Cost' => (float) $transportDetailCost,
                                'Markup' => (float) $transportDetailMarkup,
                                'TotalCost' => (float) ($transportDetailTotal + $GSTAmountTransport),
                                'IsActive' => 1,
                                'IsApplyTax' => 0,
                                'AdultCost' => (float) $transportAdultCost,
                                'ChildCost' => (float) $transportChildCost,
                                'IsTotalCostInPackage' => 1,
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonTransportData);
                        }
                        if ((int) $sightseeingDetailTotal > 0) {

                            $GSTAmountSightseeing = 0;
                            if ($arrGSTCalculations['TaxType'] == 1) {
                                $GSTAmountSightseeing = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($sightseeingDetailTotal, $arrGSTCalculations['TaxRate']);
                            }
                            if ($arrGSTCalculations['TaxType'] == 2) {
                                $GSTAmountSightseeing = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($sightseeingDetailMarkup, $arrGSTCalculations['TaxRate']);
                            }

                            $addonSightseeingData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 9,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Sightseeing',
                                'AdultCount' => !empty($postData['totalAdult']) ? (float) $postData['totalAdult'] : 0,
                                'ChildCount' => !empty($postData['totalChild']) ? (float) $postData['totalChild'] : 0,
                                'InfentCount' => !empty($postData['totalInfant']) ? (float) $postData['totalInfant'] : 0,
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => $GSTApplicableOn,
                                'Tax' => $GSTAmountSightseeing,
                                'Cost' => (float) $sightseeingDetailCost,
                                'Markup' => (float) $sightseeingDetailMarkup,
                                'TotalCost' => (float) ($sightseeingDetailTotal + $GSTAmountSightseeing),
                                'IsActive' => 1,
                                'IsApplyTax' => 0,
                                'AdultCost' => (float) $sightseeingAdultCost,
                                'ChildCost' => (float) $sightseeingChildCost,
                                'InfantCost' => (float) $sightseeingInfantCost,
                                'IsTotalCostInPackage' => 1,
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonSightseeingData);
                        }
                        if ((int) $mealDetailTotal > 0) {
                                 
                            $GSTAmountMeal = 0;
                            if ($arrGSTCalculations['TaxType'] == 1) {
                                $GSTAmountMeal = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($sightseeingDetailTotal, $arrGSTCalculations['TaxRate']);
                            }
                            if ($arrGSTCalculations['TaxType'] == 2) {
                                $GSTAmountMeal = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($sightseeingDetailMarkup, $arrGSTCalculations['TaxRate']);
                            }

                            $addonMealData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 10,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Meal',
                                'AdultCount' => !empty($postData['totalAdult']) ? (float) $postData['totalAdult'] : 0,
                                'ChildCount' => !empty($postData['totalChild']) ? (float) $postData['totalChild'] : 0,
                                'InfentCount' => !empty($postData['totalInfant']) ? (float) $postData['totalInfant'] : 0,
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => $GSTApplicableOn,
                                'Tax' => $GSTAmountMeal,
                                'Cost' => (float) $mealDetailCost,
                                'Markup' => (float) $mealDetailMarkup,
                                'TotalCost' => (float) ($mealDetailTotal + $GSTAmountMeal),
                                'IsActive' => 1,
                                'IsApplyTax' => 0,
                                'AdultCost' => (float) $mealAdultCost,
                                'ChildCost' => (float) $mealChildCost,
                                'InfantCost' => (float) $mealInfantCost,
                                'IsTotalCostInPackage' => 1,
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonMealData);
                        }

                        $adMarkup = (isset($postData['op' . $optionKey . 'Mark_Up']) && $postData['op' . $optionKey . 'Mark_Up'] > 0) ? (int) $postData['op' . $optionKey . 'Mark_Up'] : 0;
                        $addonPackageData = [
                            'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                            'TPSysId' => (int) $tpproposalID,
                            'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                            'SupplierSysId' => (int) $SupplierSysId,
                            'PlanType' => 5,
                            'InvnSysId' => 0,
                            'ServiceTitle' => 'Package',
                            'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                            'GSTTYPE' => $GSTApplicableOn,
                            'Tax' => (float) $FullServiceTax,
                            'Cost' => (float) $Total_Price,
                            'Markup' => (float) $adMarkup,
                            'TotalCost' => (float) ($Total_Price + $adMarkup + $FullServiceTax),
                            'IsActive' => 1,
                            'IsApplyTax' => (isset($IsPackageTCS) && $IsPackageTCS == 1) ? 1 : 0,
                        ];

                        $saveAddonServicesData = $objPackage->saveAddonServicesData($addonPackageData);

                        if ($isShareWithFlight == 1) { // share with flight
                            $addonFlightData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => (int) $flightSupplierSysId,
                                'PlanType' => 1,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Flight',
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => ($flightDetailGst > 0) ? $flightDetailGst : 0,
                                'Tax' => (int) ((float) $flightDetailTotal - (float) $flightDetailCost - (float) $flightDetailMarkup),
                                'Cost' => ($flightDetailCost > 0) ? $flightDetailCost : 0,
                                'Markup' => (float) $flightDetailMarkup,
                                'TotalCost' => (int) $flightDetailTotal,
                                'IsActive' => 1,
                                'IsApplyTax' => (isset($IsFlightTCS) && $IsFlightTCS == 1) ? 1 : 0,
                                'ShareCombined' => ($IsShareCombinedFlightPricing) ? $IsShareCombinedFlightPricing : 0,
                            ];

                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonFlightData);
                        }

                        if ($isShareWithVisa == 1) {

                            $VisaAdultCost = (isset($postData['op' . $optionKey . 'VisaAdultCost'])) ? $postData['op' . $optionKey . 'VisaAdultCost'] : 0;
                            $VisaChildCost = isset($postData['op' . $optionKey . 'VisaChildCost']) ? $postData['op' . $optionKey . 'VisaChildCost'] : 0;
                            $VisaInfantCost = isset($postData['op' . $optionKey . 'VisaInfantCost']) ? $postData['op' . $optionKey . 'VisaInfantCost'] : 0;
                            $VisaCost = isset($postData['op' . $optionKey . 'VisaCost']) ? $postData['op' . $optionKey . 'VisaCost'] : 0;
                            $VisaMarkup = isset($postData['op' . $optionKey . 'VisaMarkup']) ? $postData['op' . $optionKey . 'VisaMarkup'] : 0;
                            $pricingGSTVisa = isset($postData['option' . $optionKey . 'pricingGSTVisa']) ? $postData['option' . $optionKey . 'pricingGSTVisa'] : 0;
                            $VisaCostTotal = isset($postData['op' . $optionKey . 'VisaCostTotal']) ? $postData['op' . $optionKey . 'VisaCostTotal'] : 0;

                            $saveVisaDataArray = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => $tpproposalID,
                                'CustomerSysId' => trim($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => (isset($visa_supplier_type_id) && (int) $visa_supplier_type_id > 0) ? (int) $visa_supplier_type_id : (int) $SupplierSysId,
                                'PlanType' => 6,
                                'InvnSysId' => $lasttravelitenaryID,
                                'ServiceTitle' => 'Visa',
                                'Comment' => '',
                                'AdultCount' => !empty($postData['totalAdult']) ? (float) $postData['totalAdult'] : 0,
                                'ChildCount' => !empty($postData['totalChild']) ? (float) $postData['totalChild'] : 0,
                                'InfentCount' => !empty($postData['totalInfant']) ? (float) $postData['totalInfant'] : 0,
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => (int) $pricingGSTVisa,
                                'AdultCost' => !empty($VisaAdultCost) ? (float) $VisaAdultCost : 0,
                                'ChildCost' => !empty($VisaChildCost) ? (float) $VisaChildCost : 0,
                                'InfantCost' => !empty($VisaInfantCost) ? (float) $VisaInfantCost : 0,
                                'Markup' => $VisaMarkup,
                                'Cost' => $VisaCost,
                                'TotalCost' => $VisaCostTotal,
                                'Tax' => (int) ($VisaCostTotal - $VisaCost - $VisaMarkup),
                                'IsActive' => 1,
                                'IsMarkForDelete' => 0,
                                'CreateDate' => date('Y-m-d'),
                                'UpdateDate' => date('Y-m-d'),
                                'IsApplyTax' => (isset($IsVisaTCS) && $IsVisaTCS == 1) ? 1 : 0,
                                'ShareCombined' => ($IsShareCombinedVisaPricing) ? $IsShareCombinedVisaPricing : 0,
                            ];
                            $visaData = array(
                                'TPIntSysId' => $lasttravelitenaryID,
                                'SeqId' => 1,
                                'VisaSysId' => 0,
                                'XrefInvnItemSysId' => 0,
                                'Title' => '',
                                'VisaValidity' => 0,
                                'VisaDuration' => 0,
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'AgentSysId' => $this->intLoggedinUserId,
                                'RoomInfoJson' => json_encode($roomjsonArr),
                                'CreateDate' => date('Y-m-d'),
                                'UpdateDate' => date('Y-m-d'),
                                'FromDate' => !empty($fromdate) ? $fromdate : '',
                                'ToDate' => !empty($todate) ? $todate : '',
                                'NetCost' => $VisaCostTotal,
                                'Cost' => $VisaCost,
                                'Markup' => $VisaMarkup,
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'SupplierSysId' => (isset($visa_supplier_type_id) && (int) $visa_supplier_type_id > 0) ? (int) $visa_supplier_type_id : (int) $SupplierSysId,
                                'IsMarkForDelete' => 0,
                                'IsActive' => 1,
                            );
                            try {
                                $objPackage->insertData("TB_Agency_Customer_TravelPlan_Visa", $visaData);
                                $saveAddonServicesData = $objPackage->saveAddonServicesData($saveVisaDataArray);
                            } catch (Exception $error) {
                                $error->getMessage();
                                file_content_put("error/package_quick_visa_" . time() . '.txt', $error->getMessage());
                            }
                        }

                        $TotalCostForTCS = 0;
                        if ($IsVisaTCS == 1) {

                            $TotalCostForTCS = $TotalCostForTCS + (isset($VisaCostTotal) ? (int) $VisaCostTotal : 0);
                        }
                        if ($IsFlightTCS == 1) {
                            $TotalCostForTCS = $TotalCostForTCS + (isset($flightDetailTotal) ? (int) $flightDetailTotal : 0);
                        }
                        if ($IsPackageTCS == 1) {
                            $TotalCostForTCS = $TotalCostForTCS + $Total_Cost_with_GST;
                        }
                        if ((int) $TotalCostForTCS > 0) {
                            $TcsTaxSysId = 5;
                            $tcscost = round(($TotalCostForTCS * $TcsTaxSysId / 100), 2);
                            $costwithtcs = $TotalCostForTCS + $tcscost;
                            $addonTcsData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 25,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'TCS Show',
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => (float) $TcsTaxSysId,
                                'Tax' => $tcscost,
                                'Cost' => $TotalCostForTCS,
                                'TotalCost' => (float) $costwithtcs,
                                'IsActive' => 0,
                                'displayTCS' => (int) $displayTCS,
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonTcsData);
                            $tcscost = $Advance_Tcs;
                            $costwithtcs = $TotalCostForTCS + $tcscost;
                            $addonTcsShowData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 21,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'TCS',
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => (float) $TcsTaxSysId,
                                'Tax' => $tcscost,
                                'Cost' => $TotalCostForTCS,
                                'TotalCost' => (float) $costwithtcs,
                                'IsActive' => ($tcscost > 0) ? 1 : 0,
                                'displayTCS' => (int) $displayTCS,
                            ];
                            $saveAddonServicesShowData = $objPackage->saveAddonServicesData($addonTcsShowData);
                        }
                        if ((int) $ServiceFee > 0) {
                            $arrInputDataS = array(
                                "GSTApplicableOn" => $GSTApplicableOn,
                                "intProductType" => 9,
                                "intProductGeoType" => 1,
                                "Cost" => $ServiceFee,
                                "AgencyMarkUp" => 0,
                                "AgencyExtraMarkUp" => 0,
                                "AgencyDiscount" => 0
                            );
                            $arrGSTCalculationsS = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputDataS);
                            $addonServiceData = [
                                'AgencySysId' => (int) $travelplandata[0]['AgencySysId'],
                                'TPSysId' => (int) $tpproposalID,
                                'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                'SupplierSysId' => 0,
                                'PlanType' => 22,
                                'InvnSysId' => 0,
                                'ServiceTitle' => 'Service Fee',
                                'CurrencyType' => isset($CurrencyType) ? $CurrencyType : '1',
                                'GSTTYPE' => $GSTApplicableOn,
                                'Tax' => (int) $arrGSTCalculationsS['GSTAmount'],
                                'Cost' => (int) $ServiceFee,
                                'TotalCost' => (int) $arrGSTCalculationsS['AmountWithGST'],
                                'IsActive' => 0,
                                'displayTCS' => $ShareModifyRemark,
                                'Comment' => $ModificationRemark
                            ];
                            $saveAddonServicesData = $objPackage->saveAddonServicesData($addonServiceData);
                        }
                        if (!empty($promotionsData)) {
                            foreach ($promotionsData as $prKey => $prValue) {
                                $savePromotionsData = [
                                    'AgencySysId' => (int) $travelplandata[0]['AgencySysId'] ? (int) $travelplandata[0]['AgencySysId'] : 0,
                                    'TPSysId' => (int) $tpproposalID,
                                    'CustomerSysId' => (int) ($travelplandata[0]['CustomerSysId']),
                                    'PlanType' => 5,
                                    'InvnSysId' => $prValue['InvnSysId'],
                                    'PromotionTitle' => $prValue['PromotionTitle'],
                                    'PromotionCode' => $prValue['PromotionCode'],
                                    'Comment' => $prValue['Comment'],
                                    'PromotionType' => $prValue['PromotionType'],
                                    'PromotionValue' => $prValue['PromotionValue'],
                                    'PromotionSysId' => $prValue['PromotionSysId'],
                                    'IsActive' => 1,
                                ];
                                $PromotionSaveData = $objPackage->savePromotionsData($savePromotionsData);
                            }
                        }
                        //                        echo "<pre>";print_r($PromotionSaveData);die('here');
                    }

                    $expectedClosureData = [
                        'ExpectedClosureDate' => $main_trip_departuredate,
                        'ExpectedValue' => (float) $NetPriceN,
                    ];
                    if ($HotelVoucherStatus > 0) {
                        $expectedClosureData['HotelVoucherStatus'] = 0;
                    }
                    if ($isShareWithFlight > 0) {
                        $expectedClosureData['FlightVoucherStatus'] = 0;
                    }
                    if ($SightseeingVoucherStatus > 0) {
                        $expectedClosureData['SightseeingVoucherStatus'] = 0;
                    }

                    if ($TransferVoucherStatus > 0) {
                        $expectedClosureData['TransferVoucherStatus'] = 0;
                    }
                    if ($isShareWithVisa > 0) {
                        $expectedClosureData['VisaVoucherStatus'] = 0;
                    }
                    $this->_crmcusttravelplan->expectedClosureData($tpproposalID, $expectedClosureData);
                }
            }
            if ($tpproposalID > 0) {
                $enctpproposalID = base64_encode($tpproposalID);
                $secureCode = Catabatic_ValidateCustomer::secureCode($enctpproposalID, 1);
                $booknowurl = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . $enctpproposalID . '/code/' . $secureCode;
                $AgentSysId = $this->intLoggedinUserId;
                $agentDetails = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
                $booknowurl1 = $booknowurl;
                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);
                }
                if ($postData['submitType'] == 'save') {
                    $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
                    $firstname = $sessionLogin_user->FirstName ? $sessionLogin_user->FirstName . ' ' . $sessionLogin_user->LastName : 'Agent';
                    $primarycontact = $sessionLogin_user->ContactNo1 ? $sessionLogin_user->ContactNo1 : 'N/A';
                    $agencyDisplayName = trim($sessionLogin_user->agencyDetails['DisplayName']);
                    $PrimaryEmail = trim($sessionLogin_user->agencyDetails['PrimaryEmail']);
                    $sendersEmailId = trim($sessionLogin_user->EmailId);
                    $agencyDisplayName = (!empty($agencyDisplayName)) ? $agencyDisplayName : trim($sessionLogin_user->agencyDetails['Title']);
                    $Logo = $sessionLogin_user->Logo;
                    $CurrSymbol = 'INR';
                    $sentprice = $CurrSymbol . ' ' . round($postData['TotalCost']); //totall cost
                    $path = SITE_FULL_URL . 'public/assets/images';
                    $pathAgency = SITE_FULL_URL . 'public/upload/media/agency/' . $this->intLoggedinUserAgencySysId;
                    if (isset($Logo) && $Logo != '') {
                        $AgencyLogo = $pathAgency . '/' . $Logo;
                    } else {
                        $AgencyLogo = $path . '/gtx-logo-white.png';
                    }
                    $objAgency = new Travel_Model_TblAgency();
                    $getBankDetails = $objAgency->getBankDetailsByAgency($this->intLoggedinUserAgencySysId);
                    $aboutpackage = !empty($postData['EmailContent']) ? $postData['EmailContent'] : '';
                    $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                    $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpproposalID); // get proposal data from customer travel plan
                    $params['IsFromGTXNetwork'] = 0;
                    $params['packageID'] = $tpproposalID;
                    $params['intLoggedinUserAgencySysId'] = $this->intLoggedinUserAgencySysId;
                    $params['agency_logo'] = $AgencyLogo;
                    $params['trip_address'] = $destinatioPlaces;
                    $params['shared_url'] = $booknowurl;
                    $params['sent_price'] = $sentprice; //total price with currency
                    $params['price'] = $postData['OverallPackageCost']; // total price
                    $params['travelers'] = array('Adults' => $totaladult, 'Child' => $totalchild, 'Infants' => $totalInfant); // travelers to display
                    $params['cust_name'] = $cust_name;
                    $params['about_package'] = $aboutpackage;
                    $params['agent_firstname'] = $firstname;
                    $params['agent_primarycontact'] = $primarycontact;
                    $params['file_path_location'] = $path;
                    $params['sendersEmailId'] = $sendersEmailId;
                    $params['agencyDisplayName'] = $agencyDisplayName;
                    $params['b2bagencyDisplayName'] = (isset($travelplandata[0]['CompanyName'])) ? $travelplandata[0]['CompanyName'] : '';
                    $params['PrimaryEmail'] = $PrimaryEmail;
                    $params['TPSysId'] = $tpproposalID;
                    $params['AgentSysId'] = $AgentSysId;
                    $params['AgencySysId'] = $sessionLogin_user->intLoggedinUserAgencySysId;
                    $params['PackageArray'] = @$transactiontravelplandata[0];
                    $params['agentDetails'] = $agentDetails;
                    $params['BankDetails'] = $getBankDetails;
                    $params['CompanyAddress'] = trim($sessionLogin_user->agencyDetails['CompanyAddress']);
                    $params['IsSMSApi'] = $this->IsSMSApi;
                    $subject = 'Proposal Details';
                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $params['arrEmailStatisticsType'] = $arrEmailStatisticsType[0];
                    //$getcustomerdetails = $this->_crmcustomerObj->GetCustomerDetailsByEmail(trim($ProposalEmailTo), $params['AgencySysId']);
                    $params['customer_contact'] = trim($travelplandata[0]['Contacts']);
                    $params['customer_countrycode'] = trim($travelplandata[0]['countrycode']);
                    $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendProposalToCustomer($ProposalEmailTo, $subject, $params);
                    if ($params['customer_contact'] != '') {
                        $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
                        $params['arrSMSStatisticsType'] = $arrSMSStatisticsType[0];
                        // $smsStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->SendSmsToCustomer($params);
                    }
                    $this->_redirect($booknowurl1);
                    exit;
                } else if ($postData['submitType'] == 'view') {
                    $this->_redirect($booknowurl1);
                    exit;
                } else {
                    $this->_redirect('/packagesearch/buildquickpackage/id/' . $enctpproposalID . '/code/' . $secureCode);
                    exit;
                }
            } else {
                $this->_redirect($_SERVER['HTTP_REFERER']);
                exit;
            }
        }
    }

    public function SetFlightData($Data, $postData) {
        if (!empty($Data)) {
            $TPSysId = (isset($postData['TPSysId']) && !empty($postData['TPSysId'])) ? (int) $postData['TPSysId'] : 0;
            $ProposalTPSysId = (isset($postData['ProposalTPSysId']) && !empty($postData['ProposalTPSysId'])) ? (int) $postData['ProposalTPSysId'] : 0;
            $flightType = (isset($postData['flightType']) && !empty($postData['flightType'])) ? (int) $postData['flightType'] : 1;
            $textbased = (isset($postData['textbased']) && !empty($postData['textbased'])) ? (int) $postData['textbased'] : 0;
            $BookingDataAPI = (isset($postData['BookingDataAPI']) && !empty($postData['BookingDataAPI'])) ? json_decode($postData['BookingDataAPI'], 1) : [];
            // echo "<pre>";
            // print_r(($flightType));
            // echo "<pre>";
            // print_r(($textbased));
            // echo "<pre>";
            // print_r(($BookingDataAPI));
            // die;
            if ($ProposalTPSysId > 0) {
                $QueryID = $ProposalTPSysId;
                $PropType = '';
            } else {
                $QueryID = $TPSysId;
                $PropType = 'Query';
            }
            $TempBookingData = [];
            $objAirport = new Travel_Model_TblAirport();
            $invBookingID = $searchID = 'GTX' . floor(microtime(true) * 1000);
            try {

                foreach ($Data as $keFl => $value) {

                    $supplier_type_id = (isset($value['supplier_type_id']) && !empty($value['supplier_type_id'])) ? (int) $value['supplier_type_id'] : 0;
                    $currencytype = (isset($value['currencyTypes']) && !empty($value['currencyTypes'])) ? (int) $value['currencyTypes'] : 1;
                    $Adult = (isset($value['adult_pax']) && !empty($value['adult_pax'])) ? (int) $value['adult_pax'] : 1;
                    $Child = (isset($value['child_pax']) && !empty($value['child_pax'])) ? (int) $value['child_pax'] : 0;
                    $Infant = (isset($value['infant_pax']) && !empty($value['infant_pax'])) ? (int) $value['infant_pax'] : 0;
                    $totalPax = ($Adult + $Child + $Infant);
                    $totalcost_wom = (isset($value['totalcost_wom']) && !empty($value['totalcost_wom'])) ? (float) $value['totalcost_wom'] : 0;
                    $adult_total = (isset($value['adult_total']) && !empty($value['adult_total'])) ? (float) $value['adult_total'] : 0;
                    $adult_cost_pp = (isset($value['adult_cost_pp']) && !empty($value['adult_cost_pp'])) ? (float) $value['adult_cost_pp'] : 0;
                    $child_cost_pp = (isset($value['child_cost_pp']) && !empty($value['child_cost_pp'])) ? (float) $value['child_cost_pp'] : 0;
                    $infant_cost_pp = (isset($value['infant_cost_pp']) && !empty($value['infant_cost_pp'])) ? (float) $value['infant_cost_pp'] : 0;
                    $child_total = (isset($value['child_total']) && !empty($value['child_total'])) ? (float) $value['child_total'] : 0;
                    $infant_total = (isset($value['infant_total']) && !empty($value['infant_total'])) ? (float) $value['infant_total'] : 0;

                    $adult_markup = (isset($value['adult_markup']) && !empty($value['adult_markup'])) ? (float) $value['adult_markup'] : 0;
                    $adult_gst = (isset($value['adult_gst']) && !empty($value['adult_gst'])) ? (float) $value['adult_gst'] : 0;

                    $total_markup = (isset($value['total_markup']) && !empty($value['total_markup'])) ? (float) $value['total_markup'] : 0;
                    $total_gst = (isset($value['total_gst']) && !empty($value['total_gst'])) ? (float) $value['total_gst'] : 0;

                    $child_markup = (isset($value['child_markup']) && !empty($value['child_markup'])) ? (float) $value['child_markup'] : 0;
                    $child_gst = (isset($value['child_gst']) && !empty($value['child_gst'])) ? (float) $value['child_gst'] : 0;

                    $infant_markup = (isset($value['infant_markup']) && !empty($value['infant_markup'])) ? (float) $value['infant_markup'] : 0;
                    $infant_gst = (isset($value['infant_gst']) && !empty($value['infant_gst'])) ? (float) $value['infant_gst'] : 0;

                    $BaseFare = (($adult_cost_pp * $Adult) + ($child_cost_pp * $Child) + ($infant_cost_pp * $Infant));
                    $OfferedFare = ($adult_total + $child_total + $infant_total);
                    $FixedMarkUp = ($total_markup);
                    $GSTOnMarkUp = ($total_gst);

                    $TCurrencyType = $currencytype;
                    $FCurrencyType = 1;
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getCurrencyRate($FCurrencyType, $TCurrencyType, $this->intLoggedinUserAgencySysId);
                    $ConvertionRate = 1; //isset($apiResponse['Rate']) ? $apiResponse['Rate'] : 1;
                    $Symbol = isset($apiResponse['Symbol']) ? $apiResponse['Symbol'] : 'INR';
                    $CurrencyId = isset($apiResponse['CurrencyId']) ? $apiResponse['CurrencyId'] : 1;

                    $FareBreakdown[0] = [
                        "Currency" => $Symbol,
                        "PassengerType" => 1,
                        "PaxType" => "ADULT",
                        "PassengerCount" => $Adult,
                        "BaseFare" => round($adult_cost_pp * $Adult),
                        "Tax" => 0,
                        "OfferedFare" => round(($adult_cost_pp * $Adult) + ($adult_markup * $Adult) + ($adult_gst * $Adult)),
                        "PublishedFare" => round(($adult_cost_pp * $Adult) + ($adult_markup * $Adult) + ($adult_gst * $Adult)),
                        "TDS" => 0,
                        "TDSEarn" => 0,
                        "TaxBR" => [
                            "MF" => 0,
                            "YQ" => 0,
                            "AGST" => 0,
                            "MFT" => 0,
                            "OT" => 0,
                            "YR" => 0
                        ],
                        "ApiNCM" => 0,
                        "CommissionEarned" => 0,
                        "FixedMarkUp" => round($adult_markup * $Adult),
                        "GSTOnMarkUp" => round($adult_gst * $Adult),
                        "CommDiscount" => 0,
                        "AgentMarkUp" => 0,
                        "Baggage" => isset($value['Baggage']) ? $value['Baggage'] : '',
                        "CabinBaggage" => isset($value['CabinBaggage']) ? $value['CabinBaggage'] : '',
                    ];

                    if ($Child > 0) {
                        $FareBreakdown[1] = [
                            "Currency" => $Symbol,
                            "PassengerType" => 2,
                            "PaxType" => "CHILD",
                            "PassengerCount" => $Child,
                            "BaseFare" => round($child_cost_pp * $Child),
                            "Tax" => 0,
                            "OfferedFare" => round(($child_cost_pp * $Child) + ($child_markup * $Child) + ($child_gst * $Child)),
                            "PublishedFare" => round(($child_cost_pp * $Child) + ($child_markup * $Child) + ($child_gst * $Child)),
                            "TDS" => 0,
                            "TDSEarn" => 0,
                            "TaxBR" => [
                                "MF" => 0,
                                "YQ" => 0,
                                "AGST" => 0,
                                "MFT" => 0,
                                "OT" => 0,
                                "YR" => 0
                            ],
                            "ApiNCM" => 0,
                            "CommissionEarned" => 0,
                            "FixedMarkUp" => round($child_markup * $Child),
                            "GSTOnMarkUp" => round($child_gst * $Child),
                            "CommDiscount" => 0,
                            "AgentMarkUp" => 0,
                            "Baggage" => isset($value['Baggage']) ? $value['Baggage'] : '',
                            "CabinBaggage" => isset($value['CabinBaggage']) ? $value['CabinBaggage'] : '',
                        ];
                    }
                    if ($Infant > 0) {
                        $FareBreakdown[2] = [
                            "Currency" => $Symbol,
                            "PassengerType" => 3,
                            "PaxType" => "INFANT",
                            "PassengerCount" => $Infant,
                            "BaseFare" => round($infant_cost_pp * $Infant),
                            "Tax" => 0,
                            "OfferedFare" => round(($infant_cost_pp * $Infant) + ($infant_markup * $Infant) + ($infant_gst * $Infant)),
                            "PublishedFare" => round(($infant_cost_pp * $Infant) + ($infant_markup * $Infant) + ($infant_gst * $Infant)),
                            "TDS" => 0,
                            "TDSEarn" => 0,
                            "TaxBR" => [
                                "MF" => 0,
                                "YQ" => 0,
                                "AGST" => 0,
                                "MFT" => 0,
                                "OT" => 0,
                                "YR" => 0
                            ],
                            "ApiNCM" => 0,
                            "CommissionEarned" => 0,
                            "FixedMarkUp" => round($infant_markup * $Infant),
                            "GSTOnMarkUp" => round($infant_gst * $Infant),
                            "CommDiscount" => 0,
                            "AgentMarkUp" => 0,
                            "Baggage" => '',
                            "CabinBaggage" => '',
                        ];
                    }

                    $FairRules = [
                        "Currency" => $Symbol,
                        "CurrencyRate" => $ConvertionRate,
                        "currencySysId" => $CurrencyId,
                        "BaseFare" => $BaseFare,
                        "Tax" => 0,
                        "intPublishedFare" => round(($OfferedFare)),
                        "PublishedFare" => round(($OfferedFare)),
                        "PublishedFareAgent" => round(($OfferedFare)),
                        "PublishedFarePerPax" => round(($OfferedFare) / $totalPax),
                        "OfferedFare" => $OfferedFare,
                        "CommissionEarned" => 0,
                        "CommDiscount" => 0,
                        "TDS" => 0,
                        "TDSEarn" => 0,
                        "Refundable" => 0,
                        "IsRefundableTxt" => "Non-Refundable",
                        "PriceID" => "",
                        "classOfBooking" => "",
                        "FareClass" => isset($value['FareClass']) ? $value['FareClass'] : '',
                        "fareIdentifier" => "OFFLINE",
                        "IsSpecialReturn" => false,
                        "colors" => "#FF0000",
                        "SeatAvailable" => 0,
                        "FixedMarkUp" => $FixedMarkUp,
                        "GSTOnMarkUp" => $GSTOnMarkUp,
                        "AgentMarkUp" => 0,
                        "IscheckinBagInc" => true,
                        "IscabinbagInc" => true,
                        "CheckinBaggage" => isset($value['Baggage']) ? $value['Baggage'] : '',
                        "CabinBaggage" => isset($value['CabinBaggage']) ? $value['CabinBaggage'] : '',
                        "IsMealIncludes" => false,
                        "FareBreakdown" => $FareBreakdown,
                        "tripbinfo" => []
                    ];

                    $source_place_Code = (isset($value['source_place_Code']) && !empty($value['source_place_Code'])) ? $value['source_place_Code'] : '';
                    $destination_place_Code = (isset($value['destination_place_Code']) && !empty($value['destination_place_Code'])) ? $value['destination_place_Code'] : '';
                    $stops = (isset($value['stops']) && !empty($value['stops'])) ? $value['stops'] : 0;
                    $FlightNo = (isset($value['FlightNo']) && !empty($value['FlightNo'])) ? $value['FlightNo'] : '';
                    $AirlineName = (isset($value['AirlineName']) && !empty($value['AirlineName'])) ? $value['AirlineName'] : '';
                    $depaartureTime = (isset($value['depaartureTime']) && !empty($value['depaartureTime'])) ? $value['depaartureTime'] : '';
                    $depaartureDate = (isset($value['depaartureDate']) && !empty($value['depaartureDate'])) ? $value['depaartureDate'] : '';
                    $arrivalTime = (isset($value['arrivalTime']) && !empty($value['arrivalTime'])) ? $value['arrivalTime'] : '';
                    $arrivalDate = (isset($value['arrivalDate']) && !empty($value['arrivalDate'])) ? $value['arrivalDate'] : '';
                    $strDepatureDate = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($depaartureDate, 'd/m/y');
                    $strReturnDate = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($arrivalDate, 'd/m/y');
                    $DDateTime = $strDepatureDate . ' ' . $depaartureTime;
                    $ADateTime = $strReturnDate . ' ' . $arrivalTime;
                    $Duration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->CalculateTotalTime($DDateTime, $ADateTime);
                    $flightnumberEX = explode('-', $FlightNo);
                    $AirlineCode = isset($flightnumberEX[0]) ? $flightnumberEX[0] : '';
                    $filePath = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getflightlogo($AirlineCode);
                    $from = $source_place_Code;
                    $to = $destination_place_Code;
                    $objAirport->strAirportCode = $from;
                    $arrSourceCityId = $objAirport->getAirportList();
                    $objAirport->strAirportCode = $to;
                    $arrdestinationCityId = $objAirport->getAirportList();

                    $AirportTitle = isset($arrSourceCityId[0]['AirportTitle']) ? trim($arrSourceCityId[0]['AirportTitle']) : '';
                    $CountryName = isset($arrSourceCityId[0]['CountryName']) ? trim($arrSourceCityId[0]['CountryName']) : '';
                    $CityName = isset($arrSourceCityId[0]['CityName']) ? trim($arrSourceCityId[0]['CityName']) : '';
                    $CountryCode = isset($arrSourceCityId[0]['CountryCode']) ? trim($arrSourceCityId[0]['CountryCode']) : '';

                    $AirportTitledest = isset($arrdestinationCityId[0]['AirportTitle']) ? trim($arrdestinationCityId[0]['AirportTitle']) : '';
                    $CountryNamedest = isset($arrdestinationCityId[0]['CountryName']) ? trim($arrdestinationCityId[0]['CountryName']) : '';
                    $CityNamedest = isset($arrdestinationCityId[0]['CityName']) ? trim($arrdestinationCityId[0]['CityName']) : '';

                    $intOriginCountryCode = trim($arrSourceCityId[0]['CountryCode']);
                    $intDestinaionCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
                    if ($intOriginCountryCode != "IN" || empty($intOriginCountryCode)) {
                        $interNationalSearch = true;
                    } else if ($intDestinaionCountryCode != "IN" || empty($intDestinaionCountryCode)) {
                        $interNationalSearch = true;
                    } else {
                        $interNationalSearch = false;
                    }


                    $Segment = [[
                    "segmentid" => 0,
                    "isReturnSegment" => $keFl,
                    "arrivingnextday" => false,
                    "originAirportName" => $AirportTitle,
                    "destinationAirportName" => $AirportTitledest,
                    "originCityName" => $CityName,
                    "originCountryName" => $CountryName,
                    "destinationCityName" => $CityNamedest,
                    "destinationCountryName" => $CountryNamedest,
                    "destinationAirportCode" => $to,
                    "destinationArrTime" => $ADateTime,
                    "SegFlightNumber" => $FlightNo,
                    "AirlineCode" => $AirlineCode,
                    "AirlineName" => $AirlineName,
                    "FareClass" => "",
                    "cabinClass" => isset($value['FareClass']) ? $value['FareClass'] : '',
                    "originAirportCode" => $from,
                    "originDepTime" => $DDateTime,
                    "TripIndicator" => false,
                    "IscheckinBagInc" => (isset($value['Baggage']) && !empty($value['Baggage'])) ? true : false,
                    "IscabinbagInc" => (isset($value['CabinBaggage']) && !empty($value['CabinBaggage'])) ? true : false,
                    "CheckinBaggage" => isset($value['Baggage']) ? $value['Baggage'] : '',
                    "CabinBaggage" => isset($value['CabinBaggage']) ? $value['CabinBaggage'] : '',
                    "IsMealIncludes" => false,
                    "Duration" => 110,
                    "StopPoint" => [],
                    "StopOver" => false,
                    "GroundTime" => 0,
                    "NoOfSeatAvailable" => 0,
                    "strDepartureDtTime" => $depaartureTime,
                    "strArrivalDtTime" => $arrivalTime,
                    "FlightDuration" => isset($value['duration']) ? $value['duration'] : '',
                    "LAYOVERDuration" => 0,
                    "LAYOVERCity" => "",
                    "DepTerminal" => "",
                    "ArrTerminal" => "",
                    "filePath" => $filePath,
                    ]];
                    $textbased = (isset($BookingDataAPI['textbased']) && !empty($BookingDataAPI['textbased'])) ? $BookingDataAPI['textbased'] : $textbased;
                    if ($textbased == 3) {
                        $FlightBookingData = (isset($BookingDataAPI['FlightBookingData'][$keFl]) && !empty($BookingDataAPI['FlightBookingData'][$keFl])) ? $BookingDataAPI['FlightBookingData'][$keFl] : [];
                        $Segment = (isset($FlightBookingData['Segments']) && !empty($FlightBookingData['Segments'])) ? $FlightBookingData['Segments'] : $Segment;
                    }

                    $FlightData = [
                        "bookingId" => $invBookingID,
                        "APIBookingId" => $invBookingID,
                        "ApiResultIndex" => "",
                        "FlightNumber" => $FlightNo,
                        "SegFlightNumberArr" => $FlightNo,
                        "AirlineName" => $AirlineName,
                        "AirlineCode" => $AirlineCode,
                        "IsLCC" => true,
                        "SearchTraceId" => $invBookingID,
                        "SupplierSysId" => $supplier_type_id,
                        "IsRefundable" => 0,
                        "IsRefundableTxt" => "Non-Refundable",
                        "LocalFromTime" => $DDateTime,
                        "FromUTCTime" => $DDateTime,
                        "LocalToTime" => $ADateTime,
                        "ToUTCTime" => $ADateTime,
                        "FareClass" => isset($value['FareClass']) ? $value['FareClass'] : '',
                        "SourceAirportCode" => $from,
                        "DestAirportCode" => $to,
                        "FlightDuration" => isset($value['duration']) ? $value['duration'] : '',
                        "StopCount" => ($stops == 0) ? "Non-stop" : $stops . " stop",
                        "NoOfSeatAvailable" => 0,
                        "logo" => $filePath,
                        "JourneyType" => count($Data),
                        "TripType" => ($keFl + 1),
                        "ICSourceSysId" => 9,
                        "IsInternational" => $interNationalSearch,
                        "IsPassMandatory" => false,
                        "IsPassExpiry" => false,
                        "IsPassIssue" => false,
                        "IsPassDateOfBirth" => false,
                        "isGSTMandatory" => false,
                        "isDobAdult" => false,
                        "isDobChild" => false,
                        "isDobInfant" => true,
                        "isSeatAppli" => true,
                        "isHoldAllowed" => true,
                        "isDocIdAllowedMandatory" => false,
                        "isDocIdAllowedAplicable" => false,
                        "FairRules" => $FairRules,
                        "Segments" => $Segment,
                    ];

                    $TempBookingData[] = $FlightData;
                }
                $currencytype = (isset($Data[0]['currencyTypes']) && !empty($Data[0]['currencyTypes'])) ? (int) $Data[0]['currencyTypes'] : 1;
                $adultCount = (isset($Data[0]['adult_pax']) && !empty($Data[0]['adult_pax'])) ? (int) $Data[0]['adult_pax'] : 1;
                $childCount = (isset($Data[0]['child_pax']) && !empty($Data[0]['child_pax'])) ? (int) $Data[0]['child_pax'] : 0;
                $infantCount = (isset($Data[0]['infant_pax']) && !empty($Data[0]['infant_pax'])) ? (int) $Data[0]['infant_pax'] : 0;

                $CurrencyRate = isset($TempBookingData[0]['FairRules']['CurrencyRate']) ? $TempBookingData[0]['FairRules']['CurrencyRate'] : '';
                $SourceAirportCode = $oneway_origin_text = isset($TempBookingData[0]['SourceAirportCode']) ? $TempBookingData[0]['SourceAirportCode'] : '';
                $DestAirportCode = $oneway_destination_text = isset($TempBookingData[0]['DestAirportCode']) ? $TempBookingData[0]['DestAirportCode'] : '';
                $return_dates_string = isset($TempBookingData[1]['FromUTCTime']) ? $TempBookingData[1]['FromUTCTime'] : '';
                $objAirport = new Travel_Model_TblAirport();
                $objAirport->strAirportCode = $SourceAirportCode;
                $arrSourceCityId = $objAirport->getAirportList();
                $objAirport->strAirportCode = $DestAirportCode;
                $arrdestinationCityId = $objAirport->getAirportList();

                $sourceCityId = isset($arrSourceCityId[0]['CityId']) ? $arrSourceCityId[0]['CityId'] : 0;
                $destinationCityId = isset($arrdestinationCityId[0]['CityId']) ? $arrdestinationCityId[0]['CityId'] : 0;
                $UserSysId = 0;
                $MasterAgencySysId = $this->intLoggedinUserAgencySysId;

                $GetTravelPlanType = $this->_crmcusttravelplan->GetTravelPlanType($QueryID, $PropType);
                $CustomerSysId = isset($GetTravelPlanType['CustomerSysId']) ? $GetTravelPlanType['CustomerSysId'] : 0;
                $IsB2BProposal = isset($GetTravelPlanType['IsB2BProposal']) ? $GetTravelPlanType['IsB2BProposal'] : 0;
                $AgentSysId = isset($GetTravelPlanType['AgentSysId']) ? $GetTravelPlanType['AgentSysId'] : 0;
                $AgencySysId = isset($GetTravelPlanType['AgencySysId']) ? $GetTravelPlanType['AgencySysId'] : 0;
                $editLeadId = isset($GetTravelPlanType['query_id']) ? $GetTravelPlanType['query_id'] : 0;

                $totalPax = ($Adult + $Child + $Infant);
                $FlightBookingDataRiya = array(
                    "FlightBookingData" => $TempBookingData,
                    "customer" => [],
                    "roominfojson" => [],
                    "Cities" => $oneway_origin_text . '-' . $oneway_destination_text,
                    "IsHotelFromApi" => 1,
                    "ICSourceSysId" => 9,
                    'AgencySysId' => $MasterAgencySysId,
                    'AgentSysId' => $UserSysId,
                    "SourcePlaces" => $oneway_origin_text,
                    "DestinationPlaces" => $oneway_destination_text,
                    "SourcePlaceSysId" => $sourceCityId,
                    "DestinationPlacesSysId" => $destinationCityId,
                    "BaseAmount" => 0,
                    "PublishedFare" => 0,
                    "AgencyMarkUp" => 0,
                    "AgencyMarkUpGST" => 0,
                    "AgentCommisionEarned" => 0,
                    "AgentCommisionEarnedGST" => 0,
                    "adults" => $adultCount,
                    "childs" => $childCount,
                    "infants" => $infantCount,
                    "route" => count($Data),
                    "email" => isset($ProposalData[0]['EmailId']) ? $ProposalData[0]['EmailId'] : '',
                    "mobile" => isset($ProposalData[0]['Contacts']) ? $ProposalData[0]['Contacts'] : '',
                    "editLeadId" => $editLeadId,
                    "ProposalID" => $ProposalTPSysId,
                    "CustomerSysId" => $CustomerSysId,
                    'IsB2BQuery' => $IsB2BProposal,
                    'B2BAgentSysId' => $UserSysId,
                    'B2BAgencySysId' => $AgencySysId,
                    'leadsource' => 'Agency',
                    'IsB2BProposal' => $IsB2BProposal,
                    'IsforPackage' => 1,
                    'ExchangeCurrencyRate' => $CurrencyRate,
                    'APIMode' => 0,
                    'textbased' => $textbased,
                    'IsNewMigration' => 3,
                );

                return $FlightBookingDataRiya;
                // echo "<pre>";
                // print_r(($GetTravelPlanType));
                // echo "<pre>";
                // print_r(($FlightBookingDataRiya));
                // die;
            } catch (Zend_Exception $e) {
                print_r($e->getMessage());
                die;
            }
        }
    }

    public function getactivitybuildpckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        $CityId = $this->getRequest()->getParam('CityId');
        $destinationCovered = $this->getRequest()->getParam('destinationcovered');
        $obj = new Travel_Model_TblPackage();
        $result = $obj->getCityAllActivity($CityId, $this->intLoggedinUserAgencySysId, $destinationCovered);
        $htmldata = '';
        foreach ($result as $resultArr) {
            $title = preg_replace('/\s+/', ' ', $resultArr['Title']);
            $AgencySysId = $this->intLoggedinUserAgencySysId;
            $internalA = ($resultArr['ICSourceSysId'] == $AgencySysId) ? ' (Internal)' : '';
            $CityIdAct = ' (' . trim($resultArr['CityName']) . ', ' . trim($resultArr['Country']) . ') ';
            $htmldata .= '<option value="' . $resultArr['ActivitySysId'] . '__' . $title . '">' . trim($title) . $CityIdAct . $internalA . '</option>';
        }

        echo $htmldata;
        exit;
    }

    public function getasightseeingbuildpckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {
        $Params = $this->getRequest()->getParams();
        $IsShowRateText = isset($Params['IsShowRateText']) ? (int) $Params['IsShowRateText'] : 0;
        $WithCity = isset($Params['WithCity']) ? (int) $Params['WithCity'] : 0;
        $CityIdArr = $this->getRequest()->getParam('CityId');
        $destinationCovered = $this->getRequest()->getParam('destinationcovered');
        $destinationCovered = explode(',', $destinationCovered);
        if (!empty($CityIdArr) && (int) $CityIdArr[0] > 0) {

            $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        } else {
            $mergeCity = array_unique($destinationCovered);
        }



        // $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        //        $mergeCity = array_diff($mergeCity, [0]);
        $destinationCoveredId = implode(',', $mergeCity);
        $destinationCoveredId = rtrim($destinationCoveredId, ',');
        $CityId = $mergeCity[0];

        //$result = array();
        $htmldata = '';
        if ($CityId >= 1) {

            $obj = new Travel_Model_TblPackage();
            $result = $obj->getCityAllSightseeing($CityId, $this->intLoggedinUserAgencySysId, $destinationCoveredId);

            foreach ($result as $resultArr) {
                $title = preg_replace('/\s+/', ' ', $resultArr['Title']);
                $AgencySysId = $this->intLoggedinUserAgencySysId;
                $internalA = ($resultArr['ICSourceSysId'] == $AgencySysId) ? ' (Internal)' : '';
                if ($resultArr['IsRate'] == 1 && $IsShowRateText == 1) {
                    $internalA = ' (Internal with Rate)';
                }
                $CityIdAct = '(' . trim($resultArr['CityName']) . ', ' . trim($resultArr['Country']) . ') ';
                $CitySysId = (int) $resultArr['CitySysId'];

                if ($IsShowRateText == 1) {
                    $htmldata .= '<option value="' . $resultArr['SSSysId'] . '__' . trim($title) . '__' . $CitySysId . '" >' . trim($title) . ' ' . $CityIdAct . $internalA . '</option>';
                } else {
                    $htmldata .= '<option value="' . $resultArr['SSSysId'] . '__' . trim($title) . '__' . $CitySysId . '">' . trim($title) . ' ' . $CityIdAct . $internalA . '</option>';
                }
            }
        }
        echo $htmldata;
        exit;
        //        echo json_encode($result);exit;
        //}
    }

    public function getasightseeingbuildpcknewAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {

        $CityIdArr = $this->getRequest()->getParam('CityId');
        $destinationCovered = $this->getRequest()->getParam('destinationcovered');
        $destinationCovered = explode(',', $destinationCovered);
        if (!empty($CityIdArr) && (int) $CityIdArr[0] > 0) {

            $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        } else {
            $mergeCity = array_unique($destinationCovered);
        }



        // $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        //        $mergeCity = array_diff($mergeCity, [0]);
        $destinationCoveredId = implode(',', $mergeCity);
        $destinationCoveredId = rtrim($destinationCoveredId, ',');
        $CityId = $mergeCity[0];

        //$result = array();
        $htmldata = '';
        $htmldata1 = '';
        if ($CityId >= 1) {
            $obj = new Travel_Model_TblPackage();
            $result = $obj->getCityAllSightseeing($CityId, $this->intLoggedinUserAgencySysId, $destinationCoveredId);

            foreach ($result as $resultArr) {
                $title = preg_replace('/\s+/', ' ', $resultArr['Title']);
                $AgencySysId = $this->intLoggedinUserAgencySysId;
                $internalA = ($resultArr['ICSourceSysId'] == $AgencySysId) ? ' (Internal)' : '';
                $CityIdAct = ' (' . trim($resultArr['CityName']) . ', ' . trim($resultArr['Country']) . ') ';
                $htmldata .= '<option value="' . $resultArr['SSSysId'] . '__' . $title . '">' . trim($title) . $CityIdAct . $internalA . '</option>';
            }
            foreach ($result as $resultArr1) {
                $title = preg_replace('/\s+/', ' ', $resultArr1['Title']);
                $AgencySysId = $this->intLoggedinUserAgencySysId;
                $internalA = ($resultArr1['ICSourceSysId'] == $AgencySysId) ? ' (Internal)' : '';
                $CityIdAct = ' (' . trim($resultArr1['CityName']) . ', ' . trim($resultArr1['Country']) . ') ';
                $htmldata1 .= '<option value="' . $resultArr1['SSSysId'] . '">' . trim($title) . $CityIdAct . $internalA . '</option>';
            }
        }
        //        echo $htmldata;
        //        exit;
        //        $result = array('htmldata'=>$htmldata,'htmldata1'=>$htmldata1);
        echo ($htmldata1);
        exit;
        //}
    }

    public function getasightseeingraidymadepckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {

        $CityIdArr = $this->getRequest()->getParam('CityId');
        $terms = trim($this->getRequest()->getParam('term'));
        $destinationCovered = $this->getRequest()->getParam('destinationcovered');
        $fromDate = $this->getRequest()->getParam('fromDate');
        if ($fromDate == '') {
            $fromDate = date('d/m/Y');
        }
        $fromDate = explode('/', $fromDate);
        $fromDate = trim($fromDate[2] . '-' . $fromDate[1] . '-' . $fromDate[0]);
        $destinationCovered = explode(',', $destinationCovered);
        if (!empty($CityIdArr) && (int) $CityIdArr[0] > 0) {

            $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        } else {
            $mergeCity = array_unique($destinationCovered);
        }



        // $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        //        $mergeCity = array_diff($mergeCity, [0]);
        $destinationCoveredId = implode(',', $mergeCity);
        $destinationCoveredId = rtrim($destinationCoveredId, ',');
        $CityId = $mergeCity[0];

        //$result = array();
        $htmldata = '';
        if ($CityId >= 1) {
            $objSightseeing = new Travel_Model_TblSightseeing();
            $result = $objSightseeing->getSightseeingListWithPrice($CityId, $this->intLoggedinUserAgencySysId, $terms, $destinationCoveredId, $fromDate);
            //            echo "<pre>"; print_r($result); die;
            echo $this->_helper->json($result);
            exit;
        }
    }

    public function getaroomtypebuildpckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {
        $objHotel = new Travel_Model_TblHotel();
        $getMasterRoomType = $objHotel->getMasterRoomType();
        //echo "<pre>";print_r($result);die;
        echo json_encode($getMasterRoomType);
        exit;
        //}
    }

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

        $objPackage = new Travel_Model_PackageSearch();

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

            $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
            $sessionPackageFilterData = new Zend_Session_Namespace('sessionPackageFilterData');
            //            $sessionPackageSearchData->searchData = $getData;
            if (!empty($sessionPackageFilterData->filterData)) {
                $sessionPackageFilterData->filterData = array();
            }
            //echo "<pre>";print_r($sessionPackageSearchData->searchData);die;
            $customerID = (isset($sessionPackageSearchData->searchData['customerID']) && !empty($sessionPackageSearchData->searchData['customerID'])) ? $sessionPackageSearchData->searchData['customerID'] : $getData['customerID'];
            if (isset($customerID) && !empty($customerID)) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $getcustomerDetail = $this->_crmcustomerObj->GetCustomerWithDetails($customerID);
                $sessionLogin_lead_customer = new Zend_Session_Namespace('customerlead');
                $sessionLogin_lead_customer->customerID = $customerID;
                $sessionLogin_lead_customer->leadID = '';
                $sessionLogin_lead_customer->FirstName = $getcustomerDetail['FirstName'];
                $sessionLogin_lead_customer->EmailId = $getcustomerDetail['EmailId'];
                $sessionLogin_lead_customer->PrimaryContactNumber = $getcustomerDetail['Contacts'];
                $sessionPackageSearchData->searchData['customerID'] = $customerID;
                $sessionPackageSearchData->searchData['is_source'] = 'CRM';
                $sessionPackageSearchData->searchData['customerId'] = $customerID;
                $sessionPackageSearchData->searchData['FirstName'] = $getcustomerDetail['FirstName'];
                $sessionPackageSearchData->searchData['EmailId'] = $getcustomerDetail['EmailId'];
                $sessionPackageSearchData->searchData['PrimaryContactNumber'] = $getcustomerDetail['Contacts'];
                $sessionPackageSearchData->searchData['customerDetails'] = $getcustomerDetail;
            }

            //add history for search query created by Er Amit Kumar dubey on 11 april 2017 at 2:48 PM
            $this->_objPkg = new Travel_Model_PackageSearch();
            $packageThemeList = $this->_objPkg->getPackageThemeList();
            $packageInclList = $this->_objPkg->getPackageInclusionList();
            $foodPreferenceList = $this->_objPkg->getFoodPreferenceList();
            $tpintsysID = isset($getData['itenaryID']) ? $getData['itenaryID'] : '';
            $nooftraveler = $getData['travelers'];
            $search_going_to = $getData['search_going_to'];
            $get_cityname = isset($getData['multicities']) ? rtrim($getData['multicities'], ',') : '';
            $getcityvalue = @$getData['search_going_to_id'];
            $noofdaysto = @$getData['noofdaysto'];
            $currentOwnerSysId = isset($getData['currentOwnerSysId']) ? $getData['currentOwnerSysId'] : '';
            $roomjson = array();
            //$childcount = 1;

            $childsage = '';
            $TotAdultCount = 0;
            $TotChildCount = 0;
            $TotInfantCount = 0;
            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);

                $TotAdultCount += $roomjson[$k]['Adult'];
                $TotChildCount += $roomjson[$k]['Child'];
                $TotInfantCount += $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);
                }
                $roomjson[$k]['departuredate'] = $getData['search_specific_date'];
                $roomjson[$k]['returndate'] = '';
            }


            //            $sessionPackageSearchData->searchData['RoomMemInfoJson'] = json_encode($roomjson);
            if (!empty($search_going_to)) {
                $search_going_to_dest = explode('__', $search_going_to);
                $going_to_cityname = $search_going_to_dest[0];
                $going_to_cityid = $search_going_to_dest[1];
            }
            $going_to_cityid = trim($getData['search_going_to_city']);
            $search_going_from = isset($getData['search_going_from']) ? $getData['search_going_from'] : '';
            if (!empty($search_going_from)) {
                $search_going_to_source = explode('__', $search_going_from);
                $going_from_cityid = $search_going_to_source[0];
                $going_from_cityname = $search_going_to_source[1];
            }
            if (!empty($getData['search_theme'])) {
                $search_theme = $getData['search_theme'];
                for ($i = 0; $i < count($search_theme); $i++) {
                    $search_theme_list[] = $this->_crmcusttravelplan->searchForInclusionId($search_theme[$i], $packageThemeList, 'PackType');
                }
            }
            if (!empty($getData['search_inclusions'])) {
                $search_inclusion_array = $getData['search_inclusions'];
                for ($i = 0; $i < count($search_inclusion_array); $i++) {
                    $search_inclusion_list[] = $this->_crmcusttravelplan->searchForInclusionId($search_inclusion_array[$i], $packageInclList, 'InclId');
                }
            }
            if (!empty($getData['search_food'])) {
                $search_food = $getData['search_food'];
                for ($i = 0; $i < count($search_food); $i++) {
                    $search_food_list[] = $this->_crmcusttravelplan->searchForInclusionId($search_food[$i], $foodPreferenceList, 'CuisineSysId');
                }
            }
            $thememask = '';
            if (!empty($search_theme_list)) {
                $thememask = '1';
                $char = '';
                for ($k = 0; $k < count($packageThemeList); $k++) {
                    $char = in_array(@$packageThemeList[$k]['PackType'], @$search_theme_list) ? '1' : '0';
                    $thememask .= $char;
                }
            }
            $char = '';
            $inclmask = '';
            if (!empty($search_inclusion_list)) {
                $inclmask = '1';
                for ($k = 0; $k < count($packageInclList); $k++) {
                    $char = in_array(@$packageInclList[$k]['InclId'], @$search_inclusion_list) ? '1' : '0';
                    $inclmask .= $char;
                }
            }
            $char = '';
            $foodmask = '';
            if (!empty($search_food_list)) {
                $foodmask = '1';
                for ($k = 0; $k < count($foodPreferenceList); $k++) {
                    $char = in_array(@$foodPreferenceList[$k]['CuisineSysId'], @$search_food_list) ? '1' : '0';
                    $foodmask .= $char;
                }
            }
            $sessionPackageSearchData->searchData['PackTypeMask'] = $thememask;
            $sessionPackageSearchData->searchData['InclMask'] = $inclmask;
            $sessionPackageSearchData->searchData['CuisineMask'] = $foodmask;

            if (isset($getData['search_theme'])) {
                $PackTypeMask = $getData['search_theme'] ? $thememask : '';
            } else {
                $PackTypeMask = '';
            }
            if (isset($getData['search_inclusions'])) {
                $InclMask = $getData['search_inclusions'] ? $inclmask : '';
            } else {
                $InclMask = '';
            }
            if (!empty($getData['search_price_range'])) {
                $search_price_range = explode('__', @$getData['search_price_range']);
            }
            $min_price = $getData['search_price_range'] ? $search_price_range[0] : 0;
            $max_price = $getData['search_price_range'] ? $search_price_range[1] : 0;
            $createDate = date('Y-m-d H:i:s');
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $agencySysID = $sessionLogin_user->intLoggedinUserAgencySysId;
            $agentsysID = $sessionLogin_user->intLoggedinUserId;
            //  echo $DestinationPlaces;
            //echo "<pre>";print_r($getData);die;
            //print_r($sessionPackageSearchData->searchData);
            $IsB2BAgent = isset($sessionPackageSearchData->searchData['customerDetails']) ? $sessionPackageSearchData->searchData['customerDetails']['IsB2BAgent'] : 0;
            $getData['MarketPlaceId'] = ($IsB2BAgent == 1) ? 2 : 1;
            // $packageSearchResult = $objPackage->getPackageSearchData($getData);
            //$packageSearchResultF = $objPackage->getPackageSearchDataFixed($getData);
            $packageDynamicSearchResult = $objPackage->getDynamicPackageSearchData($getData);

            if ($sessionPackageSearchData->searchData['search_going_to'] == '') {
                echo json_encode(array('status' => 3, 'msg' => 'Please select destination city.'));
                exit;
            }


            $historyData = array(
                'TPSysId' => isset($getData['TPSysId']) ? $getData['TPSysId'] : 0,
                'AgencySysId' => $agencySysID,
                'AgentSysId' => $agentsysID,
                'CustomerSysId' => isset($customerID) ? $customerID : '',
                'PlanType' => 5,
                'SourcePlaces' => isset($going_from_cityname) ? trim($going_from_cityname) : '',
                'SourcePlaceSysId' => isset($going_from_cityid) ? $going_from_cityid : '',
                'DestinationPlaces' => isset($going_to_cityid) ? $going_to_cityid : '',
                'DestinationPlaceSysId' => isset($going_to_cityname) ? $going_to_cityname : '',
                'PackTypeMask' => $PackTypeMask,
                'InclusionMark' => $InclMask,
                'Rooms' => $getData['roomlp'],
                'TotAdultCount' => $TotAdultCount,
                'TotChildCount' => $TotChildCount,
                'TotInfantCount' => 0,
                'PriceRangeFrom' => $min_price,
                'PriceRangeTo' => $max_price,
                'AdditionalSrvMark' => '',
                'StartDate' => isset($plan_start_date) ? $plan_start_date : $createDate,
                'ValidTill' => isset($plan_enddate_date) ? $plan_enddate_date : $createDate,
                'Rating' => 0,
                "SearchDate" => $createDate,
                'UpdateDate' => $createDate,
                'IsActive' => 1,
                'IsMarkForDel' => 0,
            );
            $this->_crmcusttravelplanhistory = new Travel_Model_CRM_CustomerTravelPlanSearchHistory();
            $this->_crmcusttravelplanhistory->addCustomerTravelPlanSearchHistory($historyData);
            //end of search query history
            $lastencodeID = $getData['TPSysId'] ? base64_encode($getData['TPSysId']) : '';
            $secureCode = Catabatic_ValidateCustomer::secureCode($lastencodeID, 1);
            if (isset($packageSearchResult) && count($packageSearchResult) == 0 && count($packageDynamicSearchResult) == 0 && count($packageSearchResultF) == 0) {
                $objPackageNetwork = new Gtxnetwork_Model_PackageSearch();
                $readymadePackageSearchResult = $objPackageNetwork->getPackageSearchData($getData);
                $readymadePackageSearchResultFixed = $objPackageNetwork->getPackageSearchDataFixed($getData);
                $dynamicePackageSearchResultNetwork = $objPackageNetwork->getDynamicPackageSearchData($getData);
                // echo "<pre>";print_r($readymadePackageSearchResult);exit;
                if (!empty($dynamicePackageSearchResultNetwork) || !empty($readymadePackageSearchResult) || !empty($readymadePackageSearchResultFixed)) {
                    echo json_encode(array('status' => 1, 'msg' => ''));
                    exit;
                } else {
                    echo json_encode(array('status' => 2, 'msg' => 'No Package Found', 'lastencodeID' => $lastencodeID, 'code' => $secureCode));

                    exit;
                }


                echo json_encode(array('status' => 2, 'msg' => 'No Package Found', 'lastencodeID' => $lastencodeID, 'code' => $secureCode));

                exit;
            } else {
                echo json_encode(array('status' => 1, 'msg' => ''));
                exit;
                exit;
            }
        }
    }

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

        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $objPackage = new Travel_Model_PackageSearch();
            //print_r($getData['economyId']); die;
            $packageId = $getData['PackageId'];
            $customerID = $getData['customerID'];
            $network = isset($getData['network']) ? $getData['network'] : '0';
            //$hotelArr = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getHotels($packageId);
            $hotelArr = $objPackage->getSelectedPackageHotelListByPackageId($packageId);

            $jj = $sequesceIdPre = $cityIdPre = 0;
            foreach ($hotelArr as $key => $value) {
                $cityIdCurrennt = (int) $value['CityId'] . '-' . (int) $value['AccomSysId'] . '-' . (int) $value['RoomType'] . '-' . (int) $value['MealPlanType'];
                if ($cityIdCurrennt != $cityIdPre) {
                    $jj++;
                }
                $hotelData[$jj][$value['Sequence']]['HotelCount'] = $value['HotelCount'];
                $hotelData[$jj][$value['Sequence']]['TPIntSysId'] = $value['TPIntSysId'];
                $hotelData[$jj][$value['Sequence']]['Sequence'] = $value['Sequence'];
                $hotelData[$jj][$value['Sequence']]['CityId'] = $value['CityId'];
                $hotelData[$jj][$value['Sequence']]['CityName'] = $value['CityName'];
                $hotelData[$jj][$value['Sequence']]['HotelName'] = $value['HotelName'];
                $hotelData[$jj][$value['Sequence']]['Stars'] = $value['Stars'];
                $hotelData[$jj][$value['Sequence']]['EconomyTypeTitle'] = $value['EconomyTypeTitle'];
                $hotelData[$jj][$value['Sequence']]['MealPlanTypeTitle'] = $value['MealPlanTypeTitle'];
                $hotelData[$jj][$value['Sequence']]['AccomSysId'] = $value['AccomSysId'];
                $sequesceIdPre = $value['Sequence'];
                $cityIdPre = (int) $value['CityId'] . '-' . (int) $value['AccomSysId'] . '-' . (int) $value['RoomType'] . '-' . (int) $value['MealPlanType'];
            }
            //echo "<pre>";print_r($hotelArr);die;
            $objPackage = new Travel_Model_TblPackage();
            $customerDetails = array();
            if ($customerID > 0) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($customerID);
            }
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            if ($IsB2BCustomer == 1 || $network == 'Isnetwork') {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }
            $marketwiserateReadymade = $objPackage->GetMarketWiseRateBYOReadyMadeB2C($packageId, $MarketPlaceId);
            //            $objPackage = new Travel_Model_PackageSearch();
            //            $packageCityList = $objPackage->getPackageCities($packageId);
            //            
            //            $CitiesBySequenceArray = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getCitiesBySequence($packageCityList);
            //            $hotelArr = array();
            //                foreach ($CitiesBySequenceArray as $city) {
            //                    $packageTncList = $objPackage->getPackageHotel($packageId, $city[0],$city[2],$city[3]);
            //                    if(!empty($packageTncList)){
            //                    $hotelArr[] = @$packageTncList[0];
            //                    $hotelArr['startSequence'] = $city[2];
            //                    $hotelArr['endSequence'] = $city[3];
            //                    }
            //                }

            if ($network == 'Isnetwork') {
                $secureCode = Catabatic_ValidateCustomer::secureCode($marketwiserateReadymade['TPIntSysId'], 1);
            } else {
                $secureCode = Catabatic_ValidateCustomer::secureCode($marketwiserateReadymade['TPIntSysId'], 0);
            }
            $this->view->hotelData = isset($hotelData) ? $hotelData : array();
            $this->view->noofNight = $getData['noofNight'];
            $this->view->counterPAckage = $getData['counter'];
            $this->view->economyType = $getData['economyType'];
            $this->view->network = isset($getData['network']) ? $getData['network'] : '0';
            $this->view->secureCode = $secureCode;
            $this->view->marketwiserateReadymade = $marketwiserateReadymade;
        }
    }

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

        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $packageId = isset($getData['packageId']) ? $getData['packageId'] : '';
            $objPackage = new Travel_Model_PackageSearch();
            $packageSearchResult = $objPackage->getFlexiPackageActivityList($packageId);
            if (isset($packageSearchResult[0]["PackSpecType"]) && $packageSearchResult[0]["PackSpecType"] != 2) {
                $DaywiseActivityTitle = array();
                foreach ($packageSearchResult as $key => $value) {
                    $DaywiseActivityTitle[$value['Sequence']][$key] = $value['TPActivitySysId'] . '__' . ucfirst($value['Title']);
                }
                $this->view->Activites = $DaywiseActivityTitle;
            } else {
                $this->view->onlyHotelActivities = $packageSearchResult;
            }
        }
    }

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

        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $packageId = isset($getData['packageId']) ? $getData['packageId'] : '';
            $objPackage = new Travel_Model_PackageSearch();
            $packageSearchResult = $objPackage->getFlexiPackageSightseenList($packageId);
            if (isset($packageSearchResult[0]["PackSpecType"]) && $packageSearchResult[0]["PackSpecType"] != 2) {
                $DaywiseSightseenTitle = array();
                foreach ($packageSearchResult as $key => $value) {
                    $DaywiseSightseenTitle[$value['Sequence']][$key] = $value['SSSysId'] . '__' . ucfirst($value['Title']);
                }
                $this->view->Sightseeing = $DaywiseSightseenTitle;
            } else {
                $this->view->onlyHotelSightseeing = $packageSearchResult;
            }
        }
    }

    public function sendemailAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', false);
        $getData = $this->getRequest()->getPost();
        $objPackage = new Travel_Model_TblPackage();
        $flexiPackageList = $objPackage->getFlexiPackageList($getData['tpsysID']);
        $this->view->flexiPackageList = $flexiPackageList;
        //Get Package Places 
        $flexiPackagePlaces = $objPackage->getPackagePlacesList($getData['tpsysID']);
        $this->view->flexiPackagePlaces = $flexiPackagePlaces;
        //            for($k=1;$k<=$getData['roomlp'];$k++) {
        //               $roomjson[$k]['Adult']  = $getData['adult_'.@$k];
        //               $roomjson[$k]['Child']  = $getData['child_'.@$k];
        //               $roomjson[$k]['bedtype'] = $getData['extrabed_'.@$k];
        //            }
        //           $tpsysID = $getData['tpsysID']; 
        //           $roominfojson =  json_encode($roomjson);
        //           $sessionLogin_lead_customer = new Zend_Session_Namespace('customerlead');
        //           $lastID = $sessionLogin_lead_customer->leadID;
        //          
        //           $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        //           $searchResult = $sessionPackageSearchData->searchData;
        //           $gettravelplancost = $this->_crmcusttravelplan->GetTravelPlanCost($tpsysID,$roominfojson); 
        //           $getTravelplanEvents = $this->_crmcusttravelplan->GetTravelPlanEvents($tpsysID);
        //           $this->view->searchResults = $searchResult;
        //           $this->view->gettravelplancost = $gettravelplancost;
        //           $this->view->getTravelplanEvents = $getTravelplanEvents;
    }

    public function getCategoryForPopupAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $packageId = $getData['packageId'];
            $customerID = $getData['customerID'];
            $categoryResult = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getCategorywiseData($packageId);
            //print_r($categoryResult); 
            $this->view->categoryResult = $categoryResult;
            $this->view->packageId = $packageId;
            $this->view->economymask = $getData['economymask'];
            $this->view->customerID = base64_encode($customerID);
            $this->view->countPackage = $getData['counterPackage'];
            $this->view->network = $getData['network'];
        }
    }

    public function getHotelsForPopupAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $packageId = $getData['packageId'];
            $tourCatType = $getData['tourCatType'];
            $packCatType = $getData['packCatType'];
            $CityId = $getData['CityId'];
            $startSequence = $getData['startSequence'];
            $endSequence = $getData['endSequence'];
            $objPackageSearch = new Travel_Model_PackageSearch();
            $tourCatType_Explode = explode('_', $tourCatType);
            if ($packCatType == 'DYNAMIC') {
                $hotelListing = $objPackageSearch->getDynamicHotelsListbyCityId($packageId, $CityId, $startSequence, $endSequence, $tourCatType_Explode[0]);
            } else {
                $hotelListing = $objPackageSearch->getHotelsListbyCityId($packageId, $CityId, $startSequence, $endSequence);
            }
            $hotelListingArray = array();
            foreach ($hotelListing as $hotel) {
                $hotelListingArray[$hotel['Sequence']][] = $hotel;
            }
            $this->view->hotelListing = $hotelListingArray;
            $this->view->countPackage = $getData['counterPackage'];
            $this->view->cityName = $hotelListing[0]['CityName'];
        }
    }

    public function packageBookingListAction() {
        $strUrlData = $this->view->strUrlData = $this->getRequest()->getParam('data');
        $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);

        $this->view->msg = !empty($arrUrlData['msg']) ? $arrUrlData['msg'] : '';
        $this->view->status = !empty($arrUrlData['status']) ? $arrUrlData['status'] : '';
        $this->view->TPSysIdReq = !empty($arrUrlData['TPSysId']) ? $arrUrlData['TPSysId'] : 0;

        $this->_agencyuserroleObj = new Travel_Model_TblAgencyUserRole();
        $getRoleDetail = $this->_agencyuserroleObj->getDataByRole($this->roleID);
        $IsOps = (int) Travel_Model_AgencyAuth::getIdentity()->IsOps;
        if ($IsOps == 1) {
            $getRoleDetail['IsSuperAdmin'] = True;
        }
        $objPackageViewList = new Travel_Model_TblAgencyCustomerTrx();
        $objPackageViewList->ReportingToSysId = $this->ReportingToSysId;
        $getData = array();
        if ($this->getRequest()->getPost()) {
            $getData = $this->getRequest()->getPost();
            $orderBy = isset($getData['order']) ? $getData['order'] : '';

            $columnOrder = '';
            $columnName = '';
            if (isset($orderBy) && !empty($orderBy)) {
                $order_type = explode('_', $orderBy);
                if ($order_type[0] == 'travelDate' && $order_type[1] == trim(1)) {
                    $columnName = 'tb2.StartDate';
                    $columnOrder = 'ASC';
                } else if ($order_type[0] == 'travelDate' && $order_type[1] == 0) {
                    $columnName = 'tb2.StartDate';
                    $columnOrder = 'DESC';
                }
            }
            if ($columnName != '') {
                $getData['columnName'] = $columnName;
                $getData['columnOrder'] = $columnOrder;
            }
            $this->view->order = $orderBy;
            $proposalId = (isset($getData['proposalId']) && !empty($getData['proposalId'])) ? trim($getData['proposalId']) : 0;
            $proposalIdEx = explode('/', $proposalId);

            $getData = $this->_HtmlPurifier->filterArray($getData);
            $this->view->searchArr = $this->view->searchData = $getData;
            $getData['proposalId'] = (isset($proposalIdEx[2]) && !empty($proposalIdEx[2])) ? $proposalIdEx[2] : (int) $proposalIdEx[0];
            $getData['hidden_selected_hotel_cityid'] = (isset($getData['Destination']) && !empty($getData['Destination'])) ? (int) $getData['Destination'] : '';
        }
        $coupon_id = $this->_getParam('id', '');
        $filter = $this->_getParam('filter', 'today');
        $source = ($filter == 'coupon') ? 'overall' : $filter;
        $this->view->source = $source;
        switch ($source) {
            case 'overall': {
                    $currentDate = date("Y-m-d");
                    $fromDate = '2016-10-26';
                    break;
                }
            case 'last-month': {
                    $fromDate = date('Y-m-d', strtotime('first day of last month'));
                    $currentDate = date('Y-m-d', strtotime('last day of last month'));
                    break;
                }
            case 'current-month': {
                    $currentDate = date("Y-m-d");
                    $currentMonth = date("m");
                    $currentYear = date("Y");
                    $fromDate = "$currentYear-$currentMonth-01";
                    break;
                }
            case 'last-week': {
                    $previous_week = strtotime("-1 week +1 day");
                    $start_week = strtotime("last sunday midnight", $previous_week);
                    $end_week = strtotime("next saturday", $start_week);
                    $start_week = date("Y-m-d", $start_week);
                    $end_week = date("Y-m-d", $end_week);
                    $fromDate = $start_week;
                    $currentDate = $end_week;
                    break;
                }
            case 'current-week': {
                    $currentDate = date("Y-m-d");
                    if (date('D') != 'Mon') {
                        $fromDate = date('Y-m-d', strtotime('last Monday'));
                    } else {
                        $fromDate = date('Y-m-d');
                    }
                    break;
                }
            case 'today': {
                    $currentDate = date("Y-m-d");
                    $fromDate = date("Y-m-d");
                    break;
                }
            default: {
                    $currentDate = null;
                    $fromDate = null;
                    break;
                }
        }

        $update_from_date = $this->_request->getPost('from_date', NULL);
        $update_to_date = $this->_request->getPost('to_date', NULL);
        $from_date = $this->_request->getParam('from_date', NULL);
        $to_date = $this->_request->getParam('to_date', NULL);
        if ($update_from_date != NULL && $update_to_date != NULL) {
            $getData1 = array(
                'updatecurrentDate' => $update_to_date,
                'updatefromDate' => $update_from_date
            );
        } else if ($from_date != NULL && $to_date != NULL) {
            $getData1 = array(
                'currentDate' => $to_date,
                'fromDate' => $from_date
            );
        } else {
            $getData1 = array(
                'updatecurrentDate' => $currentDate,
                'updatefromDate' => $fromDate
            );
        }
        $checkOutFromDate = $this->_request->getParam('from_checkout_date', NULL);
        $checkOutToDate = $this->_request->getParam('to_checkout_date', NULL);
        if ($checkOutFromDate != NULL && $checkOutToDate != NULL) {
            $getData1 = array(
                'ValidTillcurrentDate' => $checkOutToDate,
                'ValidTillfromDate' => $checkOutFromDate
            );
        }
        $getData = array_merge($getData, $getData1);
        if ($filter == 'coupon' && $coupon_id != '') {
            $this->COUPON_HISTORY_CODE_API = COUPON_HISTORY_CODE_API;
            $url = $this->COUPON_HISTORY_CODE_API . 'get-tpsysid/?MasterCouponId=' . $coupon_id;
            $CouponHistoryArray = $this->paymentMdl->getgtxapiinfo($url);
            $TPSysIdArray = array();
            if (isset($CouponHistoryArray['results']) && !empty($CouponHistoryArray['results'])) {
                foreach ($CouponHistoryArray['results'] as $key => $value) {
                    if ($value['TPSysID'] > 0) {
                        $TPSysIdArray[] = $value['TPSysID'];
                    }
                }
            }

            if (!empty($TPSysIdArray)) {
                $getData['TPSysIdArr'] = $TPSysIdArray;
            }
        }
        if (!empty($getData['agencyServicesFilter'])) {
            if ($getData['agencyServicesFilter'] == 1) {
                $getData['agencyServicesName'] = 'HotelVoucherStatus';
            }
            if ($getData['agencyServicesFilter'] == 2) {
                $getData['agencyServicesName'] = 'FlightVoucherStatus';
            }
            if ($getData['agencyServicesFilter'] == 3) {
                $getData['agencyServicesName'] = 'SightseeingVoucherStatus';
            }
            if ($getData['agencyServicesFilter'] == 4) {
                $getData['agencyServicesName'] = 'TransferVoucherStatus';
            }
            if ($getData['agencyServicesFilter'] == 5) {
                $getData['agencyServicesName'] = 'VisaVoucherStatus';
            }
            if ($getData['agencyServicesFilter'] == 6) {
                $getData['agencyServicesName'] = 'OtherVoucherStatus';
            }
        }



        //echo "<pre>";print_r($getData);die;
        if ($getRoleDetail['IsAdmin'] == true || $getRoleDetail['IsSuperAdmin'] == true) {
            $getData['UserSysId'] = '0';
            $customerBookingRecord = $objPackageViewList->getBookedPackageDetail($this->intLoggedinUserAgencySysId, $source, $getData);
        } else {
            $getData['UserSysId'] = $this->intLoggedinUserId;
            $customerBookingRecord = $objPackageViewList->getBookedPackageDetail($this->intLoggedinUserAgencySysId, $source, $getData);
        }
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($customerBookingRecord);
        $paginator->setItemCountPerPage(GRID_PER_PAGE_RECORD_COUNT);
        $paginator->setCurrentPageNumber($page);
        //         echo '<pre>';print_r($paginator); die;
        $this->view->paginator = $paginator;
        $TblCurrency = new Travel_Model_TblCurrency();
        $this->view->CurrencySymbol = $CurrencySymbol = $TblCurrency->getCurrencySymbolByIdsList();
        $this->_crmcustomerObj->ReportingToSysId = $this->ReportingToSysId;
        $getleadSource = $this->_crmcustomerObj->getLeadSourceByAgency($this->intLoggedinUserAgencySysId);
        $this->view->leadSourceList = $getleadSource;
        if ($getRoleDetail['IsAdmin'] == true || $getRoleDetail['IsAbleToManageTask'] == true || $getRoleDetail['IsSuperAdmin'] == true) {
            $agencyUser = $this->_crmcustomerObj->getAllAgencyUserList('', $this->intLoggedinUserAgencySysId);
        } else {
            $agencyUser = $this->_crmcustomerObj->getAllAgencyUserList('', $this->intLoggedinUserAgencySysId, $this->ReportingToSysId);
        }
        $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $this->view->agencyUser = $agencyUser;
        $this->view->agencyOpsUser = $agencyOpsUser = $this->_crmcustomerObj->getAllAgencyOpsUserList($this->intLoggedinUserAgencySysId);
    }

    public function clearSearchAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
            $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
            $sessionPackageSearchData->searchData = array();
        }
    }

    //this function used for send package proposal by share/email created by Er Amit Kumar Dubey on 20 march 2017 at 12:07 PM
    public function sendproposalemailAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', false);
        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $popupArray = array();
        //echo "<pre>";print_r($sessionPackageSearchData->searchData);die;
        if (count($sessionPackageSearchData->searchData) < 2) {
            $this->_redirect('/dashboard/agency/');
            exit;
        }

        $getData = $this->getRequest()->getPost();
        //print_r($getData);
        $roomjson = array();
        $childsage = '';
        $TotAdultCount = 0;
        $TotChildCount = $TotInfantCount = 0;
        if (!isset($getData['TPSysId'])) {
            echo "No Record Found";
            exit;
        }

        for ($k = 1; $k <= $getData['roomlp']; $k++) {
            $roomjson[$k]['Adult'] = $getData['adult_' . @$k];
            $roomjson[$k]['Child'] = $getData['child_' . @$k];
            $roomjson[$k]['Infant'] = $getData['infant_' . @$k];
            if ($roomjson[$k]['Adult'] == 3) {
                $roomjson[$k]['AdultBedType'] = $getData['adultcl_extrabed_' . $k . '_3'];
            }
            $roomjson[$k]['Child'] = $getData['child_' . $k];
            $roomjson[$k]['Infant'] = $getData['infant_' . $k];

            $TotAdultCount += $roomjson[$k]['Adult'];
            $TotChildCount += $roomjson[$k]['Child'];
            $TotInfantCount += $roomjson[$k]['Infant'];
            for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                $roomjson[$k]['ChildAge_' . $j] = $getData['child_age_' . $k . '_' . $j];
                $roomjson[$k]['ChildBedType_' . $j] = $getData['child_extrabed_' . $k . '_' . $j];
            }
            $roomjson[$k]['departuredate'] = $getData['search_specific_date'];
            $roomjson[$k]['returndate'] = '';
        }


        $objPackage = new Travel_Model_TblPackage();
        $TPSysId_customer = $getData['TPSysId'];
        if (isset($TPSysId_customer) && !empty($TPSysId_customer)) {
            $sessionPackageSearchData->searchData['TPSysId'] = $TPSysId_customer;
        }
        $flexiPackageList = $objPackage->getFlexiPackageList($getData['tpsysID']);
        //print_r($flexiPackageList);die;

        $this->view->flexiPackageList = $flexiPackageList;
        $customerDetails = array();
        $newCustomerId = '';
        if (isset($getData['customerID']) && trim($getData['customerID']) != '') {
            $newCustomerId = trim($getData['customerID']);
        } else {
            $newCustomerId = trim(base64_decode($getData['search_customerId']));
        }
        if ($newCustomerId > 0) {
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($newCustomerId);
            $this->view->customerDetails = $customerDetails;
        }
        $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
        if ($IsB2BCustomer == 1) {
            $MarketPlaceId = 2;
        } else {
            $MarketPlaceId = 1;
        }
        //print_r($customerDetails);die;
        //Get Package Places 
        $pkgtype = explode('_', $getData['pkgtype']);
        if ($pkgtype[0] == 'DYNAMIC') {
            $tourCatType = explode('_', $getData['tourCatType']);
            $catID = $tourCatType[0];
            $tourID = $tourCatType[1];
            //$rateDetails=$objPackage->GetMarketWiseRateBYOReadyMade($getData['tpsysID'],$catID,$tourID);
            $marketwiseratebyo = $objPackage->GetMarketWiseRateBYOReadyMade($getData['tpsysID'], $catID, $tourID);
            $rateList['arrPkgCost'] = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getDynamicPrivateRates($flexiPackageList, $marketwiseratebyo);
            //$rateList=array('arrPkgCost'=>array('AdultPax'=>$roomjson[1]['Adult'],'ChildPax'=>$roomjson[1]['Child'],'FinalCost'=>$flexiPackageList['NetPrice'],'FinalDiscount'=>$flexiPackageList['DiscountVal'],'FinalMarkUp'=>0));



            $rateList['arrPkgCost']['AdultPax'] = $roomjson[1]['Adult'];
            $rateList['arrPkgCost']['ChildPax'] = $roomjson[1]['Child'];
            //$rateList=Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getDynamicPackageRate($getData['tpsysID'],$rateDetails,$flexiPackageList['RoomInfoJson']);
            //print_r($rateList);die;
        } else {
            $rateList = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getPackageRate($getData['tpsysID'], NULL, NULL, $MarketPlaceId);
        }
        //echo "<pre>";
        //print_r($rateList);
        //$rateList=array('arrPkgCost'=>array('AdultPax'=>$flexiPackageList['MinPax'],'ChildPax'=>0,'FinalCost'=>$flexiPackageList['NetPrice'],'FinalDiscount'=>$flexiPackageList['DiscountVal'],'FinalMarkUp'=>0));
        //print_r($rateList);

        $popupArray['dayDetails'] = urldecode($getData['dayDetails']);
        $popupArray['priceDetails'] = urldecode($getData['priceDetails']);
        $popupArray['rateList'] = json_encode($rateList);
        $flexiPackagePlaces = $objPackage->getPackagePlacesList($getData['tpsysID']);
        $this->view->flexiPackagePlaces = $flexiPackagePlaces;
        if ($flexiPackageList['SupplierSysId'] > 0) {
            $objSupplier = new Travel_Model_TblSupplier();
            $arrSupplierDetails = $objSupplier->getSupplierById($flexiPackageList['SupplierSysId']);
            $this->view->arrSupplierDetails = $arrSupplierDetails;
        }
        $customerDetails = array();
        $newCustomerId = '';
        if (isset($getData['customerID']) && trim($getData['customerID']) != '') {
            $newCustomerId = trim($getData['customerID']);
        } else {
            $newCustomerId = trim(base64_decode($getData['search_customerId']));
        }
        if ($newCustomerId > 0) {
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($newCustomerId);
            $this->view->customerDetails = $customerDetails;
        }
        $this->view->searchData = $sessionPackageSearchData->searchData;
        $this->view->popupArray = $popupArray;
        $this->view->roomjson = $roomjson;
        $this->view->pkgtype = $getData['pkgtype'];
        $this->view->tourCatType = $getData['tourCatType'];
    }

    public function viewAndCancelPackageBookingAction() {

        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
            $getData = $this->getRequest()->getPost();

            // Cancellation Request Data...

            $requestDate = !empty($getData['requestDate']) ? $getData['requestDate'] : '';
            $deductionAmount = !empty($getData['deductionAmount']) ? $getData['deductionAmount'] : 0;
            $cRemarks = !empty($getData['cRemarks']) ? $getData['cRemarks'] : '';
            $tpsysID = !empty($getData['TPSysId']) ? $getData['TPSysId'] : 0;
            $this->currentDate = date('Y-m-d H:i:s');

            // Cancellation Request Data...
            // Insert Transactional Data...
            /*
              $addData_Trx = array(
              'MPSysId' => 1,
              'InvoiceId' => '',
              'TrxOrdDocId' => $PlanType,
              'TrxDate' => date('Y-m-d H:i:s'),
              'TrxType' => $TrxType,
              'TrxPayMediaType' => "",
              'CrPartyAccSysId' => 1,
              'DrPartyAccSysId' => "",
              'CrPartyName' => 'GTX', //Agency Name
              'DrPartyName' => $Firstname,
              'CurrencyType' => 1,
              'Amount' => 0,
              'Markup' => 0,
              "AgencyMarkUp" => 0,
              "GTXMarkup" => 0,
              "TrxFee" => 0,
              "Commission" => 0,
              "GTXCommission" => 0,
              'TotalDiscount' => 0,
              'PaidAmount' => 0,
              'NetAmount' => $amount,
              "RandomCode" => $randomString,
              "RandomCodeValidFrom" => $currentDate,
              "RandomCodeValidTo" => $RandomCodeValidTo,
              'TrxStatus' => 0,
              'TBPoints' => 0,
              'IsActive' => false
              );


              $TrxSysId = $this->paymentMdl->insertTable("TB_Trx", $addData_Trx);


              $addData = array(
              'TrxId' => $TrxSysId,
              'AgencySysId' => $AgencySysId,
              'WalletSysId' => $wallet['WalletSysId'],
              'XRefTPSysId' => $TPSysId,
              "GUID" => $txnid,
              "TrxDate" => date('Y-m-d H:i:s'),
              'TrxType' => $TrxType,
              'InvoiceId' => '0',
              'TrxOrdDocId' => $PlanType,
              'PaymentModeType' => 1,
              "TrxPayMediaType" => $TrxPayMediaType,
              'TrxPayMediaRefNo' => "",
              'TransFee' => $TransFee,
              'CrPartyAccSysId' => 1,
              'DrPartyAccSysId' => 0,
              'CrPartyName' => "GTX", //Agency Name
              'DrPartyName' => $Firstname,
              'CurrencyType' => $CurrencyType,
              'TotalDiscount' => $TotalDiscount,
              "Amount" => $baseAmount,
              'NetAmount' => $NetAmount,
              'PaidAmount' => $PaidAmount,
              "SupplierSourceStr" => $SupplierSourceStr,
              "PaxCount" => $PaxCount,
              "ClosingBalance" => $getwalletBalence['BalanceAmount'],
              'TBPoints' => 0,
              "IsActive" => true,
              "UserSysId" => $AgencyUserSysId, //insert user id
              "CreateDate" => date('Y-m-d H:i:s'),
              "UpdateDate" => date('Y-m-d H:i:s'),
              "IsApproved" => true,
              "ApprovedBy" => "0",
              "ApprovedDate" => date('Y-m-d H:i:s'),
              "IsMarkForDel" => false
              );
              $this->paymentMdl->insertTable("TB_Agency_Wallet_Trx", $addData);
             */
            // Insert Transactional Data Ends...
            // Travel Plan Data...

            $travelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpsysID); // get proposal data from customer travel plan
            $customertravelpaln = $travelplandata[0];

            unset($customertravelpaln['TPSysId']);
            $customertravelpaln['CreateDate'] = $this->currentDate;
            $customertravelpaln['UpdateDate'] = $this->currentDate;
            $customertravelpaln['MasterTPSysId'] = $tpsysID;
            $customertravelpaln['StatusType'] = 9;  //new status 16 = Proposal Draft
            $newTPSysID = $this->_crmcusttravelplan->addCustomerTravelPlan($customertravelpaln); //copy of proposal in customer travel plan

            $statusArray = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->changeQueryStatusByProposal();
            //echo "<pre>";print_r($statusArray);exit;
            $querystatus = $statusArray[9];
            if (isset($querystatus) && !empty($querystatus)) {
                $whereQuery = "TPSysId = " . $tpsysID;
                $updatetravelplanquery = array(
                    'StatusType' => $querystatus,
                    'UpdateDate' => $this->currentDate
                );
                $updatetravelPlanQuery = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanquery, $whereQuery);
            }




            // Travel Plan Data Ends...
            // Travel Plan Itenary Data...
            $travelplanIetnaryData = $this->_crmcusttravelplan->GetCustomerTravelPlanItenary($tpsysID); // get itenary
            $TPIntSysIdsArr = array_column($travelplanIetnaryData, 'TPIntSysId');
            $TPIntSysIds = implode(', ', $TPIntSysIdsArr);
            $lasttravelitenaryID = array();
            foreach ($travelplanIetnaryData as $travelplanIetnary) {
                unset($travelplanIetnary['TPIntSysId']);
                $travelitenaryarray = $travelplanIetnary;
                $travelitenaryarray['TPSysId'] = $newTPSysID;
                $travelitenaryarray['CreateDate'] = $this->currentDate;
                $travelitenaryarray['UpdateDate'] = $this->currentDate;
                $lasttravelitenaryID[] = $this->_crmcustomertravelItenary->addCustomerTravelItenary($travelitenaryarray); //add new itenary
            }

            // Travel Plan Itenary Data Ends...
            // Travel Plan Itenary Accom Data...

            $tplanitenaryaccomdata = $this->_crmcusttravelplan->GetTravelPlanCustomerItenaryAccom($TPIntSysIds); // get accom by itenary id

            foreach ($tplanitenaryaccomdata as $tplanitenaryaccom) {
                unset($tplanitenaryaccom['VersionId']);
                $existingtpintID = $tplanitenaryaccom['TPIntSysId'];
                $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);
                $travelitenaryaccomArray = $tplanitenaryaccom;
                $travelitenaryaccomArray['TPIntSysId'] = $lasttravelitenaryID[$getkeyvalue];
                $travelitenaryaccomArray['CreateDate'] = $this->currentDate;
                $travelitenaryaccomArray['UpdateDate'] = $this->currentDate;
                $tplanitenaryaccomdataID[] = $this->_crmcusttravelplanItenaryAccom->addCustomerTravelPlanAccom($travelitenaryaccomArray); // add accom with new itenary ids
            }

            // Travel Plan Itenary Accom Data Ends...


            $tpitenrayEvents = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryEvents($TPIntSysIds); // get activities by itenary ids
            if (!empty($tpitenrayEvents)) {
                foreach ($tpitenrayEvents as $tpitenrayEvent) {
                    unset($tpitenrayEvent['VersionId']);
                    $existingtpintID = $tpitenrayEvent['TPIntSysId'];
                    $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);
                    $tpitenrayevntsArray = $tpitenrayEvent;
                    $tpitenrayevntsArray['TPIntSysId'] = $lasttravelitenaryID[$getkeyvalue];
                    $tpitenrayevntsArray['CreateDate'] = $this->currentDate;
                    $tpitenrayevntsArray['UpdateDate'] = $this->currentDate;
                    $travelitenrayevents[] = $this->_crmcustomertravelItenaryEvents->addCustomerTravelItenaryEvents($tpitenrayevntsArray); // add activities with new itenary ids
                }
            }

            $tpitenaryplaces = $this->_crmcusttravelplan->GetCustomerTravelPlanItenaryPaces($TPIntSysIds); // get places by itenary ids


            if (!empty($tpitenaryplaces)) {
                foreach ($tpitenaryplaces as $tpitenaryplace) {
                    unset($tpitenaryplace['VersionId']);
                    $existingtpintID = $tpitenaryplace['TPIntSysId'];
                    $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);

                    $tpitenrayplacesArray = $tpitenaryplace;
                    $tpitenrayplacesArray['TPIntSysId'] = $lasttravelitenaryID[$getkeyvalue];
                    $tpitenrayplacesArray['CreateDate'] = $this->currentDate;
                    $tpitenrayplacesArray['UpdateDate'] = $this->currentDate;

                    $travelitenrayplaces[] = $this->_crmcustomertravelItenaryPlaces->addCustomerTravelItenaryPlaces($tpitenrayplacesArray); // add places with new itenary ids
                }
            }
            $tpitenarysightseeing = $this->_crmcusttravelplan->GetCustomerTravelPlanSightSeeing($TPIntSysIds); // get sightseeing by itenary ids

            if (!empty($tpitenarysightseeing)) {
                foreach ($tpitenarysightseeing as $tpitenarysightseen) {
                    unset($tpitenarysightseen['VersionId']);
                    $existingtpintID = $tpitenarysightseen['InvnItemSysId'];
                    $getkeyvalue = array_search($existingtpintID, $TPIntSysIdsArr);

                    $tpitenraysightseeingArray = $tpitenarysightseen;
                    $tpitenraysightseeingArray['InvnItemSysId'] = $lasttravelitenaryID[$getkeyvalue];
                    $tpitenraysightseeingArray['CreateDate'] = $this->currentDate;
                    $tpitenraysightseeingArray['UpdateDate'] = $this->currentDate;

                    $travelitenraysightssing[] = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenraysightseeingArray); // add sightseeing with new itenary ids
                }
            }

            $travelplanmarketPriceArr = $this->_crmcusttravelplan->GetCustomerTravelMarketPrice($tpsysID); // get marketprice by travel plan id

            if (!empty($travelplanmarketPriceArr)) {
                foreach ($travelplanmarketPriceArr as $travelplanmarketPrice) {
                    unset($travelplanmarketPrice['TPRateSheetSysId']);
                    $travelmarketpriceArray = $travelplanmarketPrice;
                    $travelmarketpriceArray['TPIntSysId'] = $newTPSysID;
                    $travelmarketpriceArray['CreateDate'] = $this->currentDate;
                    $travelmarketpriceArray['UpdateDate'] = $this->currentDate;

                    $travelitenramarketwsierate[] = $this->_crmcustomertravelMarketPlaces->addCustomerTravelMarketRate($travelmarketpriceArray); // add marketprice with new travel plan id
                }
            }

            $travelplanPriceArr = $this->_crmcusttravelplan->GetCustomerTravelPrice($tpsysID);

            if (!empty($travelplanPriceArr)) {
                foreach ($travelplanPriceArr as $travelplanPrice) {
                    unset($travelplanPrice['TPRateSheetSysId']);
                    $travelpriceArray = $travelplanPrice;
                    $travelpriceArray['TPSysId'] = $newTPSysID;
                    $travelpriceArray['CreateDate'] = $this->currentDate;
                    $travelpriceArray['UpdateDate'] = $this->currentDate;

                    $travelitenrarate[] = $this->_crmcustomertravelPlanRate->addCustomerTravelPlanRate($travelpriceArray); // add price
                }
            }

            $travelplanterms = $this->_crmcusttravelplan->GetCustomerTravelPlanTermsCond($tpsysID);  // get tnc by travel plan id
            if (!empty($travelplanterms)) {
                foreach ($travelplanterms as $travelplanterm) {
                    unset($travelplanterm['TncId']);
                    $travelplantermsArray = $travelplanterm;
                    $travelplantermsArray['TPIntSysId'] = $newTPSysID;
                    $travelplantermsArray['CreateDate'] = $this->currentDate;
                    $travelplantermsArray['UpdateDate'] = $this->currentDate;

                    $travelplantermsids[] = $this->_crmcustomertravelTerm->addCustomerTerm($travelplantermsArray); // add tnc with new travel plan id
                }
            }

            $cancelPolicyData = $this->_crmcusttravelplan->GetCustomerTravelPlanCancelPolicy($tpsysID);
            //         echo '<pre';print_r($cancelPolicyData); 
            if (!empty($cancelPolicyData)) {
                $cancelPolicyArray = array();
                foreach ($cancelPolicyData as $cancelPolicy) {
                    unset($cancelPolicy['TPRulesSysId']);
                    $cancelPolicyArray = $cancelPolicy;
                    $cancelPolicyArray['TPSysId'] = $newTPSysID;
                    $cancelPolicyArray['CreateDate'] = $this->currentDate;
                    $cancelPolicyArray['UpdateDate'] = $this->currentDate;
                    $travelplancancelpolicyids[] = $this->_objPackage->insertData('TB_Agency_Customer_TravelPlan_Rules', $cancelPolicyArray);
                }
            }




            if (!empty($newTPSysID)) {
                $response = array('success' => true, 'msg' => "Package cancellation request captured successfully.");
                echo json_encode($response);
                exit;
            } else {
                $response = array('success' => false, 'msg' => "Oops! there might be some technical error, please try after some time.");
                echo json_encode($response);
                exit;
            }


            //echo "<pre>";print_r($customertravelpaln);exit;
        } else {

            $objPackage = new Travel_Model_TblPackage();
            $this->view->TPSysId = $tpID = base64_decode($this->getRequest()->getParam('id'));
            $flexiPackageList = $objPackage->getCustPackageList($tpID);
            $packageId = trim($flexiPackageList['TPId']);
            //echo "<pre>";print_r($flexiPackageList);echo "</pre>";

            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->view->cancelPolicyData = $cancelPolicyData = $this->_crmcusttravelplan->GetCustomerTravelPlanCancelPolicy($tpID);
            //echo "<pre>";print_r($cancelPolicyData);echo "</pre>";




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

            $this->view->flexiPackageList = $flexiPackageList;

            $flexiPackageItenList = $objPackage->getCustPackageItenList($tpID);

            $totalDaysNightsArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageTotalNoOfDays($flexiPackageItenList);
            $this->view->totalDays = $totalDays = $totalDaysNightsArr['totaldays'];
            $this->view->totalNight = $totalNight = $totalDaysNightsArr['totalnights'];
        }
    }

    public function getDynamicCategoryForPopupAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            $packageId = $getData['packageId'];
            $tourID = $getData['tourID'];
            $customerID = $getData['customerID'];
            $objPackage = new Travel_Model_TblPackage();
            $getpacktypemask = $objPackage->GetMasterPackageList();
            $flexiPackageList = $objPackage->getFlexiPackageList($packageId);
            $categoryResult = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getDynamicCategorywiseData($packageId);
            //print_r($flexiPackageList); 
            $this->view->packtypemask = $getpacktypemask;
            $this->view->flexiPackageList = $flexiPackageList;
            $this->view->packageId = $packageId;
            $this->view->tourID = trim($tourID);
            $this->view->customerID = base64_encode($customerID);
            $this->view->economymask = $getData['economymask'];
            $this->view->countPackage = $getData['counterPackage'];
            $this->view->noofnights = $getData['noofnights'];
        }
    }

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

        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest()->getPost();
            //print_r($getData['economyId']); die;
            $customerID = $getData['customerID'];
            $packageId = $getData['PackageId'];
            $economyType = $getData['economyType'];
            $hotelArr = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getDynamicPkgHotels($packageId, $getData['economyType']);
            $tourID = $getData['tourId'];
            $objPackage = new Travel_Model_TblPackage();
            $flexiPackageList = $objPackage->getFlexiPackageList($packageId);
            $tourID = (isset($tourID) && !empty($tourID)) ? $tourID : $flexiPackageList['TourType'];
            if ($tourID == "3" || $tourID == 2) {
                $tourID = 2;
            } else {
                $tourID = 1;
            }

            @$sessionPSData = new Zend_Session_Namespace('sessionPackageSearchData');
            $roomlp = $sessionPSData->searchData['roomlp'];

            $customerDetails = array();
            if ($customerID > 0) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($customerID);
            }
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            if ($IsB2BCustomer == 1) {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }

            $totaladult = 0;
            $totalchild = $totalInfant = 0;
            for ($k = 1; $k <= $sessionPSData->searchData['roomlp']; $k++) {
                $roomjson[$k]['Adult'] = $sessionPSData->searchData['adult_' . $k];
                if ($roomjson[$k]['Adult'] == 3) {
                    $roomjson[$k]['AdultBedType'] = $sessionPSData->searchData['adultcl_extrabed_' . $k . '_3'];
                }
                $totaladult = $totaladult + $roomjson[$k]['Adult'];
                $roomjson[$k]['Child'] = $sessionPSData->searchData['child_' . $k];
                $totalchild = $totalchild + $roomjson[$k]['Child'];
                $roomjson[$k]['Infant'] = $sessionPSData->searchData['infant_' . $k];
                $totalInfant = $totalInfant + $roomjson[$k]['Infant'];
                for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                    $roomjson[$k]['ChildAge_' . $j] = $sessionPSData->searchData['child_age_' . $k . '_' . $j];
                    $roomjson[$k]['ChildBedType_' . $j] = $sessionPSData->searchData['child_extrabed_' . $k . '_' . $j];
                }
            }
            $roominfojson = json_encode($roomjson);
            $totaltraveler = $totaladult + $totalchild;
            //echo $MarketPlaceId;
            $marketwiseratebyo = $objPackage->GetMarketWiseRateBYOReadyMade($packageId, $getData['economyType'], $tourID, '', $MarketPlaceId);
            $PkgData = $objPackage->GetTravelPlanInfo($packageId); //only fixed discount
            @$sessionPSData = new Zend_Session_Namespace('sessionPackageSearchData');
            $dateArr = explode('/', $sessionPSData->searchData['search_specific_date']);
            $date = $dateArr[2] . '-' . $dateArr[1] . '-' . $dateArr[0];
            $getpkgprice = Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfojson, $packageId, $economyType, $tourID, 0, $date, 'Agent', 'Calculate', NULL, $MarketPlaceId);
            //                        $getpkgprice = $objPackage->GetBYOPackagePrice($packageId,$roominfojson,$totaladult,$totalchild,$totaltraveler,$economyType,$PkgData['DiscountVal'],$tourID,'',$IsB2BCustomer);
            //			echo "<pre>";print_r($getpkgprice);echo "</pre>";
            $pricePerTraveller = $getpkgprice['cwm'] / $totaltraveler;
            //$marketwiseratebyo['PricePerPerson']=round($pricePerTraveller); // Commented By Pardeep Panchal on 18/11/2017
            if ($marketwiseratebyo['ExcludedPercent'] > 0) {
                $percentageCalculation = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($pricePerTraveller, $marketwiseratebyo['ExcludedPercent']);
                $pricePerTraveller = $percentageCalculation + $pricePerTraveller;
                //$marketwiseratebyo['PricePerPerson']=round($pricePerTraveller);  // Commented By Pardeep Panchal on 18/11/2017
            }

            //echo "<pre>";print_r($marketwiseratebyo);
            //            $objPackage = new Travel_Model_PackageSearch();
            //            $packageCityList = $objPackage->getPackageCities($packageId);
            //            
            //            $CitiesBySequenceArray = Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->getCitiesBySequence($packageCityList);
            //            $hotelArr = array();
            //                foreach ($CitiesBySequenceArray as $city) {
            //                    $packageTncList = $objPackage->getPackageHotel($packageId, $city[0],$city[2],$city[3]);
            //                    if(!empty($packageTncList)){
            //                    $hotelArr[] = @$packageTncList[0];
            //                    $hotelArr['startSequence'] = $city[2];
            //                    $hotelArr['endSequence'] = $city[3];
            //                    }
            //                }
            $this->view->hotelData = @$hotelArr;
            $this->view->noofNight = $getData['noofNight'];
            $this->view->counterPAckage = $getData['counter'];
            $this->view->economyType = $getData['economyType'];
            $this->view->marketwiseratebyo = $marketwiseratebyo;
        }
    }

    ///// Updated By:- Md Sabir
    public function enquirysupplierpackageAction() {
        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $AgencyUser = new Zend_Session_Namespace('AgencyUser');
        //echo "<pre>";print_r($sessionLogin_user->manageNotifications);die;
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $AgentSysId = $sessionLogin_user->intLoggedinUserId;
        $UserRoleTitle = $sessionLogin_user->UserRoleTitle;
        $TPSysId = $this->getRequest()->getParam('tpid') ? base64_decode($this->getRequest()->getParam('tpid')) : '';
        $type = $this->getRequest()->getParam('type') ? trim($this->getRequest()->getParam('type')) : '';
        $getLeadlist = array();
        if ($TPSysId) {
            $getLeadlist = $this->_crmcusttravelplan->GetTravelPlanDetailById($TPSysId, $AgencySysId);
            $LeadRemark = $this->_crmcusttravelplan->GetLeadRemarkById($TPSysId, $AgencySysId);
        }
        //echo'<pre>';print_r($LeadRemark);die;
        $this->view->agencyDisplayName = $sessionLogin_user->agencyDetails['DisplayName'];
        $this->view->LeadRemark = $LeadRemark;
        $objTbuset = new Travel_Model_TblUser();
        $getUserDetails = $objTbuset->getUserDetails($sessionLogin_user->UserRole, $sessionLogin_user->intLoggedinUserId);
        $this->view->getUserDetails = $getUserDetails;
        //        echo'<pre>';print_r($getUserDetails);die;
        $objPackage = new Travel_Model_TblPackage();
        $packageInclList = $objPackage->getPackageInclusionList();
        $this->view->packageInclList = $packageInclList;
        $packageThemeList = $objPackage->getPackageThemeList();
        $this->view->packageThemeList = $packageThemeList;
        $objGstRates = new Travel_Model_TblGstRates();
        $arrGSTRatesInfo = $objGstRates->getGSTMasterValue(9, 1);
        $this->view->arrGSTRatesInfo = $arrGSTRatesInfo;
        //echo Zend_Controller_Action_HelperBroker::getStaticHelper("PackageSearch")->enqsupupdatestatus('NDk=',2);die;
        //$this->enqsupupdatestatus('NDk=',2);die;
        $objTransport = new Travel_Model_TblTransport();
        //Get Vehicle Type List 
        $this->view->arrVehicleTypeList = $objTransport->getAllVehicleTypeList();

        $getDataFinal = $sessionPackageSearchData->searchData;
        //echo'<pre>';print_r($getDataFinal);die;
        //echo'<pre>';print_r($getLeadlist[0]); exit;
        $this->_objPkg = new Travel_Model_PackageSearch();
        $this->view->foodPreferenceList = $this->_objPkg->getFoodPreferenceList();
        $cityId = explode('__', $getDataFinal['search_going_to']);
        $objSupplier = new Travel_Model_TblSupplier();
        $EconomyMask = $getLeadlist[0]['EconomyMask'];
        $PlanType = $getLeadlist[0]['PlanType'];
        $IsOnlySightseeingPkg = $getLeadlist[0]['IsOnlySightseeingPkg'];
        $DestinationPlacesSysId = !empty($getLeadlist[0]['CityIds']) ? $getLeadlist[0]['CityIds'] : $getLeadlist[0]['DestinationPlacesSysId'];
        if ($PlanType == 6) {
            $DestinationPlacesSysId = $getLeadlist[0]['CityIds'];
        }
        $planTypeForSupplierServices = array(1 => array(2), 2 => array(4), 5 => array(10), 11 => array(7), 6 => array(9), 9 => array(6, 5));

        if ($PlanType == 10) {
            $supplierservices = array($EconomyMask);
        } else {
            if ($IsOnlySightseeingPkg == 1) {
                $supplierservices = array(6, 5);
            } else {
                $supplierservices = ($planTypeForSupplierServices[$PlanType]) ? $planTypeForSupplierServices[$PlanType] : array();
            }
        }
        $ShowGTXSupplier = 0;
        if (in_array('ShowGTXSupplier', $sessionLogin_user->manageNotifications)) {
            $ShowGTXSupplier = 1;
        }

        $SupplierList = $objSupplier->getSuppliersContactListById($DestinationPlacesSysId, $AgencySysId, $supplierservices, $PlanType, $IsOnlySightseeingPkg, $ShowGTXSupplier);

        //echo'<pre>';print_r($SupplierList);die;
        $this->view->SupplierList = $SupplierList;
        $SupplierServicesArrDB = $objSupplier->getSupplierServices(); //Get Supplier Services
        $this->view->arrSupplierServices = $SupplierServicesArrDB;
        $this->view->supplierservices = $supplierservices;
        $request = Zend_Controller_Front::getInstance()->getRequest();

        //get operational department details
        $objDept = new Travel_Model_TblAgencyDept();

        $roleID = $sessionLogin_user->UserRole;
        $this->_agencyuserroleObj = new Travel_Model_TblAgencyUserRole();
        $getRoleDetail = $this->_agencyuserroleObj->getDataByRole($roleID);
        //end for superadmin
        $ReportingToSysId = $sessionLogin_user->ReportingToSysId;
        if ($getRoleDetail['IsAdmin'] == true) {
            $ReportingToSysId = '';
        }
        $checkIsOpsUserArray = $objDept->getOpsDeptuserMapDet($AgencySysId, $ReportingToSysId, 1, $getLeadlist[0]['PlanType']); //1 for if department selected as IsOperational
        $this->view->checkIsOpsUserArray = $checkIsOpsUserArray;
        $objAgency = new Travel_Model_TblAgency();
        $this->view->getActiveSenderEmailId = $getActiveSenderEmailId = $objAgency->getActiveSenderEmailID($AgencySysId);
        //        echo "<pre>";print_r($checkIsOpsUserArray);die;
        //#end

        $formUrl = array('tpid' => base64_encode($TPSysId));
        if ($type) {
            $formUrl = array('type' => 'operation', 'tpid' => base64_encode($TPSysId));
        }
        if ($request->isPost()) {
            $post = $request->getPost();

            $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
            $searchResult = $sessionPackageSearchData->searchData;
            if ((!isset($post['ContactName']) || empty($post['ContactName'])) && $type != 'operation') {
                $this->_helper->FlashMessenger()->setNamespace('error')->addMessage('Please select supplier');
                $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
            }
            if ((!isset($post['ContactMobile']) || empty($post['ContactMobile'])) && $type != 'operation') {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Please select supplier');
                $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
            }
            if ((!isset($post['SupplierSysId']) || empty($post['SupplierSysId'])) && $type != 'operation') {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Please select supplier');
                $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
            }
            if ((!isset($post['SupplierContactId']) || empty($post['SupplierContactId'])) && $type != 'operation') {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Please select supplier');
                $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
            }
            if ((!isset($post['SupplierEmailId']) || empty($post['SupplierEmailId'])) && $type != 'operation') {
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Please select supplier');
                $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
            }
            //            echo '<pre>';print_r($post);echo '</pre>'; die;
            //echo json_encode($post['EmailContent']);
            //die;
            $senderEmailIDD = isset($post['senderEmailIDD']) ? $post['senderEmailIDD'] : '';
            $supplieremail = isset($post['EmailId']) ? $post['EmailId'] : '';
            $agencyUserEmail = isset($post['agencyUserEmail']) ? $post['agencyUserEmail'] : '';
            $agencyUserSysId = isset($post['agencyUserSysId']) ? $post['agencyUserSysId'] : '';
            $enquiryType = isset($post['enquiryType']) ? $post['enquiryType'] : '';
            $subject = !empty($post['subject']) ? $post['subject'] : 'no-subject';
            $ccEmailId = (isset($post['ccEmailId']) && $post['ccEmailId'] != '') ? $post['ccEmailId'] : '';
            if ($supplieremail) {
                $supplierName = $post['ContactName'];
                $arrpost1 = array(
                    "TPSysId" => $post['TPSysId'],
                    "sendersEmailId" => (!empty($senderEmailIDD)) ? $senderEmailIDD : $AgencyUser->user->EmailId,
                    "agencyPrimaryEmail" => $AgencyUser->user->EmailId,
                    "agencyDisplayName" => $sessionLogin_user->agencyDetails['DisplayName'],
                    "EmailContent" => $post['EmailContent'],
                    "EmailId" => $post['EmailId'],
                    "supplierName" => $post['ContactName'],
                    "ContactMobile" => $post['ContactMobile'],
                    "SupplierEmailId" => $post['SupplierEmailId'],
                    "searchResult" => $searchResult,
                    "arrGSTRatesInfo" => $arrGSTRatesInfo,
                    "packageInclList" => $packageInclList,
                    "intLoggedinUserAgencySysId" => $this->intLoggedinUserAgencySysId,
                    "intLoggedinUserId" => $this->intLoggedinUserId,
                    'ccEmailId' => $ccEmailId,
                );

                $IsOperational = 0;
                $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendPackageDetailToSupplier($supplieremail, $supplierName, $subject, $arrpost1);
            }
            //             echo "<pre>";print_r($arrpost1);die;
            if ($agencyUserEmail) {
                //$agencyUserEmail=array_merge(array('amit@catpl.co.in'),$agencyUserEmail);
                $agencyUserEmail = $agencyUserEmail;
                $arrpost2 = array(
                    "TPSysId" => $post['TPSysId'],
                    "sendersEmailId" => (!empty($senderEmailIDD)) ? $senderEmailIDD : $AgencyUser->user->EmailId,
                    "agencyPrimaryEmail" => $AgencyUser->user->EmailId,
                    "agencyDisplayName" => $sessionLogin_user->agencyDetails['DisplayName'],
                    "EmailContent" => $post['EmailContent'],
                    "EmailId" => $post['agencyUserEmail'],
                    "supplierName" => $post['UserContactName'],
                    "ContactMobile" => $post['UserContactMobile'],
                    "SupplierEmailId" => '',
                    "searchResult" => $searchResult,
                    "arrGSTRatesInfo" => $arrGSTRatesInfo,
                    "packageInclList" => $packageInclList,
                    "intLoggedinUserAgencySysId" => $this->intLoggedinUserAgencySysId,
                    "intLoggedinUserId" => $this->intLoggedinUserId
                );
                $IsOperational = 1;
                $emailStatus_user = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendPackageDetailToOperUser($agencyUserEmail, 'User', $subject, $arrpost2);
            }

            // echo '<pre>';print_r($agencyUserEmail);echo '</pre>';die;
            //die('email');
            if ($emailStatus == '1') {
                $CitySysId = explode('__', $post['CitySysId']);
                $chekdate = explode('/', $post['search_specific_date']);
                $currentDate = date('Y-m-d H:i:s');
                $EmailId = (isset($post['EmailId']) && !empty($post['EmailId']) ? $post['EmailId'] : '');
                $ContactName = (isset($post['ContactName']) && !empty($post['ContactName']) ? $post['ContactName'] : '');
                $ContactMobile = (isset($post['ContactMobile']) && !empty($post['ContactMobile']) ? $post['ContactMobile'] : '');
                $SupplierSysId = (isset($post['SupplierSysId']) && !empty($post['SupplierSysId']) ? $post['SupplierSysId'] : '');
                $SupplierContactId = (isset($post['SupplierContactId']) && !empty($post['SupplierContactId']) ? $post['SupplierContactId'] : '');
                $SupplierEmailId = (isset($post['SupplierEmailId']) && !empty($post['SupplierEmailId']) ? $post['SupplierEmailId'] : '');
                if ($EmailId) {
                    foreach ($EmailId as $key => $val) {
                        $insert = array(
                            "TPSysId" => $post['TPSysId'],
                            "CitySysId" => isset($CitySysId[0]) ? $CitySysId[0] : '0',
                            "SendersId" => $post['sendersId'],
                            "SendersEmailId" => $post['sendersEmailId'],
                            "SendersName" => $post['sendersName'],
                            "SendersMobile" => $post['SendersMobile'],
                            "AgencySysId" => $post['AgencySysId'],
                            "SupplierSysId" => $SupplierSysId[$key],
                            "SupplierContactId" => $SupplierContactId[$key],
                            "SupplierEmailId" => $SupplierEmailId[$key],
                            "ContactEmailId" => $val,
                            "ContactName" => $ContactName[$key],
                            "ContactMobile" => $ContactMobile[$key],
                            "CheckInDate" => ($chekdate[2] . '-' . $chekdate[1] . '-' . $chekdate[0]),
                            "MailSubject" => $subject,
                            "EmailContent" => json_encode($post['EmailContent']),
                            "RoomMemInfoJson" => isset($getDataFinal['RoomMemInfoJson']) ? $getDataFinal['RoomMemInfoJson'] : '',
                            "CreateDate" => $currentDate,
                            "UpdateDate" => $currentDate,
                            "PlanType" => 5,
                            "IsB2BAgent" => $post['IsB2BAgent'],
                            "IsActive" => 1,
                            "IsOperational" => $IsOperational,
                            "IsMarkForDelete" => 0
                        );
                        $insertId = $objPackage->AddEnquirySupplierPackage($insert);
                        //echo '<pre>';print_r($insert);echo '</pre>';
                    }

                    if ($insertId) {
                        $errorMessage = "Mail send succesfully";
                        $this->_helper->FlashMessenger->setNamespace('success')->addMessage('Mail send succesfully');
                        $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
                    } else {
                        $errorMessage = "Oops! unable to send mail! please try again.";
                        $this->view->errorMessage = $errorMessage;
                        $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
                    }
                }
            }
            if ($emailStatus_user == '1') {
                $CitySysId = explode('__', $post['CitySysId']);
                $chekdate = explode('/', $post['search_specific_date']);
                $currentDate = date('Y-m-d H:i:s');
                $EmailId = (isset($post['agencyUserEmail']) && !empty($post['agencyUserEmail']) ? $post['agencyUserEmail'] : '');
                $ContactName = (isset($post['ContactName']) && !empty($post['ContactName']) ? $post['ContactName'] : '');
                $ContactMobile = (isset($post['ContactMobile']) && !empty($post['ContactMobile']) ? $post['ContactMobile'] : '');
                $SupplierSysId = (isset($post['UserUserSysId']) && !empty($post['UserUserSysId']) ? $post['UserUserSysId'] : '');
                $SupplierContactId = (isset($post['SupplierContactId']) && !empty($post['SupplierContactId']) ? $post['SupplierContactId'] : '');
                $SupplierEmailId = (isset($post['SupplierEmailId']) && !empty($post['SupplierEmailId']) ? $post['SupplierEmailId'] : '');
                if ($EmailId) {
                    foreach ($EmailId as $key => $val) {
                        $insert = array(
                            "TPSysId" => $post['TPSysId'],
                            "CitySysId" => isset($CitySysId[0]) ? $CitySysId[0] : '0',
                            "SendersId" => $post['sendersId'],
                            "SendersEmailId" => $post['sendersEmailId'],
                            "SendersName" => $post['sendersName'],
                            "SendersMobile" => $post['SendersMobile'],
                            "AgencySysId" => $post['AgencySysId'],
                            "SupplierSysId" => $SupplierSysId[$key],
                            "SupplierContactId" => $SupplierContactId[$key],
                            "SupplierEmailId" => $SupplierEmailId[$key],
                            "ContactEmailId" => $val,
                            "ContactName" => $ContactName[$key],
                            "ContactMobile" => $ContactMobile[$key],
                            "CheckInDate" => ($chekdate[2] . '-' . $chekdate[1] . '-' . $chekdate[0]),
                            "MailSubject" => $subject,
                            "EmailContent" => json_encode($post['EmailContent']),
                            "RoomMemInfoJson" => isset($getDataFinal['RoomMemInfoJson']) ? $getDataFinal['RoomMemInfoJson'] : '',
                            "CreateDate" => $currentDate,
                            "UpdateDate" => $currentDate,
                            "PlanType" => 5,
                            "IsB2BAgent" => $post['IsB2BAgent'],
                            "IsActive" => 1,
                            "IsOperational" => $IsOperational,
                            "IsMarkForDelete" => 0
                        );
                        //echo '<pre>';print_r($insert);echo '</pre>';die;
                        $insertId = $objPackage->AddEnquirySupplierPackage($insert);
                    }

                    if ($insertId) {
                        $AgencyUserId = isset($SupplierSysId[0]) ? $SupplierSysId[0] : 0;
                        $TPSysId = isset($post['TPSysId']) ? (int) $post['TPSysId'] : 0;
                        if ($AgencyUserId > 0 && $TPSysId > 0) {
                            $userQueryAgent = array(
                                'IsOperationalLead' => 1,
                                'OpsAgentSysId' => $AgencyUserId,
                                'UpdateDate' => $currentDate,
                            );
                            $whereQuery = "TPSysId = " . $TPSysId . " OR MasterTPSysId = " . $TPSysId;
                            $this->_crmcusttravelplan->UpdateCustomerTravelPlan($userQueryAgent, $whereQuery);
                        }



                        $errorMessage = "Mail send succesfully";
                        $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Mail send succesfully');
                        $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
                    } else {
                        $errorMessage = "Oops! unable to send mail! please try again.";
                        $this->view->errorMessage = $errorMessage;
                        $this->_helper->redirector('enquirysupplierpackage', 'packagesearch', '', $formUrl);
                    }
                }
            }
        }
        $this->view->getLeadlist = $getLeadlist;
        $this->view->type = $type;
        //echo '<pre>';print_r($getLeadlist);
        //echo '</pre>';$this->_helper->flashMessenger->addMessage("Mail send succesfully");
        // $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }

    public function resendenquirysupplierpackageAction() {
        $params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $AgencyUser = new Zend_Session_Namespace('AgencyUser');
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->view->agencyDisplayName = $sessionLogin_user->agencyDetails['DisplayName'];
        $objPackage = new Travel_Model_TblPackage();
        $packageInclList = $objPackage->getPackageInclusionList();
        $this->view->packageInclList = $packageInclList;
        $objGstRates = new Travel_Model_TblGstRates();
        $arrGSTRatesInfo = $objGstRates->getGSTMasterValue(9, 1);
        $this->view->arrGSTRatesInfo = $arrGSTRatesInfo;
        $this->view->id = $params['id'];

        $objSupplier = new Travel_Model_TblSupplier();
        $SupplierServicesArrDB = $objSupplier->getSupplierServices(); //Get Supplier Services
        $this->view->arrSupplierServices = $SupplierServicesArrDB;
        $SupplierEnquiryDetails = $objSupplier->getSupplierspackageEnquiryDetails($AgencySysId, base64_decode($params['id']));
        $this->view->SupplierEnquiryDetails = $SupplierEnquiryDetails;
        $SuppliersContactName = $objSupplier->getSuppliersContactNameById($SupplierEnquiryDetails['SupplierContactId']);
        $this->view->SuppliersContactName = $SuppliersContactName;
        //echo '<pre>';print_r($SupplierEnquiryDetails);echo '</pre>';
        $request = Zend_Controller_Front::getInstance()->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost();
            $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
            $searchResult = $sessionPackageSearchData->searchData;
            //echo '<pre>';print_r($post);echo '</pre>';
            //echo json_encode($post['EmailContent']);
            //die;
            $supplieremail = $post['EmailId'];
            $supplierName = $post['ContactName'];
            $subject = !empty($post['subject']) ? $post['subject'] : 'no-subject';

            $arrpost = array(
                "TPSysId" => $post['TPSysId'],
                "sendersEmailId" => $post['sendersEmailId'],
                "agencyPrimaryEmail" => $AgencyUser->user->EmailId,
                "agencyDisplayName" => $sessionLogin_user->agencyDetails['DisplayName'],
                "EmailContent" => $post['EmailContent'],
                "EmailId" => $post['EmailId'],
                "supplierName" => $post['ContactName'],
                "ContactMobile" => $post['ContactMobile'],
                "SupplierEmailId" => $post['SupplierEmailId'],
                "searchResult" => $searchResult,
                "arrGSTRatesInfo" => $arrGSTRatesInfo,
                "packageInclList" => $packageInclList
            );
            $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendPackageDetailToSupplier($supplieremail, $supplierName, $subject, $arrpost);

            if ($emailStatus == '1') {
                $errorMessage = "Mail re-send succesfully";
                $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Mail re-send succesfully');
                $this->_helper->redirector('resendenquirysupplierpackage', 'packagesearch', 'default', array('id' => $post['ids']));
            } else {
                $errorMessage = "Oops! unable to send mail! please try again.";
                $this->view->errorMessage = $errorMessage;
                $this->_helper->redirector('resendenquirysupplierpackage', 'packagesearch', 'default', array('id' => $post['ids']));
            }
        }
        //echo '<pre>';print_r($SupplierList);echo '</pre>';$this->_helper->flashMessenger->addMessage("Mail send succesfully");
        // $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }

    public function previewenquirysupplierAction() {
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $AgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->_helper->layout->disableLayout();
        $request = Zend_Controller_Front::getInstance()->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost();
            //echo '<pre>';print_r($post['EmailContent']);echo '</pre>';die;
            $this->view->EmailContent = $post['EmailContent'];
        }
    }

    public function getcitybuildpckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {

        $term = $this->getRequest()->getParam('term');
        //$result = array();
        $obj = new Travel_Model_GeneralFunction();
        $result = $obj->getCitySearchbuildpck($term);
        //echo "<pre>";print_r($result);die;
        echo json_encode($result);
        exit;
        //}
    }

    public function senddynamicproposalemailAction() {
        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', false);
        $sessionPackageSearchData = new Zend_Session_Namespace('sessionPackageSearchData');
        $popupArray = array();
        //echo "<pre>";print_r($sessionPackageSearchData->searchData);

        if (count($sessionPackageSearchData->searchData) < 2) {
            $this->_redirect('/dashboard/agency/');
            exit;
        }

        $getData = $this->getRequest()->getPost();
        $roomjson = array();
        //$childcount = 1;

        $childsage = '';

        for ($k = 1; $k <= $getData['roomlp']; $k++) {
            $childcount = $getData['child_' . @$k];
            $roomjson[$k]['Adult'] = $getData['adult_' . @$k];
            $roomjson[$k]['Child'] = $getData['child_' . @$k];
            $roomjson[$k]['Infant'] = $getData['infant_' . @$k];
            for ($c = 1; $c <= $childcount; $c++) {
                $childsage = $getData['child_' . @$childcount . '_' . @$c];
                $roomjson[$k]['ChildAge_' . $c] = $childsage;
            }
            $roomjson[$k]['bedtype'] = $getData['extrabed_' . @$k];
            $roomjson[$k]['departuredate'] = $getData['search_specific_date'];
            $roomjson[$k]['returndate'] = '';
        }
        $roominfojson = json_encode($roomjson);

        $objPackage = new Travel_Model_TblPackage();
        $tpID = $getData['tpsysID'];
        $queryTPSysId = $getData['TPSysId'];
        //$tpID=1291;
        $tourCatType = explode('_', $getData['tourCatType']);
        $catID = $tourCatType[0];
        $tourID = $tourCatType[1];
        if ($tourCatType[1] == "3" || $tourCatType[1] == 1) {
            $selectedtourID = 1;
        } else {
            $selectedtourID = 2;
        }

        $customerDetails = array();
        $newCustomerId = '';
        if (isset($getData['customerID']) && trim($getData['customerID']) != '') {
            $newCustomerId = trim($getData['customerID']);
        } else {
            $newCustomerId = trim(base64_decode($getData['search_customerId']));
        }
        if ($newCustomerId > 0) {
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($newCustomerId);
            $this->view->customerDetails = $customerDetails;
        }
        $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
        if ($IsB2BCustomer == 1) {
            $MarketPlaceId = 2;
        } else {
            $MarketPlaceId = 1;
        }
        $IsFromModified = !empty($getData['IsFromModified']) ? $getData['IsFromModified'] : false;
        $this->view->tourID = $tourID;
        $this->view->catID = $catID;
        $this->view->tpID = $tpID;
        $this->view->queryTPSysId = $queryTPSysId;
        $this->view->IsFromModified = $IsFromModified;
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $flexiPackageList = $objPackage->getFlexiPackageList($tpID);
        //print_r($flexiPackageList);die;
        $pkgagencysysID = $flexiPackageList['AgencySysId'];
        $flexiPackageList['RoomInfoJson'] = $roominfojson;
        // if($pkgagencysysID == $intLoggedinUserAgencySysId){
        $flexiPackageItenList = $objPackage->getFlexiPackageItenList($tpID);
        // $objAgency = new Travel_Model_TblAgency();
        $agencyTncList = $objPackage->getCustomerTnCDetails($tpID);
        $this->view->agencyTncList = $agencyTncList;
        $this->view->flexiPackageItenList = $flexiPackageItenList;
        $termscond = $objPackage->getPkgTermCond($tpID);
        $marketwiseratebyo = $objPackage->GetMarketWiseRateBYOReadyMade($tpID, $catID, $selectedtourID, '', $MarketPlaceId);
        $this->view->marketwiseratebyo = $marketwiseratebyo;
        $this->view->termc = $termscond;
        //echo $this->getRequest()->getParam('id');		
        if ($tpID > 0) {
            $getpacktypemask = $objPackage->GetMasterPackageList();
            $this->view->packtypemask = $getpacktypemask;

            $getitenryID = $objPackage->GetTravelPlanItenaryIDBYO($tpID);
            $flexiPackagePlaces = $objPackage->getPackagePlacesList($tpID);
            $this->view->flexiPackagePlaces = $flexiPackagePlaces;
            $itenararray = array();
            for ($i = 0; $i < count($getitenryID); $i++) {
                $itenararray[] = "'" . $getitenryID[$i]['TPIntSysId'] . "'";
            }

            $implodeitenary = implode(",", $itenararray);
            $this->view->allitnID = $implodeitenary;
            $getselectedHotel = $objPackage->GetAllSelectedHotelCountBYO($implodeitenary, $catID);
            $this->view->totalhotelcount = count($getselectedHotel);

            $getflightcount = $objPackage->GetFlightCountBYO($implodeitenary);
            $this->view->totalflightcount = count($getflightcount);
            $getactivitycount = $objPackage->GetIncludedActivityCountBYO($implodeitenary);

            $gettransportoption = $objPackage->GetTransPortOptionBYO($tpID);
            //echo count($gettransportoption);
            $totaltransport = count($gettransportoption);
            $this->view->totaltransport = $totaltransport;
            $this->view->totalactivitycount = count($getactivitycount);
            $this->view->implodeitenary = $implodeitenary;
            $getsightseeincount = $objPackage->GetSightSeeingByItenaryCountBYO($implodeitenary);
            $this->view->totalsightseeingcount = count($getsightseeincount);
            //$this->view->hotelCount = count($getselectedHotel);
            $flightitenarydata = $objPackage->GetFlightItenaryWiseBYO($implodeitenary);
            //  $hotelcount = $objPackage->GetAllSelectedHotel($implodeitenary);
            $this->view->itenarydata = $itenararray;
            $this->view->flightitenarydata = $flightitenarydata;

            $this->view->flexiPackageList = $flexiPackageList;

            //Get Package Hotels
            $flexiPackageHotelsList = $objPackage->getFlexiPackageHotelsListBYO($implodeitenary);

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

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

            $customerDetails = array();
            $newCustomerId = '';
            if (isset($getData['customerID']) && trim($getData['customerID']) != '') {
                $newCustomerId = trim($getData['customerID']);
            } else {
                $newCustomerId = trim(base64_decode($getData['search_customerId']));
            }
            if ($newCustomerId > 0) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($newCustomerId);
                $this->view->customerDetails = $customerDetails;
            }
            $this->view->searchData = $sessionPackageSearchData->searchData;
            ########## Code Added By Shobhit ##################
        }
        //}
        else {
            $this->_redirect('/publicpackage/pagenotfound/');
        }
    }

    // Added By Pardeep Panchal       

    public function offlinePaymentProcessAction() {
        $objPkgBooking = new Travel_Model_TblPackageBooking();
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {

            $TPSysId = $this->getRequest()->getParam('TPSysId');
            $paymentType = $this->getRequest()->getParam('paymentType'); // 1 For Online, 2 For Offline
            $amountPost = $this->getRequest()->getParam('amount'); // 1 For Online, 2 For Offline
            $PlanType = $this->getRequest()->getParam('PlanType');
            // print_r( $TPSysId);  die();
            $arrPostValues = array(
                "TPSysId" => $TPSysId,
                "amount" => $amountPost,
                "PlanType" => isset($PlanType) ? $PlanType : 5,
            );

            // $arrPackage = $objPkgBooking->getPackageTravelPlanDetailForPaymentReminder($TPSysId);
            // print_r($arrPackage); die();
            if (!empty($TPSysId)) {
                if ($paymentType == 11) {
                    $travelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId);
                    $SecureCode = Zend_Controller_Action_HelperBroker::getStaticHelper('SecureCode')->secureCode(base64_encode($TPSysId), 1);
                    $CustomerSysId = $travelplandata[0]['CustomerSysId'];
                    echo json_encode(array('success' => true, 'pType' => $paymentType, 'msg' => '', 'TPSysId' => base64_encode($TPSysId), 'CustomerSysId' => base64_encode($CustomerSysId), 'SecureCode' => $SecureCode));
                    exit;
                } else if ($paymentType == 1) {

                    $this->sendPaymentReminderToCustomerAction($TPSysId); // send offline payment reminder to customer...

                    echo json_encode(array('success' => true, 'pType' => $paymentType, 'msg' => 'A payment reminder email with payment link has been sent to the customer.'));
                    exit;
                } else {

                    if ($amountPost < 0) {
                        echo json_encode(array('success' => false, 'pType' => $paymentType, 'msg' => 'Amount entered should be in three digits.'));
                        exit;
                    }


                    $arrResponse = $this->packageOfflinePaymentAction($arrPostValues);
                    echo json_encode(array('success' => true, 'pType' => $paymentType, 'arrResponse' => $arrResponse, 'msg' => 'Work In Progress'));
                    exit;
                }

                echo json_encode(array('success' => false, 'pType' => $paymentType, 'msg' => 'Oops! there might be some Technical Error, Please Contact Administrator.'));
                exit;
            } else {
                echo json_encode(array('success' => false, 'msg' => 'Oops ! We could not find your Travel Plan Details, Please Contact Administrator.'));
                exit;
            }
        } else {


            $TpSysId = $this->getRequest()->getParam('TpSysId');
            $status = $this->getRequest()->getParam('status');
            $msg = $this->getRequest()->getParam('error');

            /*
              $objPkgBooking = new Travel_Model_TblPackageBooking();

              $objPkgBooking->TPSysId = $TpSysId;
              $arrPkgDetails = $objPkgBooking->getPackageTravelPlanDetails();
              $PackageCost = round($arrPkgDetails[0]['NetPrice']);

              $amountPaid = $objPkgBooking->getAmountPaidForProposalOfflinePaymentByTPSysId($TpSysId);
              $TotalAmountPaid = !empty($amountPaid['TotalAmountPaid'])?round($amountPaid['TotalAmountPaid']):0;

              if ($status == "Pending" && ($PackageCost == $TotalAmountPaid)) {
              $StatusType = 17; //8 = Proposal Booked
              } else if($status == "Pending" && ($PackageCost > $TotalAmountPaid)){
              $StatusType = 13; //13 = Advance booking
              } else if ($status == "failure") {
              $StatusType = 6;  //6 = Payment Pending
              } else {
              $StatusType = 7; //7 = Booking Pending
              }

              $objPkgBooking->updateProposalStatus($StatusType, $TpSysId,$arrPkgDetails[0]['MasterTPSysId']);
             */

            $status = $this->getRequest()->getParam('status');
            $msg = $this->getRequest()->getParam('error');

            $arrData = array(
                "msg" => $msg,
                "status" => $status,
                "TPSysId" => $TpSysId
            );

            $strUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataEncode($arrData);
            if ($status == "Pending") {
                $this->_redirect('/packagesearch/package-booking-list/data/' . $strUrlData);
                exit;
            }
        }
    }

    public function packageOfflinePaymentAction($arrPostValues) {

        $TPSysId = $arrPostValues['TPSysId'];
        $amount = $arrPostValues['amount'];

        $objPkgBooking = new Travel_Model_TblPackageBooking();
        $amountPaid = $objPkgBooking->getAmountPaidForProposalByTPSysId($TPSysId);
        $TotalAmountPaid = !empty($amountPaid['TotalAmountPaid']) ? $amountPaid['TotalAmountPaid'] : 0;

        $arrPackage = $objPkgBooking->getPackageTravelPlanDetailForPaymentReminder($TPSysId);

        $packageCost = round($arrPackage['NetPrice']);
        $AgencySysId = round($arrPackage['AgencySysId']);
        $AgentSysId = round($arrPackage['AgentSysId']);
        $balanceAmount = $packageCost - $TotalAmountPaid;

        $intCustSysId = $arrPackage['CustomerSysId'];
        if (!empty($intCustSysId)) {
            $objFlight = new Travel_Model_TblFlight();
            $arrTrevllerDetails = $objFlight->GetAgencyCustomerDetailsForBooking($intCustSysId, $TPSysId);
            $leadCustFirstName = isset($arrTrevllerDetails[0][0]['FirstName']) ? trim($arrTrevllerDetails[0][0]['FirstName']) : '';
            $leadContacts = isset($arrTrevllerDetails[0][0]['Contacts']) ? trim($arrTrevllerDetails[0][0]['Contacts']) : '';
            $leadCustEmailId = isset($arrTrevllerDetails[0][0]['EmailId']) ? trim($arrTrevllerDetails[0][0]['EmailId']) : '';
        }




        $markuparray['intAgentMarkUpAmount'] = 0;
        $markuparray['intAgencyMarkUpAmount'] = 0;
        $markuparray['intGTXMarkUpAmount'] = 0;
        $markuparray['intTotalAmount'] = $amount;
        $markuparray['intTax'] = 0;
        $markuparray['intTotalGTXTaxAmount'] = 0;
        $markuparray['GTXServiceTaxAmount'] = 0;
        $markuparray['AgentServiceTaxAmount'] = 0;
        $markuparray['AgentsCustomServiceTaxAmount'] = 0;
        $markuparray['Pax'] = 0;
        $markuparray['SupplierSourceStr'] = $AgencySysId . '/myinventory';
        $markuparray['TotalDiscount'] = 0;
        $markuparray['CurrencyType'] = 1; //currency Id
        $markuparray['MarketPlaceId'] = 1; //b2b or b2c

        $encryptMarkUpData = $this->getEnc(json_encode($markuparray));

        $guid = $this->GUID();
        $securecode = $this->walletCode($AgentSysId, $guid, $amount, $AgencySysId, $TPSysId, $intCustSysId, $encryptMarkUpData);

        $IsPaymentGateway = !empty($arrAgencyDetails['IsPaymentGateway']) ? $arrAgencyDetails['IsPaymentGateway'] : 0;
        $strPaymentUrl = Catabatic_Helper::getSiteUrl() . "payment/customer-offline-payment";
        //$strPaymentUrl = "http://st.tb.tripsbank.com/payment/customer-offline-payment"; 

        $intPlanType = (isset($arrPostValues['PlanType']) && !empty($arrPostValues['PlanType'])) ? $arrPostValues['PlanType'] : (int) $arrPackage['PlanType'];
        $strTrxType = ($intPlanType == 2) ? 'H' : 'P'; //TrxType
        $IsCardChrgToCustomer = 1;

        // for wallet use
        $fullBaseUrl = $this->view->baseUrl();
        $strReturnURL = $fullBaseUrl . "/packagesearch/offline-payment-process";
        $strErrorURL = $fullBaseUrl . "/packagesearch/offline-payment-process";

        $response = array(
            "guid" => $guid,
            "securecode" => $securecode,
            "Firstname" => $leadCustFirstName,
            "email" => $leadCustEmailId,
            "phone" => $leadContacts,
            "amount" => $amount,
            "AgencyUserSysId" => $AgentSysId,
            "AgencySysId" => $AgencySysId,
            "TrxType" => $strTrxType,
            "PlanType" => $intPlanType,
            "TPSysId" => $TPSysId,
            "IsCardChrgToCustomer" => $IsCardChrgToCustomer,
            "CustomerSysId" => $intCustSysId,
            "returnURL" => $strReturnURL,
            "stringData" => $encryptMarkUpData,
            "errorURL" => $strErrorURL,
            "strPaymentUrl" => $strPaymentUrl
        );

        return $response;
    }

    public function sendPaymentReminderToCustomerAction($TPSysId) {

        $objPackage = new Travel_Model_TblPackage();
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $this->baseUrl = $request->getScheme() . '://' . $request->getHttpHost();

        $path = SITE_FULL_URL . 'public/assets/images';

        $objPkgBooking = new Travel_Model_TblPackageBooking();
        $amountPaid = $objPkgBooking->getAmountPaidForProposalByTPSysId($TPSysId);
        $TotalAmountPaid = !empty($amountPaid['TotalAmountPaid']) ? $amountPaid['TotalAmountPaid'] : 0;

        $arrPackage = $objPkgBooking->getPackageTravelPlanDetailForPaymentReminder($TPSysId);
        $travelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($TPSysId);
        $DestinationPlaces = trim($travelplandata[0]['DestinationPlaces']);
        $currencyExchangeRate = $objPackage->currencyExchangeRate($arrPackage['CurrencyType'], $amountPaid['CurrencyType'], $arrPackage['AgencySysId']);
        //        echo "<pre>";print_r($currencyExchangeRate);echo "</pre>";exit;



        $packageCost = round(($arrPackage['NetPrice'] + $arrPackage['TotalCostGen'] + $arrPackage['TotalTcs']) * $currencyExchangeRate);
        $AgencySysId = $arrPackage['AgencySysId'];

        $balanceAmount = $packageCost - $TotalAmountPaid;
        $arrBookingDate = (array) $arrPackage['ApproveDate'];

        $BookingDate = explode(" ", @$arrBookingDate['date']);
        $BookingDate = date('d/m/Y', strtotime(trim(@$BookingDate[0])));

        $intCustSysId = $arrPackage['CustomerSysId'];
        if (!empty($intCustSysId)) {
            $objFlight = new Travel_Model_TblFlight();
            $arrTrevllerDetails = $objFlight->GetAgencyCustomerDetailsForBooking($intCustSysId, $TPSysId);
            $leadCustFirstName = $arrTrevllerDetails[0][0]['FirstName'];
            $leadCustLastName = $arrTrevllerDetails[0][0]['LastName'];
            $leadCustEmailId = $arrTrevllerDetails[0][0]['EmailId'];
            $leadCustcountryCode = $arrTrevllerDetails[0][0]['countrycodeISD'];
            $leadCustContacts = $arrTrevllerDetails[0][0]['Contacts'];
        }

        $objAgency = new Travel_Model_TblAgency();
        $arrAgencyDetails = $objAgency->getAgencyDataById($AgencySysId); //get agent details
        //print_r($arrAgencyDetails);die();
        //


        $pathAgency = SITE_FULL_URL . 'public/upload/media/agency/' . $AgencySysId;
        if (isset($arrAgencyDetails['Logo']) && $arrAgencyDetails['Logo'] != '') {
            $AgencyLogo = $pathAgency . '/' . $arrAgencyDetails['Logo'];
        } else {
            $AgencyLogo = $path . '/default_company_logo.jpg';
        }




        //echo "<pre>";print_r($arrAgencyDetails);
        $IsB2CSite = !empty($arrAgencyDetails['IsB2CSite']) ? $arrAgencyDetails['IsB2CSite'] : 0;
        $IsPaymentGateway = !empty($arrAgencyDetails['IsPaymentGateway']) ? $arrAgencyDetails['IsPaymentGateway'] : 0;
        $secureCode = Zend_Controller_Action_HelperBroker::getStaticHelper('SecureCode')->secureCode(base64_encode($TPSysId), 1);
        $booknowurl = $this->baseUrl . "/package-booking/package-booking-view/pid/" . base64_encode($TPSysId) . "/cid/" . base64_encode($intCustSysId) . "/ptype/b/code/" . $secureCode;

        if ($IsB2CSite == 1) {
            $booknowurl = $arrAgencyDetails['Url'] . "detail/index/view/id/" . base64_encode($booknowurl);
        }




        $params['agency_logo'] = $AgencyLogo;
        $params['company_name'] = $arrAgencyDetails['DisplayName'];
        $params['booking_date'] = ($BookingDate != "01/01/1970") ? $BookingDate : '';
        $params['package_cost'] = (int) $packageCost;
        $params['paid_amount'] = (int) $TotalAmountPaid;
        $params['balance_amount'] = (int) $balanceAmount;
        $params['shared_url'] = $booknowurl;
        $params['cust_name'] = trim($leadCustFirstName) . " " . trim(@$leadCustLastName);
        $params['about_package'] = "";
        $params['agent_firstname'] = trim($arrAgencyDetails['FirstName']) . ' ' . trim($arrAgencyDetails['LastName']);
        $params['agent_primarycontact'] = $arrAgencyDetails['ContactNo1'];
        $params['file_path_location'] = $path;
        $params['sendersEmailId'] = $arrAgencyDetails['EmailId'];
        $params['agencyDisplayName'] = $arrAgencyDetails['DisplayName'] ? $arrAgencyDetails['DisplayName'] : $arrAgencyDetails['Title'];
        $params['PrimaryEmail'] = $arrAgencyDetails['PrimaryEmail'];
        $params['TPSysId'] = $TPSysId;
        $params['AgencySysId'] = trim($travelplandata[0]['AgencySysId']);
        $params['AgentSysId'] = trim($arrPackage['AgentSysId']);
        //$params['arrPackage'] = $paramArrayPackage;
        $subject = 'Package Booking Payment Reminder';
        $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->sendPaymentReminderToCustomer($leadCustEmailId, $subject, $params);

        if ($emailStatus) {
            $arrAgentDetails = $this->_crmcusttravelplan->getAgentDetails($arrPackage['AgentSysId']);
            $CustomersecureCode = Zend_Controller_Action_HelperBroker::getStaticHelper('SecureCode')->secureCode(trim(base64_encode($intCustSysId)), 1);

            $countrycode = (strpos($leadCustcountryCode, '+') !== false) ? $leadCustcountryCode : "+" . $leadCustcountryCode;
            $CustomerMobileNumber = trim($countrycode) . '' . trim($leadCustContacts);
            $customerFirstName = trim($leadCustFirstName);
            $OutstandingBalanceAmount = trim($amountPaid['Symbol']) . ' ' . trim($balanceAmount);
            $postData = array(
                "UserSysId" => trim($arrPackage['AgentSysId']),
                // "IsSchedule" => False,
                "schedule_time" => "",
                "title" => "Payment reminder",
                "body" => "$customerFirstName  $DestinationPlaces trip payment is due for $OutstandingBalanceAmount. Kindly remind the client.",
                //"IsButton" => True,
                "URL" => "customer/customer-booking/id/" . base64_encode($intCustSysId) . "/code/" . $CustomersecureCode,
                "IsCall" => true,
                "mobileNo" => trim($CustomerMobileNumber)
            );
            if (isset($arrAgentDetails['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($arrAgentDetails['SecurityKey']),
                    //'Content-Type: application/json'
                    ),
                ));
                $response = curl_exec($curl);
                curl_close($curl);
            }
        }
    }

    public function bookingPaymentHistoryAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {

            $TPSysId = $this->getRequest()->getParam('TPSysId');
            $objTrx = new Travel_Model_TblAgencyCustomerTrx();
            $this->view->arrPaymentHistory = $arrPaymentHistory = $objTrx->getTrasactionProposalByTPSysId($TPSysId);
        }
    }

    // Added By Pardeep Panchal Ends       

    public function sendquickpackageproposalAction() {
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);
        $objPackage = new Travel_Model_TblPackage();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $postData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($postData);die;
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $IsSendMail = isset($postData['IsSendMail']) ? $postData['IsSendMail'] : 0;
            $IsSendSms = isset($postData['IsSendSms']) ? $postData['IsSendSms'] : 0;
            $MarkUp = isset($postData['MarkUp']) ? (int) $postData['MarkUp'] : 0;
            $discountValue = isset($postData['discountValue']) ? (int) $postData['discountValue'] : 0;
            $GSTApplicableOn = isset($postData['gsttype']) ? $postData['gsttype'] : 0;
            $GSTAmount = $DiscountArrayServiceTax = $MarkupArrayServiceTax = 0;
            $Isclipboard = isset($postData['Isclipboard']) ? $postData['Isclipboard'] : 0;
            $MarkupWDiscount = $MarkUp - $discountValue;
            if ($MarkupWDiscount > 0) {
                $arrInputData = array(
                    "GSTApplicableOn" => $GSTApplicableOn,
                    "intProductType" => 9,
                    "intProductGeoType" => 1,
                    "Cost" => 0,
                    "AgencyMarkUp" => 0,
                    "AgencyExtraMarkUp" => $MarkUp,
                    "AgencyDiscount" => $discountValue
                );

                $arrGSTCalculations = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->calculateGST($arrInputData);
                $GSTAmount = $arrGSTCalculations['GSTAmount'];
                $DiscountArrayServiceTax = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($discountValue, $arrGSTCalculations['TaxRate']);
                $DiscountArrayServiceTax = !empty($DiscountArrayServiceTax) ? $DiscountArrayServiceTax : 0;
                $arrServiceTaxOnNetPayable = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->calculatePercentage($MarkUp, $arrGSTCalculations['TaxRate']);
                $MarkupArrayServiceTax = !empty($arrServiceTaxOnNetPayable) ? $arrServiceTaxOnNetPayable : 0;
            }

            //echo "<pre>";print_r($arrGSTCalculations['GSTAmount']);die;

            $ARR_SALUTION = unserialize(ARR_SALUTION);
            $tpproposalID = $postData['TPSysId'];
            $ccemail = $postData['ccemail'] ? $postData['ccemail'] : '';
            $GreetingsMessage = $postData['GreetingsMessage'] ? $postData['GreetingsMessage'] : '';
            $EmailTemplateType = $postData['EmailTemplateType'];
            $EmailTemplateColor = $postData['EmailTemplateColor'];
            $proposalEmailFrom = (isset($postData['senderEmailID']) && !empty($postData['senderEmailID'])) ? trim($postData['senderEmailID']) : trim($sessionLogin_user->EmailId);
            $emailsubject = $postData['emailsubject'] ? trim($postData['emailsubject']) : '';
            $enctpproposalID = base64_encode($tpproposalID);
            $secureCodeMain = Catabatic_ValidateCustomer::secureCode($enctpproposalID, 1);
            $booknowurl = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . $enctpproposalID . '/code/' . $secureCodeMain;
            $AgentSysId = $this->intLoggedinUserId;
            $agentDetails = $this->_crmcusttravelplan->getAgentDetails($AgentSysId);
            $objAgency = new Travel_Model_TblAgency();
            $getBankDetails = $objAgency->getBankDetailsByAgency($this->intLoggedinUserAgencySysId);
            $getAgencyAddress = $objAgency->getAddressByAgency($this->intLoggedinUserAgencySysId);
            $markupMdl = new Markup_Model_Markup();
            $isDisplayAgencyTax = $markupMdl->getDetailsAgencyCurrencyDeatil("TB_Agency", $this->intLoggedinUserAgencySysId);
            $isDisplayTax = $isDisplayAgencyTax['TaxLabelId'];
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $objSupplier = new Travel_Model_TblSupplier();
            $transactiontravelplandataR = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpproposalID); // get proposal data from customer travel plan

            $XServiceTaxAmount = $GSTAmount + $transactiontravelplandataR[0]['XServiceTaxAmount'];

            $getAllAddonServices = $this->_objPackage->getTravelPlanAddonServicesMultipleIds($this->intLoggedinUserAgencySysId, $tpproposalID, array(21));
            $GTXNetworkAgencySysId = 0;

            $displayTCS = (isset($getAllAddonServices[0]['displayTCS'])) ? (int) $getAllAddonServices[0]['displayTCS'] : 0;
            $Tax = (isset($getAllAddonServices[0]['Tax'])) ? (int) $getAllAddonServices[0]['Tax'] : 0;

            $IsB2BAgent = $postData['IsB2BAgent'] ? (int) $postData['IsB2BAgent'] : 0;
            $selectedCustomerId = $postData['selectedCustomerId'] ? (int) base64_decode($postData['selectedCustomerId']) : '';
            if ((int) $transactiontravelplandataR[0]['IsB2BProposal'] == 1 && $selectedCustomerId > 0) {
                $getB2bAgencySysId = $this->_crmcusttravelplan->getB2bAgencySysId($selectedCustomerId);
                $GTXNetworkAgencySysId = isset($getB2bAgencySysId[0]['AgencySysId']) ? $getB2bAgencySysId[0]['AgencySysId'] : 0;
            }
            if (strlen($GreetingsMessage) > 4000) {
                echo json_encode(array('status' => false, 'message' => 'Greeting Message Limit Exceed!!'));
                exit;
            }

            $MultiOptions = array();
            if ($transactiontravelplandataR[0]['EconomyMask'] == 6) {
                $MultiOptions = json_decode($transactiontravelplandataR[0]['MultiOptions'], 1);

                $MultiOptionsVal = array_values($MultiOptions);
                //              print_r($transactiontravelplandataR);
                $MultiOptionsVal = array_keys($MultiOptionsVal[0]);

                $versions = implode(',', $MultiOptionsVal);
                // print_r($versions);die;
                $whereQuery = "TPSysId = " . $transactiontravelplandataR[0]['MasterTPSysId'];
                $masterTPSysId = $transactiontravelplandataR[0]['MasterTPSysId'];
                $where = "MasterTPSysId =  $masterTPSysId  AND VersionId IN ($versions)";
            } else {
                $whereQuery = "TPSysId = " . $transactiontravelplandataR[0]['MasterTPSysId'];
                $masterTPSysId = $transactiontravelplandataR[0]['MasterTPSysId'];
                $where = "TPSysId =  $tpproposalID";
            }
            $IsShareWithGST = isset($postData['GSTIncluded']) ? $postData['GSTIncluded'] : 0;
            $StatusType = 2;
            $updatetravelplanQuery = array(
//                'IsOperationalLead' => 0,
                'UpdateDate' => $this->currentDate,
                'IsDraft' => 0,
                'GreetingMessage' => substr($GreetingsMessage, 0, 4000),
                'IsShared' => 1,
                'EmailTemplateType' => !empty($EmailTemplateType) ? $EmailTemplateType : '1',
                'EmailTemplateColor' => !empty($EmailTemplateColor) ? $EmailTemplateColor : 'default',
                'IsShareWithGST' => $IsShareWithGST,
                'ProposalEmailFrom' => $proposalEmailFrom,
//                'B2BAgencySysId' => $GTXNetworkAgencySysId,
                'ExpectedClosureDate' => $transactiontravelplandataR[0]['StartDate']->format('Y-m-d'),
                'ExpectedValue' => $transactiontravelplandataR[0]['NetPrice'],
                    //                'SelectPricingType' => !empty($postData['SelectPricing']) ? $postData['SelectPricing'] : 'Overall' // this value is set at quick package creation
            );
            if (empty($transactiontravelplandataR[0]['RefTPSysId'])) {
                $updatetravelplanQuery['StatusType'] = $StatusType;
            }

            $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplanQuery, $whereQuery);

            $NetPrice = $transactiontravelplandataR[0]['NetPrice'] + ($MarkUp - $discountValue) + $GSTAmount;
            $updatetravelplan = array(
//                'IsOperationalLead' => 0,
                'AgentSysId' => $AgentSysId,
                'UpdateDate' => $this->currentDate,
                'IsDraft' => 0,
                'StatusType' => 4,
                'GreetingMessage' => substr($GreetingsMessage, 0, 4000),
                'IsShared' => 1,
                'EmailTemplateType' => !empty($EmailTemplateType) ? $EmailTemplateType : '1',
                'EmailTemplateColor' => !empty($EmailTemplateColor) ? $EmailTemplateColor : 'default',
                'IsShareWithGST' => $IsShareWithGST,
                'ProposalEmailFrom' => $proposalEmailFrom,
//                'B2BAgencySysId' => $GTXNetworkAgencySysId,
//                'SelectPricingType' => !empty($postData['SelectPricing']) ? $postData['SelectPricing'] : 'Overall' // this value is set at quick package creation
            );
            /* Start For Operation Staff Package */
            if ($MarkupWDiscount > 0) {
                $updatetravelplan['ExtraMarkup'] = $MarkUp;
                $updatetravelplan['CustomDiscount'] = $discountValue;
                $updatetravelplan['NetPrice'] = $NetPrice;
                //                $updatetravelplan['XServiceTaxAmount'] = $XServiceTaxAmount;
                $updatetravelplan['ServiceTaxOnCustomDiscount'] = $DiscountArrayServiceTax;
                $updatetravelplan['AgentsCustomServiceTaxAmount'] = $MarkupArrayServiceTax;
            }
            /* End For Operation Staff Package */

            //echo "<pre>";print_r($updatetravelplan);die;
            $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplan, $where);

            $deldata = array("CurrencyType" => 1);
            $whereMPR = array('TPIntSysId = ?' => $tpproposalID);
            $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_MarketWise_Rate', $deldata, $whereMPR);

            //            $ClosureData = $this->_crmcusttravelplan->expectedClosureData($masterTPSysId, $expectedClosureData);
            /* Start For Operation Staff Package */
            if ($MarkupWDiscount > 0) {
                $FullServiceTax = $XServiceTaxAmount;
                $TotalMarkup = (float) $transactiontravelplandataR[0]['MarkUp'] + $MarkUp;
                $updateAddon = [
                    'Tax' => (float) $FullServiceTax,
                    'Markup' => (float) $TotalMarkup,
                    'TotalCost' => (float) $transactiontravelplandataR[0]['Price'] + (float) $FullServiceTax + (float) $TotalMarkup,
                ];
                $whereAddon = array('TPSysId = ?' => $tpproposalID, 'PlanType = ?' => 5);
                $this->_objPackage->updateData('TB_Agency_Customer_TravelPlan_AddonServices', $updateAddon, $whereAddon);
            }
            $TPArray = array();
            if (!empty($transactiontravelplandataR[0]['MultiOptions'])) {
                $MultiOptions = json_decode($transactiontravelplandataR[0]['MultiOptions'], 1);
                $MultiOptionsVal = array_values($MultiOptions);
                $MultiOptionsVal = array_keys($MultiOptionsVal[0]);
                $TPArray = $this->_crmcusttravelplan->GetTravelPlanByVersion($transactiontravelplandataR[0]['MasterTPSysId'], $MultiOptionsVal);
            }

            /* End For Operation Staff Package */
            //            print_r($updatetravelPlan);die;
            if (!empty($TPArray)) {
                $muy2 = 1;

                foreach ($TPArray as $totalHotelOptionCountKey => $totalHotelOptionCountVal) {

                    $enctpproposalID = base64_encode($totalHotelOptionCountVal['TPSysId']);

                    $secureCode = Catabatic_ValidateCustomer::secureCode($enctpproposalID, 1);
                    $booknowurl1 = $booknowurl = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . $enctpproposalID . '/code/' . $secureCode;
                    if ($agentDetails['IsB2CSite'] == 1) {
                        $booknowurl1 = $agentDetails['Url'] . "detail/index/view/id/" . base64_encode($booknowurl);
                    } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 1)) {
                        $booknowurl1 = $agentDetails['Url'] . "hellogtx/index.html?id=" . base64_encode($booknowurl);
                    } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 0)) {
                        $booknowurl1 = $agentDetails['Url'] . "hellogtx/gtx.php?id=" . base64_encode($booknowurl);
                    }
                    $booknowurlArr[$muy2] = $booknowurl1;
                    $muy2++;
                }
            } else {
                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);
                }
                $booknowurlArr[1] = $booknowurl;
            }

            $DefaultPDF = (isset($agentDetails['DefaultPDF']) && $agentDetails['DefaultPDF'] > 0) ? (int) $agentDetails['DefaultPDF'] - 1 : 0;
            $transactiontravelplandata = $this->_crmcusttravelplan->GetTravelPlanByCustomer($tpproposalID);
            // if ($postData['submitType'] == 'save') {
            $CustPackageRoomwisePrice = array();
            ################# Send Mail to Customer ##############
            //            echo '<pre>'; print_r(); die;

            $firstname = $sessionLogin_user->FirstName ? $sessionLogin_user->FirstName . ' ' . $sessionLogin_user->LastName : 'Agent';
            $primarycontact = $sessionLogin_user->ContactNo1 ? $sessionLogin_user->ContactNo1 : 'N/A';
            //         echo '<pre';print_r($transactiontravelplandata[0]['NetPrice']); die;
            $agencyDisplayName = trim($sessionLogin_user->agencyDetails['DisplayName']);
            $PrimaryEmail = trim($sessionLogin_user->agencyDetails['PrimaryEmail']);
            $sendersEmailId = trim($sessionLogin_user->EmailId);
            //        $sendersEmailId = ($IsEmailIdForCustVarified == 1) ? $EmailIdForCustomer : $AgentEmailId;
            $agencyDisplayName = (!empty($agencyDisplayName)) ? $agencyDisplayName : trim($sessionLogin_user->agencyDetails['Title']);

            $Logo = $sessionLogin_user->Logo;
            $CurrSymbol = trim($transactiontravelplandata[0]['Symbol']);

            $sentprice = $CurrSymbol . ' ' . round($transactiontravelplandata[0]['NetPrice']); //totall cost
            if ($IsShareWithGST == 1) {
                $sentprice = $CurrSymbol . ' ' . round($transactiontravelplandata[0]['NetPrice']);
            } else {
                $PackageArray = $transactiontravelplandata[0];
                $totalCost = (float) $PackageArray['NetPrice'] - ((float) $PackageArray['XServiceTaxAmount'] + (float) $PackageArray['AgentServiceTaxAmount'] + (float) $PackageArray['AgentsCustomServiceTaxAmount'] - (float) $PackageArray['ServiceTaxOnCustomDiscount']);
                $sentprice = $CurrSymbol . ' ' . round($totalCost, 2);
            }
            $path = SITE_FULL_URL . 'public/assets/images';
            $pathAgency = SITE_FULL_URL . 'public/upload/media/agency/' . $this->intLoggedinUserAgencySysId;
            if (isset($Logo) && $Logo != '') {
                $AgencyLogo = $pathAgency . '/' . $Logo;
            } else {
                $AgencyLogo = $path . '/gtx-logo-white.png';
            }

            //            $aboutpackage = !empty($postData['EmailContent']) ? $postData['EmailContent'] : '';
            $packageRoomInfoArr = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getPackageRoomInfo($transactiontravelplandata[0]['RoomInfoJson'], $transactiontravelplandata[0]['PKqueryType']);
            $AdultCount = $packageRoomInfoArr['onlyCount']['adultCount'];
            $ChildCount = $packageRoomInfoArr['onlyCount']['childWBCount'] + $packageRoomInfoArr['onlyCount']['childWOBCount'] + $packageRoomInfoArr['onlyCount']['childFreeCount'];
            $infantCount = $packageRoomInfoArr['onlyCount']['infantCount'];
            $EmailText = isset($transactiontravelplandata[0]['EmailText']) ? json_decode($transactiontravelplandata[0]['EmailText'], 1) : '';
            $getsuppliertype = $objSupplier->getSupplierServicesbyId($transactiontravelplandata[0]['EconomyMask']);
            $SalutationTitle = isset($ARR_SALUTION[$transactiontravelplandata[0]['Salutation']]) ? $ARR_SALUTION[$transactiontravelplandata[0]['Salutation']] : '';
            $params['EconomyMaskTitle'] = (isset($getsuppliertype[0]['Title']) && !empty($getsuppliertype[0]['Title'])) ? $getsuppliertype[0]['Title'] : '';
            $params['IsFromGTXNetwork'] = 0;
            $params['packageID'] = $tpproposalID;
            $params['intLoggedinUserAgencySysId'] = $this->intLoggedinUserAgencySysId;
            $params['agency_logo'] = $AgencyLogo;
            $params['trip_address'] = $transactiontravelplandata[0]['DestinationPlaces'];
            $params['shared_url'] = $booknowurlArr;
            $params['sent_price'] = $sentprice; //total price with currency
            $params['price'] = $transactiontravelplandata[0]['Price']; // total price
            $params['travelers'] = array('Adults' => $AdultCount, 'Child' => $ChildCount, 'Infants' => $infantCount); // travelers to display
            $params['cust_name'] = trim($SalutationTitle . ' ' . ucfirst(stripslashes(trim($transactiontravelplandata[0]['FirstName']))) . ' ' . ucfirst(stripslashes(trim($transactiontravelplandata[0]['LastName']))));
            $params['GreetingMessage'] = $transactiontravelplandata[0]['GreetingMessage'];
            $params['about_package'] = $transactiontravelplandata[0]['EmailText']; // total price;
            //$params['aboutEmailContent'] = $EmailText; // total price;
            $params['agent_firstname'] = $firstname;
            $params['agent_primarycontact'] = $primarycontact;
            $params['file_path_location'] = $path;
            $params['sendersEmailId'] = $proposalEmailFrom;
            $params['agencyDisplayName'] = $agencyDisplayName;
            $params['b2bagencyDisplayName'] = (isset($transactiontravelplandata[0]['CompanyName'])) ? $transactiontravelplandata[0]['CompanyName'] : '';
            $params['PrimaryEmail'] = $PrimaryEmail;
            $params['TPSysId'] = $tpproposalID;
            $params['AgentSysId'] = $AgentSysId;
            $params['AgencySysId'] = $sessionLogin_user->intLoggedinUserAgencySysId;
            $params['PackageArray'] = $transactiontravelplandata[0];
            $params['agentDetails'] = $agentDetails;
            $params['isDisplayTax'] = $isDisplayTax;
            $params['CustomerSysId'] = $transactiontravelplandataR[0]['CustomerSysId'];
            $subject = ($emailsubject != '') ? $emailsubject : 'Proposal Details';
            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $params['arrEmailStatisticsType'] = $arrEmailStatisticsType[0];
            $params['CurrencyId'] = $transactiontravelplandata[0]['CurrencyType'];
            $params['CurrencySymbol'] = $CurrSymbol;
            $params['flightPriceArray'] = $EmailText['flightPriceArray'];
            $params['visaPriceArray'] = $EmailText['visaPriceArray'];
            $params['IsSMSApi'] = $this->IsSMSApi;
            $params['BankDetails'] = $getBankDetails;
            $params['CompanyAddress'] = trim($getAgencyAddress['Address']);

            $custemail = $transactiontravelplandata[0]['EmailId'];
            $mailToCC = array();
            if ($ccemail != '') {
                $mailToCC = explode(',', $ccemail);
            }

            if (!empty($IsB2BAgent)) {
                $getcustomerdetails = $this->_crmcustomerObj->GetCustomerDetailsByEmailB2B(trim($custemail), $params['AgencySysId']);
            } else {
                $getcustomerdetails = $this->_crmcustomerObj->GetCustomerDetailsByEmail(trim($custemail), $params['AgencySysId']);
            }
            $params['b2bagencyDisplayName'] = (isset($getcustomerdetails['CompanyName'])) ? trim($getcustomerdetails['CompanyName']) : '';
            $params['customer_contact'] = trim($getcustomerdetails['Contacts']);
            $params['customer_countrycode'] = trim($getcustomerdetails['countrycode']);

            if ($Isclipboard == 1) {
                $copyclipboardbody = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->CopyEmailBodyToClipboard($custemail, $subject, $params, $mailToCC);
            }
            if ($IsSendMail == 1) {
                $emailStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('EmailTemplate')->SendProposalToCustomer($custemail, $subject, $params, $mailToCC);
            } else {
                $emailStatus = 1;
            }

            if ($params['customer_contact'] != '') {
                $arrSMSStatisticsType = array_keys(unserialize(ARR_SMS_STATISTICS_TYPE));
                $params['arrSMSStatisticsType'] = $arrSMSStatisticsType[0];
                if ($IsSendSms == 1) {

                    // $smsStatus = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->SendSmsToCustomer($params);
                }

                $shorturl_response = Zend_Controller_Action_HelperBroker::getStaticHelper('ShortUrl')->url_get($params);
                if (isset($shorturl_response['status_code']) && $shorturl_response['status_code'] == 200) {
                    $booknowurl = $shorturl_response['data']['short_url'];
                }
            }

            if ($emailStatus == 1) {
                $queryData = $objPackage->GetTravelPlanQueryDetails($transactiontravelplandata[0]['MasterTPSysId']); // get query data from customer travel plan
                if (!empty($queryData['EnSupPackId'])) {
                    Zend_Controller_Action_HelperBroker::getStaticHelper('PackageSearch')->enqsupupdatestatus($queryData['EnSupPackId'], 2); //2 for proposal
                }

                $totalCostHtml = $DynamicUrl = '';
                if (!empty($TPArray)) {
                    $mm = 1;
                    foreach ($TPArray as $tpKey => $tpVal) {
                        $mMultiOptions = json_decode($tpVal['MultiOptions'], 1);
                        $options = array_keys($mMultiOptions);
                        $CustPackageRoomwisePrice = $this->_crmcusttravelplan->getCustPackageRoomwisePrice($tpVal['TPSysId']);

                        $enctpproposalID = base64_encode($tpVal['TPSysId']);
                        $secureCode = Catabatic_ValidateCustomer::secureCode($enctpproposalID, 1);
                        $DynamicUrl = '/publicpackage/view-customer-final-package/id/' . $enctpproposalID . '/code/' . $secureCode;
                        $booknowurl = $this->baseUrl . '/publicpackage/view-customer-final-package/id/' . $enctpproposalID . '/code/' . $secureCode;

                        if ($agentDetails['IsB2CSite'] == 1) {
                            $DynamicUrl = "detail/index/view/id/" . base64_encode($booknowurl);
                            $booknowurl = $agentDetails['Url'] . "detail/index/view/id/" . base64_encode($booknowurl);
                        } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 1)) {
                            $DynamicUrl = "hellogtx/index.html?id=" . base64_encode($booknowurl);
                            $booknowurl = $agentDetails['Url'] . "hellogtx/index.html?id=" . base64_encode($booknowurl);
                        } else if (($agentDetails['IsB2CSite'] == 2) && ($agentDetails['IsSiteType'] == 0)) {
                            $DynamicUrl = "hellogtx/gtx.php?id=" . base64_encode($booknowurl);
                            $booknowurl = $agentDetails['Url'] . "hellogtx/gtx.php?id=" . base64_encode($booknowurl);
                        }
                        $bitly_response = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->getSmallLinkFromBitlyAPI($booknowurl, $this->BITLYLOGIN, $this->BITLYAPIKEY);
                        if ($bitly_response['errorCode'] == 0) {
                            $booknowurl = $bitly_response['results'][$booknowurl]['shortUrl'];
                        }
                        $sharedmealId = ($params['PackageArray']['PackageCostCalType'] == 1) ? @$params['PackageArray']['SharedMealPlanType'] : 0;
                        $getHotelsBySequenceArrayI = Zend_Controller_Action_HelperBroker::getStaticHelper('Package')->getAllSelectedCustomerHotels($tpVal['TPSysId'], $params['PackageArray']['EconomyMask'], $sharedmealId, $params['PackageArray']['Readymade']);
                        $GSTApplicable = $transactiontravelplandata[0]['GSTSharedMode'];
                        $objGstRates = new Travel_Model_TblGstRates();
                        $arrGSTRatesInfo = $objGstRates->getGSTTypeAndRates(9, $GSTApplicable, 0, 0);
                        $TaxRate = $arrGSTRatesInfo['TaxRate'];
                        $TaxType = $arrGSTRatesInfo['TaxType'];
                        $getHotelsBySequenceArrayNew = array();
                        foreach ($getHotelsBySequenceArrayI as $b => $getHotelsBySequenceArrayIVal) {
                            foreach ($getHotelsBySequenceArrayIVal as $b1 => $getHotelsBySequenceArrayIVal1) {
                                //echo "<pre>";print_r($getHotelsBySequenceArrayIVal1['startSequence']);die;
                                $getHotelsBySequenceArrayNew[] = [
                                    'CityName' => $getHotelsBySequenceArrayIVal1['hotels'][0]['CityName'],
                                    'Title' => $getHotelsBySequenceArrayIVal1['hotels'][0]['Title'],
                                    'RoomTitle' => (isset($getHotelsBySequenceArrayIVal1['hotels'][0]['RoomTitle']) && !empty(trim($getHotelsBySequenceArrayIVal1['hotels'][0]['RoomTitle']))) ? $getHotelsBySequenceArrayIVal1['hotels'][0]['RoomTitle'] : $getHotelsBySequenceArrayIVal1['hotels'][0]['RoomTypeStr'],
                                    'RoomMealType' => $getHotelsBySequenceArrayIVal1['hotels'][0]['RoomMealType'],
                                    'Stars' => $getHotelsBySequenceArrayIVal1['hotels'][0]['Stars'],
                                    'Nights' => $getHotelsBySequenceArrayIVal1['endSequence'] - $getHotelsBySequenceArrayIVal1['startSequence'],
                                ];
                            }
                        }
                        if (count($TPArray) > 1) {
                            $totalCostHtml .= '%0a%0a=========%0a*Option ' . $mm . '.*';
                        }
                        $HotelHtml = '';

                        if (!empty($getHotelsBySequenceArrayNew)) {
                            foreach ($getHotelsBySequenceArrayNew as $hKey => $hVal) {
                                $totalCostHtml .= ($hVal['CityName'] != '') ? '%0a%0a' . $hVal['CityName'] . '(' . $hVal['Nights'] . 'N)' : '';
                                $totalCostHtml .= (trim($hVal['Title']) != '') ? ': *' . trim($hVal['Title']) . '*' : '';
                                $totalCostHtml .= (!empty((int) $hVal['Stars'])) ? ' - ' . (int) $hVal['Stars'] . ' Star' : '';
                                $RoomTitle = (!empty($hVal['RoomTitle'])) ? trim($hVal['RoomTitle']) : '';
                                $RoomMealType = (!empty($hVal['RoomMealType'])) ? trim($hVal['RoomMealType']) : '';
                                $mmMarkUpPerRoom = (!empty($CustPackageRoomwisePrice)) ? $transactiontravelplandata[0]['MarkUp'] / count($CustPackageRoomwisePrice) : 0;
                                foreach ($CustPackageRoomwisePrice as $rpKey => $rpVal) {
                                    $NoOfNight = (int) $rpVal['NoOfNight'];
                                    $mmMarkUpPerRoomPerNights = (float) ($mmMarkUpPerRoom / $NoOfNight);
                                    $totalCostHtml .= '%0a%0a*Room ' . ((count($CustPackageRoomwisePrice) > 1) ? $rpKey + 1 : '') . ':* ' . $RoomTitle . ' (' . $RoomMealType . ')';
                                    $Cost = $CurrSymbol . ' ' . getPriceWithGST(((int) $rpVal['Cost'] + $mmMarkUpPerRoomPerNights), $mmMarkUpPerRoomPerNights, $TaxType, $TaxRate) . '/-';
                                    $TotalCost = $CurrSymbol . ' ' . getPriceWithGST(((int) $rpVal['TotalCost'] + $mmMarkUpPerRoom), $mmMarkUpPerRoom, $TaxType, $TaxRate) . '/-';
                                    $totalCostHtml .= '%0a*Per Night Cost*: ' . $Cost;
                                    if (count($CustPackageRoomwisePrice) > 1) {
                                        $totalCostHtml .= '%0a*Cost for ' . ((int) $transactiontravelplandata[0]['NoofNight']) . ' Nights*: ' . $TotalCost;
                                    }
                                }

                                $HotelHtml .= trim($hVal['CityName']) . '(' . $hVal['Nights'] . 'N): *' . trim($hVal['Title']) . '*\n\n';
                            }
                        }

                        $NetPrice = round($tpVal['NetPrice']);
                        if ($displayTCS == 1) {
                            $NetPrice = $NetPrice + $Tax;
                        }
                        $totalCostHtml .= '%0a%0a=====%0a*Total Cost:* ' . $CurrSymbol . ' ' . $NetPrice . '/-%0a=====%0a%0aTo view details and *book online* click on the below link:%0a' . $booknowurl;
                        $mm++;
                    }
                } else {
                    $totalCostHtml = '%0a%0a*Total Cost:* ' . $sentprice . '/-%0a%0aTo view details and *book online* click on the below link:%0a%0a' . $booknowurl;
                }

                //                echo $HotelHtml;die;
                $custname = trim($params['cust_name']);
                $AgenctEmailId = trim($agentDetails['EmailId']);
                $destinationValues = trim($transactiontravelplandata[0]['DestinationPlaces']);
                $roomjson = json_decode($transactiontravelplandata[0]['RoomInfoJson'], 1);
                $noofRooms = $NoofDays = '';
                $TravelDate = (isset($transactiontravelplandata[0]['StartDate'])) ? '%0a%0a*Travel Date:* ' . ($transactiontravelplandata[0]['StartDate']->format('d M y')) : '';
                if (isset($transactiontravelplandata[0]['IsOnlySightseeingPkg']) && $transactiontravelplandata[0]['IsOnlySightseeingPkg'] == 1) {
                    $packageTypeText = 'sightseeing';
                    $getIncludedSightseeingArr = $this->_crmcusttravelplan->getIncludedPackageSightseenList($tpproposalID, 'FreeSight');
                    // echo "<pre>";print_r($getIncludedSightseeingArr);die;
                    $fianlShowSightseeingArray = array();
                    $fianlShowSightseeingHtml = '';
                    foreach ($getIncludedSightseeingArr as $sssKey => $sssVal) {
                        $fianlShowSightseeingArray[] = trim($sssVal['Title']);
                    }
                    if (!empty($fianlShowSightseeingArray)) {
                        $fianlShowSightseeingHtml = '%0a%0a*Sightseeings:* ' . implode(', ', $fianlShowSightseeingArray);
                    }
                } else {

                    $packageTypeText = 'package';
                    if (isset($transactiontravelplandata[0]['IsHotelOnlyPackage']) && $transactiontravelplandata[0]['IsHotelOnlyPackage'] == 1) {
                        $packageTypeText = 'hotel';
                    }
                    $noofRooms = (isset($roomjson) && !empty($roomjson)) ? '%0a%0a*No of Rooms:* ' . count($roomjson) : '';
                    $NoofDaysHtml = ((int) $transactiontravelplandata[0]['NoofNight']) . ' Night';
                    if ($transactiontravelplandata[0]['NoofNight'] > 1) {
                        $NoofDaysHtml .= 's';
                    }
                    $NoofDaysHtml .= '/ ' . ((int) $transactiontravelplandata[0]['NoofNight'] + 1) . ' Day';
                    if ($transactiontravelplandata[0]['NoofNight'] > 0) {
                        $NoofDaysHtml .= 's';
                    }
                    $NoofDays = '%0a%0a*No of Nights:* ' . $NoofDaysHtml;
                }
                if ($ChildCount > 0) {
                    $ChildCount = "$ChildCount Child(s)";
                } else {
                    $ChildCount = '';
                }
                if ($infantCount > 0) {
                    $infantCount = "$infantCount Infant(s)";
                } else {
                    $infantCount = '';
                }

                if ($_SESSION['sessionLogin_user']['IsWhatsApp'] == 1 && trim($getcustomerdetails['countrycode']) != '') {

                    $whatsappData = array(
                        'SecurityKey' => $agentDetails['SecurityKey'],
                        'CustomerName' => $custname,
                        'CustomerMobile' => trim($getcustomerdetails['countrycode']) . trim($getcustomerdetails['Contacts']),
                        'Destination' => $destinationValues,
                        'TravelDate' => $transactiontravelplandata[0]['StartDate']->format('d M y'),
                        'NoofDays' => (int) $transactiontravelplandata[0]['NoofNight'] + 1,
                        'Travellers' => $AdultCount . ' Adult(s) ' . $ChildCount . ' ' . $infantCount,
                        'DestinationWiseHotel' => ($HotelHtml != '') ? str_replace('\n', '', $HotelHtml) : '',
                        'TotalCost' => ' ' . $sentprice,
                        'AgentName' => $firstname,
                        'AgencyDisplayName' => $agencyDisplayName,
                        'AgentContactNo' => $primarycontact,
                        'DynamicUrl' => $DynamicUrl,
                    );
                    $this->_crmcusttravelplan->sendWhatsAppMessage($whatsappData, $this->baseUrl);
                }


                $whatsappmessage = "*Dear $custname*,%0a%0aThanks for your $packageTypeText query for $destinationValues.%0a%0a*Destination:* $destinationValues $fianlShowSightseeingHtml $TravelDate $NoofDays  %0a%0a*No of Pax:* $AdultCount Adult(s) $ChildCount $infantCount $noofRooms $totalCostHtml  %0a%0aYou can also call $firstname at $primarycontact or email at $proposalEmailFrom or whatsapp me here.%0a%0aRegards %0a%0a$firstname, %0a$agencyDisplayName";

                $response = array('status' => 'success', 'whatsapp' => $whatsappmessage, 'contactno' => trim($getcustomerdetails['countrycode']) . trim($getcustomerdetails['Contacts']), 'message' => 'Proposal has been shared with customer', 'TPSysId' => @$tpproposalID, 'codeMain' => $secureCodeMain, 'enctpproposalID' => $enctpproposalID, 'code' => $secureCode, 'DefaultPDF' => $DefaultPDF);
            } else {
                $response = array('status' => 'fail', 'message' => 'There is some error in sending email. Please try after sometime.');
            }
            if ($Isclipboard == 1) {
                $response = array('status' => 'success', 'Isclipboard' => 1, 'copyclipboardbody' => $copyclipboardbody, 'message' => 'Email body copied to clipboard', 'TPSysId' => @$leadID, 'enctpproposalID' => $enctpproposalID, 'code' => $secureCode, 'DefaultPDF' => $DefaultPDF);
            }
            echo json_encode($response);
            exit;
            //}
        }
    }

    public function getmealypebuildpckAction() {

        $this->_helper->layout->disableLayout();
        //$this->_helper->viewRenderer->setNoRender(false);
        //if ($this->getRequest()->isXmlHttpRequest()) {
        $objHotelMealType = new Travel_Model_Master_Mealtype();
        $arrHotelRoomMealTypes = $objHotelMealType->getRoomMealtypes();
        //      
        //echo "<pre>";print_r($result);die;
        echo json_encode($arrHotelRoomMealTypes);
        exit;
        //}
    }

    public function quickPackageListingAction() {
        $agencySysId = $this->intLoggedinUserAgencySysId;
        $getQid = $this->getRequest()->getParam('qid', 0);
        $check_string = is_numeric($getQid);
        if (!$check_string) {
            $qid = base64_decode($getQid);
        } else {
            $qid = $getQid;
        }
        $model = new Travel_Model_PackageSearch();
        $customerTravelPlan = new Travel_Model_CRM_CustomerTravelPlan();
        $getCustomerTravelPlanData = $customerTravelPlan->GetCustomerTravelPlanByTPID($qid, 'query');
        $destination_name2 = '';
        $code = $this->getRequest()->getParam('code');
        $secureCode = Catabatic_ValidateCustomer::secureCode($getQid, 1);
        if ($code != $secureCode) {
            echo "Do not change qid or code";
            exit;
        }
        $this->view->secureCode = $secureCode;
        //         echo "<pre>";print_r($getCustomerTravelPlanData);die;
        if (!empty($getCustomerTravelPlanData)) {
            if (isset($getCustomerTravelPlanData[0]['DestinationPlaces']) && ($getCustomerTravelPlanData[0]['DestinationPlaces'] != "")) {
                $destination_name = $getCustomerTravelPlanData[0]['DestinationPlaces'];
                $destination_name1 = explode('(', $destination_name);
                $destination_name2 = trim($destination_name1[0]);
            }
        }

        $travel_date = '';
        $creation_date = '';
        $cust_name = '';
        $postData = $this->getRequest()->getPost();

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

            $cust_name = isset($postData['cust_name']) ? $postData['cust_name'] : '';
            if (isset($postData['creation_date']) && $postData['creation_date'] != '__/__/____') {
                $creation_date = date("Y-m-d", strtotime(str_replace('/', '-', $postData['creation_date'])));
            }
            if (isset($postData['travel_date']) && $postData['travel_date'] != '__/__/____') {

                $travel_date = date("Y-m-d", strtotime(str_replace('/', '-', $postData['travel_date'])));
            }
            $destination_name2 = '';
            $destination_name = isset($postData['destination_name']) ? $postData['destination_name'] : '';
            $destination_name1 = explode('(', $destination_name);
            $destination_name2 = trim($destination_name1[0]);
        }

        $this->view->cust_name = $cust_name;
        $this->view->creation_date = $creation_date;
        $this->view->travel_date = $travel_date;
        $this->view->destination_name2 = $destination_name2;

        $model->srtSearchData = '';
        $model->srtSearchDataDes = '';

        $model->srtSearchData .= "  t1.IsMarkForDel = '0' AND  t1.PKqueryType = " . (int) $getCustomerTravelPlanData[0]['PKqueryType'] . " AND t1.AgencySysId = " . $this->intLoggedinUserAgencySysId;
        if ($getCustomerTravelPlanData[0]['PlanType'] == 2) {
            $model->srtSearchData .= " AND t1.IsHotelOnlyPackage = 1";
        } else {
            $model->srtSearchData .= " AND t1.IsHotelOnlyPackage = 0";
        }
        if (!empty($cust_name)) {
            $model->srtSearchData .= " AND (t2.FirstName like '%" . $cust_name . "%' OR t2.LastName like '%" . $cust_name . "%' OR (RTRIM(LTRIM(t2.FirstName)) + ' ' + RTRIM(LTRIM(t2.LastName))) = '" . $cust_name . "')";
        }
        if (!empty($creation_date)) {
            $model->srtSearchData .= " AND (convert(date,t1.CreateDate) = '" . $creation_date . "')";
        }
        if (!empty($travel_date)) {
            $model->srtSearchData .= " AND (convert(date,t1.StartDate) = '" . $travel_date . "')";
        }

        if ($destination_name2 != "") {


            $seachMultiData = $destination_name2;
            if (trim($seachMultiData)) {
                $expodeDataSet = explode(',', $destination_name2);
                if (!empty($expodeDataSet)) {
                    $model->srtSearchDataDes .= "  ( ";
                    for ($i = 0; $i < count($expodeDataSet); $i++) {
                        $model->srtSearchDataDes .= "  t1.SearchString LIKE '%" . trim($expodeDataSet[$i]) . "%' ";
                        if (count($expodeDataSet) > $i + 1) {
                            $model->srtSearchDataDes .= " OR ";
                        }
                    }
                    $model->srtSearchDataDes .= " ) ";
                }
            }

            // $model->srtSearchDataDes .= "(t1.SearchString like '%" . $destination_name2 . "%' or t1.SearchString like '" . $destination_name2 . ",%' or t1.SearchString like '%," . $destination_name2 . ",%' or t1.SearchString like '%," . $destination_name2 . "' or t1.SearchString like '" . $destination_name2 . "%' )";
        }

        $quickPkgSearch = $model->quickPkgListing($agencySysId);
        $this->view->qid = $qid;

        $listings = Zend_Paginator::factory($quickPkgSearch);
        $page = $this->_getParam('page', 1);
        $listings->setCurrentPageNumber($page);
        $listings->setItemCountPerPage(25);

        # End : Pagination 
        $this->view->trxData = $listings;
        $this->view->searchData = $listings;
        $this->view->per_page_record = '25';
        $this->view->page = $page;
        //echo "<pre>";print_r($quickPkgSearch);exit;    
    }

    public function searchResultFixdeparturePopupAction() {

        $this->_helper->layout->disableLayout();
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            //echo "<pre>";print_r($postData);exit;
            $pkgId = $postData['id'];
            $CurrencyType = (int) $postData['CurrencyType'];
            $marketPlaceId = $postData['marketPlaceId'];
            $code = $postData['code'];
            $qId = $postData['qId'];
            $packageType = $postData['packageType'];
            $FixedDepartureSourceSysId = isset($postData['FixedDepartureSourceSysId']) ? $postData['FixedDepartureSourceSysId'] : NULL;
            $cId = $postData['cId'];
            $pkgSearchLink = $postData['pkgSearchLink'];
            $flexiPackageList = $objPackage->getFlexiPackageList($pkgId);
            if (@$flexiPackageList['MasterRefId'] == '0') {
                $childpackarr = $objPackage->getChildPackageList(@$flexiPackageList['TPSysId']);
            } else {
                $childpackarr = $objPackage->getChildPackageList(@$flexiPackageList['MasterRefId']);
            }

            $inventoryData = array();
            $inventoryResultDate = array();
            $l = 0;
            //echo "<pre>";print_r($childpackarr);exit;
            $MasterId = 0;
            if (!empty($childpackarr)) {
                foreach ($childpackarr as $val) {
                    if ($val['MasterRefId'] == '0') {
                        $MasterId = $val['TPSysId'];
                    }
                    $inventoryData[$l] = $val['TPSysId'];
                    $l++;
                }
                //$inventoryData = array();
                if (!empty($inventoryData)) {
                    $TpSysIdString = $MasterId;
                    //                    $inventoryResultDate = $objPackage->getInventoryDateForSearchResult($intLoggedinUserAgencySysId,$TpSysIdString,$marketPlaceId,$pkgId);
                    $inventoryResultDate = $objPackage->getInventoryDateForSearchResultForNetwork($TpSysIdString, $marketPlaceId, $pkgId, $FixedDepartureSourceSysId);
                }
            }
            $TblCurrency = new Travel_Model_TblCurrency();
            $getAllCurrency = $TblCurrency->getAllConvertionRate();
            $ExchangeRateMaarkup = $this->agencyDetails['ExchangeRateMaarkup'];
            $CurrencyConversionArray = array();
            foreach ($getAllCurrency as $cKey => $cVal) {
                $RateWithMarkup = (float) $cVal['Rate'] + (float) $cVal['Rate'] * $ExchangeRateMaarkup / 100;
                $CurrencyConversionArray[$cVal['FCurrencyType'] . '-' . $cVal['TCurrencyType']] = $RateWithMarkup;
            }

            $this->view->packageType = $packageType;
            $this->view->marketPlaceId = $marketPlaceId;
            $this->view->flexiPackageList = $inventoryResultDate;
            $this->view->MasterId = $MasterId;
            $this->view->pkgId = $pkgId;
            $this->view->code = $code;
            $this->view->qId = $qId;
            $this->view->cId = $cId;
            $this->view->pkgSearchLink = $pkgSearchLink;
            $this->view->CurrencyConversionArray = $CurrencyConversionArray;
            $this->view->CurrencyType = $CurrencyType;
        }
    }

    public function getDestinationBySightseeingIdAction() {
        $this->_helper->layout->disableLayout();
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $objPackage = new Travel_Model_TblPackage();
        $objSightseeing = new Travel_Model_TblSightseeing();
        $sightSeeingDetail = array();
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            $Process = isset($postData['process']) ? $postData['process'] : 0;
            $supplierId = (int) $postData['supplierId'];
            $sightseeingId = trim($postData['sightseeingId']);
            $baseCurrencyID = isset($postData['baseCurrency']) ? (int) $postData['baseCurrency'] : 0;
            //            if ($baseCurrencyID <= 0) {
            //                $baseCurrencyID = 1;
            //            }
            $dightseeingDate = (isset($postData['dightseeingDate']) && !empty($postData['dightseeingDate'])) ? trim($postData['dightseeingDate']) : date('d/m/Y');
            $dightseeingDate = explode('/', $dightseeingDate);
            //            echo "<pre>";print_r($postData);die;
            $fromDate = trim($dightseeingDate[2] . '-' . $dightseeingDate[1] . '-' . $dightseeingDate[0]);
            $marketPlace = isset($postData['MarketPlace']) ? (int) $postData['MarketPlace'] : 1;
            $OptionalSightseeingType = isset($postData['OptionalSightseeingType']) ? (int) $postData['OptionalSightseeingType'] : 1;
            $adult = isset($postData['adult']) ? (int) $postData['adult'] : 0;
            $child = isset($postData['child']) ? (int) $postData['child'] : 0;
            if ($marketPlace > 0) {
                $marketPlace = $marketPlace;
            } else {
                $marketPlace = 1;
            }
            if ($OptionalSightseeingType == 0) {
                $checkSightseeingPriceType = $objSightseeing->checkSightseeingPriceType($sightseeingId, $intLoggedinUserAgencySysId);
                //echo "<pre>";print_r($checkSightseeingPriceType);die; 
                $PriceType = array();
                if (isset($checkSightseeingPriceType['AdultEntryFee']) && (int) $checkSightseeingPriceType['AdultEntryFee'] > 0) {
                    $PriceType[] = array('key' => 3, 'value' => 'Entry Only');
                }
                if (isset($checkSightseeingPriceType['NetPriceNativeAdult']) && (int) $checkSightseeingPriceType['NetPriceNativeAdult'] > 0) {
                    $PriceType[] = array('key' => 1, 'value' => 'SIC');
                }
                if ((isset($checkSightseeingPriceType['TotalCostNativeAdult']) && (int) $checkSightseeingPriceType['TotalCostNativeAdult'] > 0) || (isset($checkSightseeingPriceType['RouteVechSysId']) && (int) $checkSightseeingPriceType['RouteVechSysId'] > 0)) {
                    $PriceType[] = array('key' => 2, 'value' => 'PVT');
                }

                $result = array('status' => true, 'priceType' => $PriceType);
                echo json_encode($result);
                exit;
            } else {
                $sightSeeingDetail = $objPackage->getSightseenDetailsWithPricing($sightseeingId, $intLoggedinUserAgencySysId, $fromDate, $marketPlace, $baseCurrencyID, $OptionalSightseeingType, $adult, $child, '', $supplierId);
            }

            //            echo "<pre>";print_r($sightSeeingDetail);exit('here');

            if (!empty($sightSeeingDetail)) {
                $Vehicles = isset($sightSeeingDetail['Vehicles']) ? $sightSeeingDetail['Vehicles'] : array();
                $CostCurrency = (isset($sightSeeingDetail['CostCurrency']) && $sightSeeingDetail['CostCurrency'] > 0) ? $sightSeeingDetail['CostCurrency'] : $this->intLoggedinUserTrxCurrency;
                $CurrencySymbol = (isset($sightSeeingDetail['CurrencySymbol']) && $sightSeeingDetail['CurrencySymbol'] != '') ? $sightSeeingDetail['CurrencySymbol'] : '';
                $result = array('status' => true, 'cityId' => $sightSeeingDetail['CitySysId'], 'cityName' => $sightSeeingDetail['CityName'], 'ContSysId' => $sightSeeingDetail['ContSysId'], 'adultPrice' => $sightSeeingDetail['TotalCostNativeAdult'], 'childPrice' => $sightSeeingDetail['TotalCostNativeChild'], 'AdultCost' => $sightSeeingDetail['AdultCost'], 'ChildCost' => $sightSeeingDetail['ChildCost'], 'AdultMarkup' => $sightSeeingDetail['AdultMarkup'], 'ChildMarkup' => $sightSeeingDetail['ChildMarkup'], 'SupplierSysId' => $sightSeeingDetail['SupplierSysId'], 'SupplierName' => $sightSeeingDetail['SupplierName'], 'CostCurrency' => $CostCurrency, 'CurrencySymbol' => $CurrencySymbol, 'Vehicles' => $Vehicles, 'priceType' => array());
            } else {
                $result = array('status' => false);
            }
            echo json_encode($result);
            exit;
        }
    }

    public function getSightseeingWithPriceAction() {

        $this->_helper->layout->disableLayout();
        $CityIdArr = $this->getRequest()->getParam('CityId');
        $destinationCovered = $this->getRequest()->getParam('destinationcovered');
        $fromDate = $this->getRequest()->getParam('fromDate');
        $fromDate = explode('/', $fromDate);
        $fromDate = trim($fromDate[2] . '-' . $fromDate[1] . '-' . $fromDate[0]);
        $destinationCovered = explode(',', $destinationCovered);
        if (!empty($CityIdArr) && (int) $CityIdArr[0] > 0) {

            $mergeCity = array_unique(array_merge($CityIdArr, $destinationCovered));
        } else {
            $mergeCity = array_unique($destinationCovered);
        }
        $destinationCoveredId = implode(',', $mergeCity);
        $destinationCoveredId = rtrim($destinationCoveredId, ',');
        $CityId = $mergeCity[0];

        //$result = array();
        $htmldata = '';
        if ($CityId >= 1) {
            $obj = new Travel_Model_TblPackage();
            $result = $obj->getCityAllSightseeingHavePricing($CityId, $this->intLoggedinUserAgencySysId, $destinationCoveredId, $fromDate);

            foreach ($result as $resultArr) {
                $title = preg_replace('/\s+/', ' ', $resultArr['Title']);
                $AgencySysId = $this->intLoggedinUserAgencySysId;
                $internalA = ($resultArr['ICSourceSysId'] == $AgencySysId) ? ' (Internal)' : '';
                $CityIdAct = ' (' . trim($resultArr['CityName']) . ', ' . trim($resultArr['Country']) . ') ';
                $htmldata .= '<option value="' . $resultArr['SSSysId'] . '__' . $title . '">' . trim($title) . $CityIdAct . $internalA . '</option>';
            }
        }
        echo $htmldata;
        exit;
        //        echo json_encode($result);exit;
        //}
    }

    public function miscellaneousBookingListAction() {
        $this->_agencyuserroleObj = new Travel_Model_TblAgencyUserRole();
        $getRoleDetail = $this->_agencyuserroleObj->getDataByRole($this->roleID);
        //echo print_r($getRoleDetail);die;
        $objPackageViewList = new Travel_Model_TblAgencyCustomerTrx();
        $objPackageViewList->ReportingToSysId = $this->ReportingToSysId;
        $getData = array();
        if ($this->getRequest()->getPost()) {
            $getData = $this->getRequest()->getPost();
            $getData = $this->_HtmlPurifier->filterArray($getData);
            $this->view->searchData = $getData;
        }

        if ($getRoleDetail['IsAdmin'] == true || $getRoleDetail['IsSuperAdmin'] == true) {
            $getData['UserSysId'] = '0';
            $customerBookingRecord = $objPackageViewList->getMiscellaneousPackageDetail($this->intLoggedinUserAgencySysId, $getData);
        } else {
            $getData['UserSysId'] = $this->intLoggedinUserId;
            $customerBookingRecord = $objPackageViewList->getMiscellaneousPackageDetail($this->intLoggedinUserAgencySysId, $getData);
        }

        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($customerBookingRecord);
        $paginator->setItemCountPerPage(GRID_PER_PAGE_RECORD_COUNT);
        $paginator->setCurrentPageNumber($page);
        //         echo '<pre>';print_r($paginator); die;
        $this->view->paginator = $paginator;
        $TblCurrency = new Travel_Model_TblCurrency();
        $this->view->CurrencySymbol = $CurrencySymbol = $TblCurrency->getCurrencySymbolByIdsList();
    }

    public function getSupplierListDataAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {

            $getData = $this->getRequest()->getParams();

            $PlanType = $getData['PlanType'];
            $Countries = $getData['Countries'];
            $DestinationPlacesSysId = $getData['DestinationPlacesSysId'];
            $IsOnlySightseeingPkg = $getData['IsOnlySightseeingPkg'];
            if ($PlanType == 6) {
                $DestinationPlacesSysId = $Countries;
            }

            $supplierservices = (isset($getData['supplierservices']) && !empty($getData['supplierservices'])) ? $getData['supplierservices'] : array();
            $AgencySysId = $this->intLoggedinUserAgencySysId;
            $objSupplier = new Travel_Model_TblSupplier();
            $SupplierList = $objSupplier->getSuppliersContactListById($DestinationPlacesSysId, $AgencySysId, $supplierservices, $PlanType, $IsOnlySightseeingPkg);
            $this->view->SupplierList = $SupplierList;
            $SupplierServicesArrDB = $objSupplier->getSupplierServices(); //Get Supplier Services
            $this->view->arrSupplierServices = $SupplierServicesArrDB;
        }
    }

    public function dayWiseItineraryAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $getData = $this->getRequest($getData)->getParams();

            $StartDatePaidSight = isset($getData['startDatePaidSight']) ? $getData['startDatePaidSight'] : '';
            $AdultCount = isset($getData['TotalAdult']) ? $getData['TotalAdult'] : 2;
            $ChildCount = isset($getData['TotalChild']) ? $getData['TotalChild'] : 0;
            $Infant = isset($getData['TotalInfant']) ? $getData['TotalInfant'] : 0;
            $noofnight = (isset($getData['noofnight']) && $getData['noofnight'] != '') ? (int) $getData['noofnight'] : '';
            $dayWiseItineraryArr = json_decode($getData['dayWiseItineraryArr']);
            $titledescArrayfinal = json_decode($getData['titledescArrayfinal']);
            $modelBY0 = new BuildYourOwn_Model_Byo();
            $getAllCurrency = $modelBY0->getAllCurrency();
            $obj = new Travel_Model_TblPackage();
            $DestinationCoveredCityIdArr = isset($getData['DestinationCovered']) ? explode(',', $getData['DestinationCovered']) : '';
            $mergeDestinationCoveredCity = array();
            if (!empty($DestinationCoveredCityIdArr) && (int) $DestinationCoveredCityIdArr[0] > 0) {
                $mergeDestinationCoveredCity = array_unique($DestinationCoveredCityIdArr);
            }
            $DestinationCoveredCityId = $mergeDestinationCoveredCity[0];
            $mergeDestinationCoveredCityId = implode(',', $mergeDestinationCoveredCity);
            $mergeDestinationCoveredCityId = rtrim($mergeDestinationCoveredCityId, ',');
            $resultDestinationCoverdCity = array();
            if (!empty($mergeDestinationCoveredCity)) {
                $resultDestinationCoverdCity = $obj->getCityAllSightseeing($DestinationCoveredCityId, $this->intLoggedinUserAgencySysId, $mergeDestinationCoveredCityId);
            }
            //echo "<pre>";print_r($getData);die;  
            $SourcePlaceSysId = isset($getData['SourcePlaceSysId']) ? $getData['SourcePlaceSysId'] : 0;
            $CityIdArr = isset($getData['CityId']) ? $getData['CityId'] : array();
            $mergeCity = array();
            if (!empty($CityIdArr) && (int) $CityIdArr[0] > 0) {
                $mergeCity = array_unique($CityIdArr);
            }


            $CityId = $mergeCity[0];
            $destinationCoveredId = implode(',', $mergeCity);
            $destinationCoveredId = rtrim($destinationCoveredId, ',');
            $objSightseeing = new Travel_Model_TblSightseeing();
            $dayWiseItineraryArrExplode = (isset($dayWiseItineraryArr[0])) ? explode('~~', $dayWiseItineraryArr[0]) : array();
            $dayWiseItineraryDate = (isset($dayWiseItineraryArrExplode[1])) ? $dayWiseItineraryArrExplode[1] : '';
            $StartDate = (!empty($dayWiseItineraryDate)) ? implode('-', array_reverse(explode('/', $dayWiseItineraryDate))) : '';
            if (empty($StartDate)) {
                $StartDate = '';
            }
            $resultPaidSightseeing = $objSightseeing->getSightseeingListWithPrice('', $this->intLoggedinUserAgencySysId, '', $destinationCoveredId, $StartDate, 1);
            $result = $obj->getCityAllSightseeing($CityId, $this->intLoggedinUserAgencySysId, $destinationCoveredId);
            $finalArray = array();
            foreach ($result as $key => $value) {
                $finalArray[$value['CitySysId']][$value['SSSysId']] = $value;
            }

            $this->view->Adult = $AdultCount;
            $this->view->Child = $ChildCount;
            $this->view->getAllCurrency = $getAllCurrency;
            $this->view->finalArray = $finalArray;
            $this->view->dayWiseItineraryArr = $dayWiseItineraryArr;
            $this->view->titledescArrayfinal = $titledescArrayfinal;
            $this->view->destinationCoverdCitySightseeings = $resultDestinationCoverdCity;
            $this->view->SourcePlaceSysId = $SourcePlaceSysId;
            $this->view->resultPaidSightseeing = $resultPaidSightseeing;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        }
    }

    public function updateQuickQueryAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->getPost()) {

            $param = $this->getRequest()->getParams();
            $MasterTPSysId = (isset($param['MasterTPSysId'])) ? (int) $param['MasterTPSysId'] : 0;

            $roomjson = array();
            //ECHO "<pre>";PRINT_R($param);die;
            for ($k = 1; $k <= $param['roomlp']; $k++) {
                $roomjson[$k]['Adult'] = (int) $param['adult_' . $k];
                if (isset($param['adult_type_' . $k]) && !empty($param['adult_type_' . $k])) {
                    $roomjson[$k]['adult_type'] = (isset($param['adult_type_' . $k])) ? trim($param['adult_type_' . $k]) : '';
                }

                if ($roomjson[$k]['Adult'] == 3) {
                    $roomjson[$k]['AdultBedType'] = $param['adultcl_extrabed_' . $k . '_3'];
                }
                $roomjson[$k]['Child'] = (int) $param['child_' . $k];
                $roomjson[$k]['Infant'] = (int) $param['infant_' . $k];
                for ($j = 1; $j <= $roomjson[$k]['Child']; $j++) {
                    $roomjson[$k]['ChildAge_' . $j] = (int) $param['child_age_' . $k . '_' . $j];
                    $roomjson[$k]['ChildBedType_' . $j] = $param['child_extrabed_' . $k . '_' . $j];
                }
                $roomjson[$k]['departuredate'] = $param['search_specific_date'];
                $roomjson[$k]['returndate'] = '';
            }
            $roominfojson = json_encode($roomjson);
            $search_specific_date = (isset($param['search_specific_date']) && !empty($param['search_specific_date'])) ? trim($param['search_specific_date']) : '';
            $plan_start_date = '';
            if (!empty($search_specific_date)) {
                $search_specific_date = explode('/', $search_specific_date);
                $plan_start_date = $search_specific_date[2] . '-' . $search_specific_date[1] . '-' . $search_specific_date[0];
            }
            if (!empty($plan_start_date) && !empty($roomjson) && $MasterTPSysId > 0) {
                $where = "TPSysId = " . $MasterTPSysId;
                $updatetravelplan = array(
                    'StartDate' => $plan_start_date,
                    'RoomInfoJson' => $roominfojson,
                );
                //              echo "<pre>";print_r($updatetravelplan);die;
                $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplan, $where);

                //                $whereProposal = "MasterTPSysId = " . $MasterTPSysId;
                //                $updatetravelplanProposal = array(
                //                    'StatusType' => 15,
                //                );
                //                $this->_crmcusttravelplan->UpdateCustomerTravelPlan($updatetravelplanProposal, $whereProposal);
                $response = array('status' => true, 'message' => 'Query updated successfully.');
            } else {
                $response = array('status' => false, 'message' => 'Unable to update, Please refresh and try again.');
            }
        } else {
            $response = array('status' => false, 'message' => 'Please use post method.');
        }
        echo json_encode($response);
        exit;
    }

    public function getAllToConversionRateAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->getPost()) {
            $TblCurrency = new Travel_Model_TblCurrency();
            $param = $this->getRequest()->getParams();
            $selectedCurrency = ($param['CurrencyId']) ? $param['CurrencyId'] : 0;
            $getToCurrencyConvertionRate = $TblCurrency->getToCurrencyConvertionRate($selectedCurrency);
            $ExchangeRateMaarkup = $this->agencyDetails['ExchangeRateMaarkup'];
            echo json_encode(array('status' => true, 'data' => $getToCurrencyConvertionRate, 'ExchangeRateMaarkup' => $ExchangeRateMaarkup));
            exit;
        }
    }

    public function addMoreSightseeingAction() {
        $this->_helper->layout->disableLayout();
        $modelBY0 = new BuildYourOwn_Model_Byo();
        $getAllCurrency = $modelBY0->getAllCurrency();
        $day = $this->getRequest()->getParam('day');
        $seq = $this->getRequest()->getParam('vseq');
        $adult = $this->getRequest()->getParam('totalAdult');
        $child = $this->getRequest()->getParam('totalchild');
        $pkgType = $this->getRequest()->getParam('pkgType');
        $IsDisplay = 0;
        $obj = new Travel_Model_TblPackage();
        $this->view->getAllCurrency = $getAllCurrency;
        $taxArray = unserialize(GST_TYPE);
        $this->view->taxArray = $taxArray;
        $this->view->day = $day;
        $this->view->sequence = $seq;
        $this->view->adult = $adult;
        $this->view->child = $child;
        $this->view->pkgType = $pkgType;
    }

    public function addMoreMiscItemAction() {
        $this->_helper->layout->disableLayout();
        $modelBY0 = new BuildYourOwn_Model_Byo();
        $getAllCurrency = $modelBY0->getAllCurrency();
        $seq = $this->getRequest()->getParam('vseq');
        $adult = $this->getRequest()->getParam('totalAdult');
        $child = $this->getRequest()->getParam('totalchild');
        $pkgType = $this->getRequest()->getParam('pkgType');
        $IsDisplay = 0;
        $this->markupMdl = new Markup_Model_Markup();
        $resultPaidMicsItem = $this->markupMdl->getDetailsForMisc($this->intLoggedinUserAgencySysId);
        $arrSacCode = $this->markupMdl->getDetailsForSacCode();
        $obj = new Travel_Model_TblPackage();
        $this->view->getAllCurrency = $getAllCurrency;
        $taxArray = unserialize(GST_TYPE);
        $this->view->taxArray = $taxArray;
        $this->view->day = $day;
        $this->view->sequence = $seq;
        $this->view->adult = $adult;
        $this->view->child = $child;
        $this->view->pkgType = $pkgType;
        $this->view->resultPaidMicsItem = $resultPaidMicsItem;
        $this->view->arrSacCode = $arrSacCode;
    }

    public function addMoreTransportAction() {
        //error_reporting(E_ALL);
        $this->_helper->layout->disableLayout();
        $modelBY0 = new BuildYourOwn_Model_Byo();
        $getAllCurrency = $modelBY0->getAllCurrency();
        $day = $this->getRequest()->getParam('day');
        $seq = $this->getRequest()->getParam('vseq');
        $adult = $this->getRequest()->getParam('totalAdult');
        $child = $this->getRequest()->getParam('totalchild');
        $pkgType = $this->getRequest()->getParam('pkgType');
        $IsDisplay = 0;
        $obj = new Travel_Model_TblPackage();
        $this->view->getAllCurrency = $getAllCurrency;
        $taxArray = unserialize(GST_TYPE);
        $this->view->taxArray = $taxArray;
        $this->view->day = $day;
        $this->view->sequence = $seq;
        $this->view->adult = $adult;
        $this->view->child = $child;
        $this->view->pkgType = $pkgType;
    }

    public function getMiscostByMiscIdAction() {
        $this->_helper->layout->disableLayout();
        $intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
        $intLoggedinUserAgentSysId = $this->intLoggedinUserId;
        $objMisc = new Travel_Model_TblMiscellaneous();
        $sightSeeingDetail = array();
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            $Process = isset($postData['process']) ? $postData['process'] : 0;
            $miscId = trim($postData['miscId']);
            $baseCurrencyID = isset($postData['baseCurrency']) ? (int) $postData['baseCurrency'] : 0;
            //            if ($baseCurrencyID <= 0) {
            //                $baseCurrencyID = 1;
            //            }
            $marketPlace = isset($postData['MarketPlace']) ? (int) $postData['MarketPlace'] : 1;
            $adult = isset($postData['adult']) ? (int) $postData['adult'] : 0;
            $child = isset($postData['child']) ? (int) $postData['child'] : 0;
            $totalPax = (int) $adult + $child;
            if ($marketPlace > 0) {
                $marketPlace = $marketPlace;
            } else {
                $marketPlace = 1;
            }

            $miscDetail = $objMisc->getmiscDetailById($miscId, $intLoggedinUserAgentSysId);
            $SacCodeSysId = $miscDetail[0]['SacCodeSysId'];

            $MarkupType = $miscDetail[0]['MarkupType'];
            $perPersonCost = (float) $miscDetail[0]['Cost'];

            $Cost = round((float) $perPersonCost, 2);
            if ($marketPlace == 1) {
                if ($MarkupType == 2) {
                    $Markup = round((float) $Cost * ($miscDetail[0]['B2CMarkup'] / 100), 2);
                } else if ($MarkupType == 1) {
                    $Markup = round((float) $miscDetail[0]['B2CMarkup'], 2);
                }
            } else {
                if ($MarkupType == 2) {
                    $Markup = round((float) $Cost * ($miscDetail[0]['B2BMarkup'] / 100), 2);
                } else if ($MarkupType == 1) {
                    $Markup = round((float) $miscDetail[0]['B2BMarkup'], 2);
                }
            }
            $Totalcost = (float) ($Cost + $Markup);

            if (!empty($miscDetail)) {
                $CostCurrency = (isset($miscDetail[0]['CurrencySysId']) && $miscDetail[0]['CurrencySysId'] > 0) ? $miscDetail[0]['CurrencySysId'] : $this->intLoggedinUserTrxCurrency;
                $CurrencySymbol = (isset($miscDetail[0]['Symbol']) && $miscDetail[0]['Symbol'] != '') ? $miscDetail[0]['Symbol'] : '';
                $result = array('status' => true, 'Cost' => $Totalcost, 'Price' => $Cost, 'MarkupType' => $miscDetail[0]['MarkupType'], 'Markup' => $Markup, 'SupplierSysId' => $miscDetail[0]['SupplierSysId'], 'SupplierName' => $miscDetail[0]['SupplierName'], 'CostCurrency' => $CostCurrency, 'CurrencySymbol' => $CurrencySymbol, 'MarkupType' => $MarkupType, 'priceType' => $miscDetail[0]['PriceType'], 'SacCodeSysId' => $SacCodeSysId, 'Description' => $miscDetail[0]['Description']);
            } else {
                $result = array('status' => false);
            }
            echo json_encode($result);
            exit;
        }
    }

    function getAreaDataAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $this->byo = new BuildYourOwn_Model_Byo();
        $AgencySysId = $this->intLoggedinUserAgencySysId;
        try {
            if ($this->getRequest()->getPost()) {
                $params = $this->getRequest()->getParams();
                $startCityId = $params['startCityId'];
                $endCityId = $params['endCityId'];
                $TPSysId = (int) $params['TPSysId'];
                $transferType = $params['transferType'];
                $categoryTransport = $params['categoryTransport'];
                $subCategoryTransport = $params['subCategoryTransport'];
                $subCategoryTransportTitle = (isset($TRANSPORT_SUB_CATEGORIES[$subCategoryTransport]) && $TRANSPORT_SUB_CATEGORIES[$subCategoryTransport] != '') ? trim($TRANSPORT_SUB_CATEGORIES[$subCategoryTransport]) : '';
                $dropAreaData = $params['dropArea'];
                $dropAreaExplode = explode('__', $dropAreaData);
                $dropArea = $dropAreaExplode[0];
                $pickupAreaData = $params['pickupArea'];
                $pickupAreaExplode = explode('__', $pickupAreaData);
                $pickupArea = $pickupAreaExplode[0];
                $day = (int) $params['day'];
                $dayDate = isset($params['dayDate']) ? $params['dayDate'] : '';
                $MarketPlaceId = isset($params['MarketPlaceId']) ? $params['MarketPlaceId'] : 1;
                $DestinationIdArr = $returnArraym = $params['destinations'];
                if ($categoryTransport == 1) {
                    if ($day == 1) {
                        $StartDestinationId = ($DestinationIdArr[0]) ? $DestinationIdArr[0] : 0;
                        $cityIds = implode(',', $DestinationIdArr);
                        $autosugestTransportData1 = $this->byo->getAllItinerayTransportRouteTransportSubType($AgencySysId, $startCityId, $cityIds . ',' . $startCityId, $MarketPlaceId, $dayDate);
                        $autosugestTransportData2 = array();
                        if ($startCityId != $StartDestinationId) {
                            $autosugestTransportData2 = $this->byo->getAllItinerayTransportRouteTransportSubType($AgencySysId, $StartDestinationId, $cityIds, $MarketPlaceId, $dayDate);
                        }
                        $autosugestTransportData = array_merge($autosugestTransportData1, $autosugestTransportData2);
                    }
                } else {
                    $autosugestTransportData = $this->byo->getAutosuggestTransportRouteDataPreToNext($AgencySysId, $startCityId, $endCityId, 0, '', $transferType, $categoryTransport, $subCategoryTransport, $dayDate, $dayDate, $MarketPlaceId);
                    //$autosugestTransportData2 = $this->byo->getAutosuggestTransportRouteData($AgencySysId, $endCityId, $endCityId, '', $transferType, $categoryTransport, $subCategoryTransport);
                    //$autosugestTransportData = array_merge($autosugestTransportData1);
                }

                $finalHtml = '<option value="">Select</option>';
                $checkRouteSysIdArr = $checkRouteVehSysIdArr = array();
                $checkDuplicateRoute = $cityIncludes = array();
                $autosugestTransportDataNew = $autosugestTransportDataArea = $autosugestTransportDataPickupArea = array();
                foreach ($autosugestTransportData as $tKey => $tVal) {
                    if (!isset($checkRouteVehSysIdArr[$tVal['RouteSysId']]) || in_array($tVal['RouteVechSysId'], $checkRouteVehSysIdArr[$tVal['RouteSysId']])) {
                        $autosugestTransportDataNew[$tVal['RouteSysId']] = $tVal;
                        $autosugestTransportDataArea[$tVal['RouteSysId']][$tVal['dropAreaId']] = $tVal['DropLocation'];
                        $autosugestTransportDataPickupArea[$tVal['RouteSysId']][$tVal['pickupAreaId']] = $tVal['PickupLocation'];
                        $nights = ($tVal['destSequence'] == 1 && $tVal['nights'] < $tVal['Noofnights'] && $tVal['StartCitySysId'] != $tVal['DestSysId']) ? $tVal['nights'] - 1 : $tVal['nights'];
                        for ($im1 = 0; $im1 < $nights; $im1++) {
                            $cityIncludes[$tVal['RouteSysId']][] = $tVal['DestSysId'];
                        }
                        $checkRouteVehSysIdArr[$tVal['RouteSysId']][] = $tVal['RouteVechSysId'];
                    }
                }
                //echo "<pre>";print_r($autosugestTransportDataNew);die;
                $duplicateArea = array();
                foreach ($autosugestTransportDataNew as $tKey => $tVal) {
                    if (!in_array($tVal['RouteSysId'], $checkDuplicateRoute)) {
                        $checkDuplicateRoute[] = $tVal['RouteSysId'];
                        if (isset($categoryTransport) && $categoryTransport == 1) {
                            $CheckItinerayRouteSysId = 0;
                            $cityIncludesm = $cityIncludes[$tKey];
                            //$cityIncludesm[] = $tVal['DestinationCitySysId'];
                            $returnArraymN = $returnArraym;
                            if ($tVal['TransportType'] == 2) {
                                $checkDiff = ($cityIncludesm == $returnArraymN);
                                if ($checkDiff == true) {
                                    $CheckItinerayRouteSysId++;
                                }
                            } else {
                                for ($im = count($returnArraymN) - 1; $im >= 0; $im--) {
                                    $checkDiff = ($cityIncludesm == $returnArraymN);
                                    if ($checkDiff == true) {
                                        $CheckItinerayRouteSysId++;
                                    }
                                    unset($returnArraymN[$im]);
                                }
                            }

                            if ($CheckItinerayRouteSysId > 0) {
                                $finalHtml .= '<option value="' . $tVal['RouteSysId'] . '">' . ($tVal['Noofnights']) . ' day(s) / ' . $tVal['RouteName'] . '</option>';
                            }
                        } else if ($categoryTransport == 2) {

                            if (trim($pickupArea) != '') {
                                $Area = isset($autosugestTransportDataArea[$tVal['RouteSysId']]) ? $autosugestTransportDataArea[$tVal['RouteSysId']] : array();
                            } else {
                                $Area = isset($autosugestTransportDataPickupArea[$tVal['RouteSysId']]) ? $autosugestTransportDataPickupArea[$tVal['RouteSysId']] : array();
                            }
                            //echo $dropArea."<pre>";print_r($Area); 
                            foreach ($Area as $arKey => $arval) {
                                if (isset($dropArea) && isset($pickupArea)) {
                                    if (trim($dropArea) == '0' && trim($pickupArea) == '') {
                                        $pickupArea = '0';
                                    }
                                }
                                if (isset($dropArea) && trim($dropArea) != '') {
                                    if ($arKey == $dropArea && !in_array($tVal['RouteSysId'], $checkRouteSysIdArr)) {
                                        $finalHtml .= '<option value="' . $tVal['RouteSysId'] . '">' . $tVal['Noofnights'] . ' day(s) / ' . $tVal['RouteName'] . '</option>';
                                        $checkRouteSysIdArr[] = $tVal['RouteSysId'];
                                    }
                                } else {
                                    if (($dropArea == '0' && $pickupArea == '0')) {
                                        
                                    } else {
                                        if (!in_array($arKey, $duplicateArea) && $arKey > 0) {
                                            $finalHtml .= '<option value="' . $arKey . '__' . trim($arval) . '">' . (($arval != '') ? $arval : 'NA') . '</option>';
                                            $duplicateArea[] = $arKey;
                                        }
                                    }
                                }
                            }
                        } else {

                            if (trim($pickupArea) != '') {
                                $Area = isset($autosugestTransportDataArea[$tVal['RouteSysId']]) ? $autosugestTransportDataArea[$tVal['RouteSysId']] : array();
                            } else {
                                $Area = isset($autosugestTransportDataPickupArea[$tVal['RouteSysId']]) ? $autosugestTransportDataPickupArea[$tVal['RouteSysId']] : array();
                            }
                            foreach ($Area as $arKey => $arval) {
                                if (isset($dropArea) && isset($pickupArea)) {
                                    if (trim($dropArea) == '0' && trim($pickupArea) == '') {
                                        $pickupArea = '0';
                                    }
                                }
                                if (isset($dropArea) && trim($dropArea) != '') {
                                    if ($arKey == $dropArea && !in_array($tVal['RouteSysId'], $checkRouteSysIdArr)) {
                                        $finalHtml .= '<option value="' . $tVal['RouteSysId'] . '">' . $tVal['Noofnights'] . ' day(s) / ' . $tVal['RouteName'] . '</option>';
                                        $checkRouteSysIdArr[] = $tVal['RouteSysId'];
                                    }
                                } else {
                                    if (($dropArea == '0' && $pickupArea == '0')) {
                                        
                                    } else {
                                        if (!in_array($arKey, $duplicateArea) && $arKey > 0) {
                                            $finalHtml .= '<option value="' . $arKey . '__' . trim($arval) . '">' . (($arval != '') ? $arval : 'NA') . '</option>';
                                            $duplicateArea[] = $arKey;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if ($finalHtml != '<option value="">Select</option>') {
                    $finalHtml .= '<option value="0__">Other</option>';
                }
                //                die; 

                echo $finalHtml;
                die;
            }
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }

    function getPriceWithGST($price, $markup, $TaxType, $TaxRate) {

        if ($TaxType == 1) {
            $gstAmount = ((float) $price * $TaxRate) / 100;
        } elseif ($TaxType == 2) {
            $gstAmount = ((float) $markup * $TaxRate) / 100;
        } else {
            $gstAmount = 0;
        }
        return (int) ($price + $gstAmount);
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit