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

/**
 * Class Hotel
 *
 * @name		Buy Hotel
 * @author		Harpreet
 * @version 	1.0
 * @copyright 	Catabatic India Pvt Ltd
 * Handle Hotel Related function
 *
 */
class BuyhotelController extends Catabatic_ValidateGtx
{
    //class BuyhotelController extends Zend_Controller_Action {
    private $SMSURL;
    private $SMSMETHOD;
    private $SMSAPIKEY;
    private $SMSSENDER;
    private $SMSFORMAT;
    private $IsSMSApi;
    private $intLoggedinUserId = '';
    private $intLoggedinAgencyId = '';
    private $intLoggedinUserGroupSysId = '';
    private $intLoggedinUserAgencySysId = '';
    private $intLoggedinUserTrxCurrency = '';
    private $InfoSourceSysId = '';
    public $baseUrl = '';
    public $url = 'http://api.tektravels.com/SharedServices/SharedData.svc/rest/Authenticate';
    public $urlHotel = 'http://api.tektravels.com/BookingEngineService_Hotel/hotelservice.svc/rest/GetHotelResult/';
    public $userIp = '180.151.8.18';
    public $user = "tripshows";
    public $pass = "tripshows@123";
    public $clientID = 'apiintegration';
    public $agencymarkup = '';
    public $agencyDetails = [];
    public $intLoggedinUserContactNo = '';
    public $intLoggedinUserEmailId = '';
    public $CurrencyTitle = '';
    public $CurrencyId = 0;
    public $CurrencyRate = 1;

    public function init()
    {
        //        phpinfo();
        //        exit;
        parent::init();

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

        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');

        ############## For HTML Purifer ####################
        $this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();

        $this->intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $this->intLoggedinUserGroupSysId = $sessionLogin_user->intLoggedinUserGroupSysId;
        $this->intLoggedinUserAgencySysId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->intLoggedinAgencyId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->intLoggedinUserTrxCurrency = $sessionLogin_user->intLoggedinUserTrxCurrency;
        $this->intLoggedinUserContactNo = $sessionLogin_user->ContactNo1;
        $this->intLoggedinUserEmailId = $sessionLogin_user->EmailId;
        $this->agencyDetails = $sessionLogin_user->agencyDetails;
        $objHotel = new Travel_Model_TblBuyHotel();
        $this->agencymarkup = $objHotel->getAgencyMarkup();
        if (!empty($this->intLoggedinUserAgencySysId)) {
            $this->InfoSourceSysId = '2'; /* Information Source is Agent */
        }

        $this->SMSURL = Catabatic_Helper::getSMSURL();
        $this->SMSMETHOD = Catabatic_Helper::getSMSMETHOD();
        $this->SMSAPIKEY = Catabatic_Helper::getSMSAPIKEY();
        $this->SMSSENDER = Catabatic_Helper::getSMSSENDER();
        $this->SMSFORMAT = Catabatic_Helper::getSMSFORMAT();

        $this->CurrencyRate = 1;
        $this->CurrencyTitle = ($this->agencyDetails['Symbol']) ? $this->agencyDetails['Symbol'] : 'INR';
        $this->CurrencyId = ($this->agencyDetails['TrxCurrency']) ? $this->agencyDetails['TrxCurrency'] : 1;
    }

    public function indexAction()
    {
        //ini_set("display_errors", 1);
        $sessionHotelSearchParams = new Zend_Session_Namespace('sessionHotelDirectSearchData');
        $sessionHotelSearchParams->params['searchType'] = 'DIRECTHOTELSEARCH';
        $this->view->searchParams = $sessionHotelSearchParams->params;

        $this->view->country = $this->getCountry();

        $objHotel = new Travel_Model_TblBuyHotel();
        $arrResponse = $objHotel->getHotelAminityAutoSuggest();
        //        print_r($arrResponse);
        //        echo "HI"; exit;
        $this->view->AminityArr = $arrResponse;
    }

    public function hotelReviewBookingAction()
    {

        $this->view->intCustomerSysId = $intCustomerSysId = base64_decode(trim($this->getRequest()->getParam('cid')));
        $this->view->intTpSysId = $intTpSysId = base64_decode(trim($this->getRequest()->getParam('tid')));
        $travelplanObj = new Travel_Model_CRM_CustomerTravelPlan();
        $travelPlanDetail = $travelplanObj->GetPublicPageLeadList($intCustomerSysId, $this->intLoggedinUserAgencySysId, $intTpSysId);
        $this->view->intTpIntSysId = $intTpIntSysId = base64_decode(trim($this->getRequest()->getParam('it_id')));

        $this->view->Error = $strError = trim($this->getRequest()->getParam('error_Message'));

        $fullBaseUrl = $this->view->baseUrl();
        $this->view->strPayWithWalletUrl = $fullBaseUrl . "/payment/wallet-pay";
        $this->view->strRechargeNowUrl = $fullBaseUrl . "/payment/payment-options";
        $this->view->strSearchPageUrl = $fullBaseUrl . "/buyhotel/search-results";
        $this->view->strReturnURL = $fullBaseUrl . "/buyhotel/make-payment/cid/" . base64_encode($intCustomerSysId) . "/tid/" . base64_encode($intTpSysId) . "/it_id/" . base64_encode($intTpIntSysId);
        $this->view->strErrorURL = $fullBaseUrl . "/buyhotel/hotel-review-booking/cid/" . base64_encode($intCustomerSysId) . "/tid/" . base64_encode($intTpSysId) . "/it_id/" . base64_encode($intTpIntSysId);
        $this->view->intPlanType = "2";
        $this->view->strTrxType = "H";


        $wallet = Zend_Controller_Action_HelperBroker::getStaticHelper('Dashboard')->getWalletPrice($this->intLoggedinUserAgencySysId);
        $this->view->walletBalanceAmount = $wallet[0]['BalanceAmount'];


        if (!empty($intCustomerSysId)) {
            // for CRM Member Details
            $objBuyHotel = new Travel_Model_TblBuyHotel();
            $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
            //print_r($getCustomerDetail);
            $intMemberSysId = isset($getCustomerDetail['MemberSysId']) ? $getCustomerDetail['MemberSysId'] : 0;
            if (!empty($intMemberSysId)) {
                $this->view->intMemberSysId = $intMemberSysId;
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            } else {
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            }
        }



        //            $curencyTy = new Zend_Session_Namespace('curency');
        //            $curencyTy->curency;
        //            $markuptype = new Zend_Session_Namespace('markupty');
        //            $markuptype->markupty;
        //            $markupAgency = new Zend_Session_Namespace('markupAg');
        //            $markupAgency->markupAg;



        $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
        $API_SOURCE_ID = $sessionPreBookingHotelDetails->params['HOTELINFO']['API_SOURCE_ID'];

        if ($API_SOURCE_ID == "3") {
            $arrHotelRoomsDetails = $_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'];
            if (!empty($arrHotelRoomsDetails)) {
                $intRoomPrice = 0;
                $intTax = 0;
                foreach ($arrHotelRoomsDetails as $roomsDetailsVal) {
                    $strCurrencyCode = $roomsDetailsVal['Price']['CurrencyCode'];
                    $intRoomPrice = $roomsDetailsVal['Price']['RoomPrice'];
                    $intTax += $roomsDetailsVal['Price']['Tax'];
                }
            }

            $intRoomPrice = round($intRoomPrice);
            //echo $intRoomPrice;

            /* Search Session Variables */
            $this->view->intRoomCount =  $intRoomCount = $_SESSION['noOfRooms'];
            $this->view->intNigthsCount =  $intNigthsCount = $_SESSION['nights'];
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $intNoOfAdults = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
            $intNoOfChild = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
            $intTotalPaxCount = $intNoOfAdults + $intNoOfChild;
            $strCountryCode = $sessionhotelDirectSearchData->params['countryCode'];
            /* Search Session Variables */

            $arrHotelPriceAndMarkupsDetails = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($intRoomPrice, "0", $intNigthsCount, $intRoomCount, $strCountryCode);

            if (!empty($arrHotelPriceAndMarkupsDetails)) {
                $intBasePrice = $arrHotelPriceAndMarkupsDetails['intBasePrice'];
                $intSTaxOnBasePrice = $arrHotelPriceAndMarkupsDetails['intSTaxOnBasePrice'];
                $intPriceWithMarkUpsAndSTax = $arrHotelPriceAndMarkupsDetails['intPriceWithMarkUpsAndSTax'];
                $intGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intGTXMarkUp'];
                $intSTaxOnGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnGTXMarkUp'];
                $intGTXMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intGTXMarkUpWithSTax'];
                $intAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUp'];
                $intSTaxOnAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnAgencyMarkUp'];
                $intAgencyMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUpWithSTax'];
                $intNetSTax = $arrHotelPriceAndMarkupsDetails['intNetSTax'];
                $intGTXMarkUpType = $arrHotelPriceAndMarkupsDetails['GTXMarkUpType'];
                $intAgencyMarkUpType = $arrHotelPriceAndMarkupsDetails['AgencyMarkUpType'];
                $intAgencyMarkUpDB = $arrHotelPriceAndMarkupsDetails['AgencyMarkUpDB'];
            } else {
                $intBasePrice = 0;
                $intSTaxOnBasePrice = 0;
                $intPriceWithMarkUpsAndSTax = 0;
                $intGTXMarkUp = 0;
                $intSTaxOnGTXMarkUp = 0;
                $intGTXMarkUpWithSTax = 0;
                $intAgencyMarkUp = 0;
                $intSTaxOnAgencyMarkUp = 0;
                $intAgencyMarkUpWithSTax = 0;
                $intNetSTax = 0;
                $intGTXMarkUpType = 0;
                $intAgencyMarkUpType = 0;
            }

            if ($intAgencyMarkUpType == 2) {
                $intAgencyMarkUp = $intAgencyMarkUp * $intRoomCount;
                $intAgencyMarkUp = $intAgencyMarkUp - ($intGTXMarkUp * $intAgencyMarkUpDB) / 100;
            }
            //echo $intAgencyMarkUp;
            //$intAgencyMarkUpWithSTax = $intAgencyMarkUpWithSTax*$intRoomCount;
            $intTotalRoomPrice = ($intBasePrice * $intRoomCount) + $intGTXMarkUpWithSTax;
            $intRoomFarePerNightPerRoom = ($intTotalRoomPrice / $intNigthsCount) / $intRoomCount;
            $intAllApplicableSTax = $intSTaxOnBasePrice + $intSTaxOnGTXMarkUp + $intSTaxOnAgencyMarkUp;
            $intTotalNetPayable = $intTotalRoomPrice + $intAgencyMarkUp; //$intAgencyMarkUpWithSTax;

            $arrServiceTaxOnNetPayable = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intTotalNetPayable, "H", 8);
            $intServiceTaxOnNetPayable = !empty($arrServiceTaxOnNetPayable['serviceTaxAmount']) ? $arrServiceTaxOnNetPayable['serviceTaxAmount'] : 0;

            $intTotalNetPayable = ($intTotalNetPayable + $intServiceTaxOnNetPayable);

            $intTotalAmount = $intBasePrice * $intRoomCount;
            $arrServiceTaxOnBaseAmount = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intTotalAmount, "H", 8);
            $intServiceTaxOnBaseAmount = !empty($arrServiceTaxOnBaseAmount['serviceTaxAmount']) ? $arrServiceTaxOnBaseAmount['serviceTaxAmount'] : 0;

            $arrSTaxOnGTXMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intGTXMarkUp, "H", 8);
            $intSTaxOnGTXMarkUp = !empty($arrSTaxOnGTXMarkUp['serviceTaxAmount']) ? $arrSTaxOnGTXMarkUp['serviceTaxAmount'] : 0;

            $arrSTaxOnAgencyMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intAgencyMarkUp, "H", 8);
            $intSTaxOnAgencyMarkUp = !empty($arrSTaxOnAgencyMarkUp['serviceTaxAmount']) ? $arrSTaxOnAgencyMarkUp['serviceTaxAmount'] : 0;


            $arrPriceAndMarkups = array(
                "intAgentMarkUpAmount" => 0,
                "intAgencyMarkUpAmount" => $intAgencyMarkUp,
                "intGTXMarkUpAmount" => $intGTXMarkUp,
                "intTotalAmount" => ($intBasePrice * $intRoomCount),
                "intTax" => $intServiceTaxOnBaseAmount,
                "GTXServiceTaxAmount" => $intSTaxOnGTXMarkUp,
                "AgentServiceTaxAmount" => $intSTaxOnAgencyMarkUp,
                "AgentsCustomServiceTaxAmount" => "0",
                "Pax" => $intTotalPaxCount,
                "SupplierSourceStr" => "API",
                "MarketPlaceId" => "1",
                "TotalDiscount" => "0",
                "CurrencyType" => "1"
            );
            //echo "<pre>";print_r($arrPriceAndMarkups);echo "</pre>";//exit;
            $strPriceAndMarkups = json_encode($arrPriceAndMarkups);
            $this->view->stringData = $strStringData = $this->getEnc($strPriceAndMarkups);
            if (!empty($intPriceWithMarkUpsAndSTax)) {
                $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intTotalNetPayable;
            } else {
                $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intBasePrice;
            }
        } else if ($API_SOURCE_ID == "4") {
            $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
            $NO_OF_ROOMS = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_ROOMS'];
            $ARR_ROOMPRICE = $sessionPreBookingHotelDetails->params['ROOMPRICE'];
            //echo "<pre>";print_r($ARR_ROOMPRICE);exit;
            $NO_OF_CHILD = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_CHILD'];
            $NO_OF_ADULTS = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_ADULTS'];

            //echo ""; print_r($sessionPreBookingHotelDetails->params);

            if (!empty($ARR_ROOMPRICE)) {
                $intRoomPrice = 0;
                $intTax = 0;
                $intServiceFee = 0;
                //for ($i = 1; $i<=$NO_OF_ROOMS; $i++){


                $strCurrencyCode = $ARR_ROOMPRICE['CURRENCY'];
                $intRoomPrice += $ARR_ROOMPRICE['PRICE'];
                $intTax += $ARR_ROOMPRICE['SURCHARGE_TAX'];
                $intServiceFee += $ARR_ROOMPRICE['SERVICE_FEE'];

                //}



            }



            $intRoomPrice = round($intRoomPrice);
            $this->view->intRoomCount =  $intRoomCount = $_SESSION['noOfRooms'];
            $this->view->intNigthsCount =  $intNigthsCount = $_SESSION['nights'];
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $intNoOfAdults = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
            $intNoOfChild = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
            $intTotalPaxCount = $intNoOfAdults + $intNoOfChild;
            $strCountryCode = $sessionhotelDirectSearchData->params['countryCode'];

            $arrHotelPriceAndMarkupsDetails = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($intRoomPrice, "0", $intNigthsCount, $intRoomCount, $strCountryCode);
            if (!empty($arrHotelPriceAndMarkupsDetails)) {
                $intBasePrice = $arrHotelPriceAndMarkupsDetails['intBasePrice'];
                $intSTaxOnBasePrice = $arrHotelPriceAndMarkupsDetails['intSTaxOnBasePrice'];
                $intPriceWithMarkUpsAndSTax = $arrHotelPriceAndMarkupsDetails['intPriceWithMarkUpsAndSTax'];
                $intGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intGTXMarkUp'];
                $intSTaxOnGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnGTXMarkUp'];
                $intGTXMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intGTXMarkUpWithSTax'];
                $intAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUp'];
                $intSTaxOnAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnAgencyMarkUp'];
                $intAgencyMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUpWithSTax'];
                $intNetSTax = $arrHotelPriceAndMarkupsDetails['intNetSTax'];
            } else {
                $intBasePrice = 0;
                $intSTaxOnBasePrice = 0;
                $intPriceWithMarkUpsAndSTax = 0;
                $intGTXMarkUp = 0;
                $intSTaxOnGTXMarkUp = 0;
                $intGTXMarkUpWithSTax = 0;
                $intAgencyMarkUp = 0;
                $intSTaxOnAgencyMarkUp = 0;
                $intAgencyMarkUpWithSTax = 0;
                $intNetSTax = 0;
            }

            $intTotalRoomPrice = ($intBasePrice) + $intGTXMarkUpWithSTax;
            $intRoomFarePerNightPerRoom = ($intTotalRoomPrice / $intNigthsCount) / $intRoomCount;
            $intAllApplicableSTax = $intSTaxOnBasePrice + $intSTaxOnGTXMarkUp + $intSTaxOnAgencyMarkUp;
            $intTotalNetPayable = $intTotalRoomPrice + $intAgencyMarkUpWithSTax;

            $arrServiceTaxOnNetPayable = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intTotalNetPayable, "H", 9);
            $intServiceTaxOnNetPayable = !empty($arrServiceTaxOnNetPayable['serviceTaxAmount']) ? $arrServiceTaxOnNetPayable['serviceTaxAmount'] : 0;

            $intTotalNetPayable = ($intTotalNetPayable + $intServiceTaxOnNetPayable);


            $arrServiceTaxOnBaseAmount = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intBasePrice, "H", 9);
            $intServiceTaxOnBaseAmount = !empty($arrServiceTaxOnBaseAmount['serviceTaxAmount']) ? $arrServiceTaxOnBaseAmount['serviceTaxAmount'] : 0;

            $arrSTaxOnGTXMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intGTXMarkUp, "H", 9);
            $intSTaxOnGTXMarkUp = !empty($arrSTaxOnGTXMarkUp['serviceTaxAmount']) ? $arrSTaxOnGTXMarkUp['serviceTaxAmount'] : 0;

            $arrSTaxOnAgencyMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intAgencyMarkUp, "H", 9);
            $intSTaxOnAgencyMarkUp = !empty($arrSTaxOnAgencyMarkUp['serviceTaxAmount']) ? $arrSTaxOnAgencyMarkUp['serviceTaxAmount'] : 0;




            $arrPriceAndMarkups = array(
                "intAgentMarkUpAmount" => 0,
                "intAgencyMarkUpAmount" => $intAgencyMarkUp,
                "intGTXMarkUpAmount" => $intGTXMarkUp,
                "intTotalAmount" => ($intBasePrice),
                "intTax" => $intServiceTaxOnBaseAmount,
                "GTXServiceTaxAmount" => $intSTaxOnGTXMarkUp,
                "AgentServiceTaxAmount" => $intSTaxOnAgencyMarkUp,
                "AgentsCustomServiceTaxAmount" => "0",
                "Pax" => $intTotalPaxCount,
                "SupplierSourceStr" => "API",
                "MarketPlaceId" => "1",
                "TotalDiscount" => "0",
                "CurrencyType" => "1"
            );
            //echo "<pre>";print_r($arrPriceAndMarkups);echo "</pre>";//exit;
            $strPriceAndMarkups = json_encode($arrPriceAndMarkups);
            $this->view->stringData = $strStringData = $this->getEnc($strPriceAndMarkups);

            if (!empty($intPriceWithMarkUpsAndSTax)) {
                $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intTotalNetPayable;
            } else {
                $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intBasePrice;
            }
        }


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

        $this->view->guid = $this->GUID();
        $this->view->walletCode = $this->walletCode($this->intLoggedinUserAgencySysId, $this->view->guid, $intGrandPayableAmount, $this->intLoggedinUserId, $intTpSysId, $intCustomerSysId, $strStringData);
        $this->view->securecode = $this->secureCode($this->intLoggedinUserAgencySysId, $this->view->guid);
        $this->view->sessionhotelDirectSearchData = $sessionhotelDirectSearchData->params;
        $this->view->travelPlanDetail = $travelPlanDetail;
    }

    public function getCountry()
    {
        $objCountry = new Travel_Model_TblCountry();
        return $country = $objCountry->getCountryList();
    }

    public function autosuggestAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        //       print_r($this->getRequest()->getParam("term"));
        //       exit;
        try {
            $arrResponse = array();
            if ($this->getRequest()->getParam("term") or $this->getRequest()->getParam("query")) {
                $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
                $countryId = $this->getRequest()->getParam("countryId") ? $this->getRequest()->getParam("countryId") : '';

                $objHotel = new Travel_Model_TblBuyHotel();
                $condCity = "tbl.Title like '" . $term . "%'";
                if (isset($countryId) && !empty($countryId)) {
                    $condCity .= " AND tbl.ContSysId = " . $countryId . "";
                }
                //echo $condCity;
                $arrResponse = $objHotel->getBuyHotelCityAutoSuggest($condCity);
                //print_r($arrResponse);die;
            }
            echo json_encode($arrResponse);
            exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }
    public function autosuggestcityAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        //       print_r($this->getRequest()->getParam("term"));
        //       exit;
        try {
            $arrResponse = array();
            if ($this->getRequest()->getParam("term") or $this->getRequest()->getParam("query")) {
                $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
                $countryId = $this->getRequest()->getParam("countryId") ? $this->getRequest()->getParam("countryId") : '';
                if ($this->intLoggedinUserAgencySysId == 139360 && empty($countryId)) {
                    $countryId = 215;
                }
                $objHotel = new Travel_Model_TblBuyHotel();
                $condCity = "tbl.Title like '" . $term . "%'";
                if (isset($countryId) && !empty($countryId)) {
                    $condCity .= " AND tbl.ContSysId = " . $countryId . "";
                }
                //echo $condCity;
                $arrResponse = $objHotel->getBuyHotelCityAutoSuggest($condCity);
                //print_r($arrResponse);die;
            }
            echo json_encode($arrResponse);
            exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }
    public function autosuggestnewAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        try {
            $arrResponse = array();
            if ($this->getRequest()->getParam("term") or $this->getRequest()->getParam("query")) {
                $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
                $query = urlencode(strtoupper($term));
                $countryId = $this->getRequest()->getParam("countryId") ? $this->getRequest()->getParam("countryId") : '';
                if (!empty(trim($query))) {
                    $url          = 'https://hotels.globaltravelexchange.com/api/v1/trip-jack-hotel-cities/?keywords=' . $query;
                    $data = array(
                        'keywords' => $query
                    );
                    $data_stringh = json_encode($data);
                    $ch           = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Accept: application/json',
                        'Content-Type: application/json',
                        'Accept-Encoding: gzip',
                        'Content-Length: ' . strlen($data_stringh)
                    ));

                    $outputH      = curl_exec($ch);
                    if (curl_errno($ch)) {
                        print(curl_error($ch));
                        exit;
                    }
                    curl_close($ch);
                    echo $outputH;
                    exit;
                }
            }
            // echo json_encode($arrResponse);
            // exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }


    public function autosuggestForPackageAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        //       print_r($this->getRequest()->getParam("term"));
        //       exit;
        try {
            $arrResponse = array();
            if ($this->getRequest()->getParam("term") or $this->getRequest()->getParam("query")) {
                $term = $this->getRequest()->getParam("term") ? $this->getRequest()->getParam("term") : $this->getRequest()->getParam("query");
                $countryId = $this->getRequest()->getParam("countryId") ? $this->getRequest()->getParam("countryId") : '';

                $objHotel = new Travel_Model_TblBuyHotel();
                //                $condCity = "tbl.Title like '" . $term . "%'";
                //				if(isset($countryId) && !empty($countryId)){
                //					$condCity .= " AND tbl.ContSysId = " . $countryId . "";
                //				}
                //echo $condCity;
                $arrResponse = $objHotel->getAutosuggestForPackage($term);
                //print_r($arrResponse);die;
            }
            echo json_encode($arrResponse);
            exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }




    public function autosuggestAminityAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            $arrResponse = array();
            if ($this->getRequest()->getParam("term")) {
                $term = $this->getRequest()->getParam("term");
                $objHotel = new Travel_Model_TblBuyHotel();
                $arrResponse = $objHotel->getHotelAminityAutoSuggest($term);
            }
            echo json_encode($arrResponse);
            exit;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }

    public function getRoomAminitesMaskAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            $aminity = $this->getRequest()->getParam('amenity');
            if ($this->getRequest()->isXmlHttpRequest()) {
                $objRoomAminities = new Travel_Model_TblAmenities();
                $roomAminity = $objRoomAminities->getRoomInventoryAmenitiesDB($aminity);
                $aminiti = str_split($aminity);


                $res = array('rAmit' => $roomAminity);

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

    public function getAminitiesMask($aminiteStr)
    { /*     * ***Aminities with masterAminities**** */
        try {
            $objHotelAminities = new Travel_Model_TblAmenities();
            $aminityTble = $objHotelAminities->getHotlAmenitiesDB();
            $aminitiesArra = str_split($aminiteStr);
            unset($aminitiesArra[0]);
            $aminitiesArray = array_values($aminitiesArra);
            foreach ($aminityTble as $val) {
                $title[] = trim($val['Title']);
            }
            $count = min(count($title), count($aminitiesArray));
            $aminitiesArray1 = array_combine(array_slice($title, 0, $count), array_slice($aminitiesArray, 0, $count));
            $imgArr = array();
            return $imgArr;
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }

    public function getHotlAmitCateAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            if ($this->_request->isXmlHttpRequest()) {
                $amenityId = $this->getRequest()->getParam('amenity');

                $objAminity = new Travel_Model_TblAmenities();
                $hotelAminity = $objAminity->getHotlAmenitiesforPopup($amenityId);

                $aminitHtml = "<ul class='roomactivities'>";
                for ($i = 0; $i < count($hotelAminity); $i++) {
                    $aminitHtml .= '<li><span>' . $hotelAminity[$i] . '</li>';
                }
                $aminitHtml .= '</ul>';


                echo $aminitHtml;
            }
        } catch (Exception $e) {
            $response = array('success' => false, 'msg' => $e->getMessage());
            echo json_encode($response);
            exit;
        }
    }
    public function getHotlAmitCateApiAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            if ($this->_request->isXmlHttpRequest()) {
                $hotlcode = $this->getRequest()->getParam('hotlcode');

                $objAminity = new Travel_Model_TblAmenities();
                $hotelAminity = $objAminity->getHotlAmenitiesforPopupApi($hotlcode);
                //echo "<pre>";print_r($hotelAminity);exit;
                if (!empty($hotelAminity)) {
                    $aminitHtml = "<ul class='roomactivities'>";
                    for ($i = 0; $i < count($hotelAminity); $i++) {
                        $aminitHtml .= '<li><span>' . $hotelAminity[$i] . '</li>';
                    }
                    $aminitHtml .= '</ul>';
                } else {
                    $aminitHtml = "No amenities available !";
                }

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

    public function getImageAccomodationDB($accomoID)
    {
        $objImgAccomo = new Travel_Model_TblAccomoImg();
        $img = $objImgAccomo->getAccomoImage($accomoID);
        foreach ($img as $val) {
            $imgDetail = $val['Details'];
        }
        return $imgDetail;
    }

    public function getAccomodationDetailAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        try {
            if ($this->_request->isXmlHttpRequest()) {
                $AccomSysId = $this->getRequest()->getParam('id');
            }
            $objAccomo = new Travel_Model_TblBuyHotel();
            $objAccImg = new Travel_Model_TblAccomoImg();
            $objRomms = new Travel_Model_TblAccomoRooms();

            $accomoDetail = $objAccomo->getAccomoWherID($AccomSysId);
            $accomoTitle = $objAccomo->getAccomodation($AccomSysId);
            $accImg = $objAccImg->getAccomoImage($AccomSysId);
            $accRooms = $objRomms->getAccomoRoomDetail($AccomSysId);

            $vaTit = array();
            foreach ($accRooms as $valRTitle) {

                $vaTit[$valRTitle['RoomTitle']][] = array('title' => trim($valRTitle['Title']), 'cost' => trim($valRTitle['DOccupCost']), 'DOccupMarkUp' => trim($valRTitle['DOccupMarkUp']), 'MarkUpType' => trim($valRTitle['MarkUpType']), 'MarkUpType' => trim($valRTitle['MarkUpType']), 'AminitiesMask' => trim($valRTitle['AminitiesMask']), 'InvnItemSysId' => $valRTitle['InvnItemSysId']);
            }

            $accomoMap = $objRomms->getAccomoMap($AccomSysId);
            foreach ($accomoMap as $map) {
                $hotel = 'Hotel ' . $map['Title'] . ' ' . trim($map['Address']);
                $mapHotel = str_replace(" ", "+", $hotel);
                $mapRes = '<iframe src="http://maps.google.com/maps?q=' . $mapHotel . '&loc:' . trim($map['GeoLat']) . '+' . trim($map['GeoLong']) . '&z=9&output=embed" width="600" height="450"></iframe>';
                $mapHotelRes = str_replace("++", "+", $mapRes);
                $mapHotelRs = str_replace(",+,+", "+", $mapHotelRes);
            }
            $res = array('accomoDetail' => $accomoDetail, 'accImg' => $accImg, 'accomoTitle' => $accomoTitle, 'accRooms' => $accRooms, 'mapHotelRs' => $mapHotelRs, 'vaTit' => $vaTit);
            $_SESSION['ROOM_DETAIL_HTL_DETAIL'] = $res;

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



    public function deleteMpInventoryAccomAction()
    {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $InvnItemSysId = $this->getRequest()->getParam('InvnItemSysId');
            $objHotel = new Travel_Model_TblBuyHotel();
            $objHotel->deleteMpInventoryAccom($InvnItemSysId);
            $response = array('success' => true);
            echo json_encode($response);
            exit;
        }
    }

    public function showTermsAction()
    {
        /* Disable Layout */
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $AccomSysId = $this->getRequest()->getParam('AccomSysId');
            $terms = $this->getRequest()->getParam('terms');
            $objHotel = new Travel_Model_TblBuyHotel();
            $objHotel->addTermsConditions($AccomSysId, $terms);
        }
    }

    //    public function getHotelDetailApiAction() {
    //        $this->_helper->viewRenderer->setNoRender(true);
    //        $this->_helper->layout->disableLayout();
    //        if ($this->_request->isXmlHttpRequest()) {
    //           //$resultIndex = $this->getRequest()->getParam('resultIndex');
    //
    //            $hotelCode =$this->getRequest()->getParam("hotelCode");
    //            $userip = $_SERVER['REMOTE_ADDR'];
    //           $obj = new Travel_Model_TblBuyHotel();
    //            $resultIndex  = $obj->gethotelResultIndex($hotelCode);
    //
    ////            $tokenid = $this->getRequest()->getParam('tokenid');
    ////            $traceid = $this->getRequest()->getParam('traceid');
    //
    //            $objApi = new Travel_Model_ApiIntegration();
    //            $hotelInfo = $objApi->getHotelInfo($resultIndex, $hotelCode, $userip, $_SESSION['tokenId'], $_SESSION['traceId']);
    //            $traceidSecondStep = new Zend_Session_Namespace('traceidSecondStep');
    //            $traceidSecondStep->traceId=$hotelInfo['HotelInfoResult']['TraceId'];
    //
    //
    //            $_SESSION['HOTELINFO'] = $hotelInfo;
    //            $hotelRoomD = $objApi->getHotelRoomDetail($userip, $_SESSION['tokenId'], $_SESSION['traceId'], $resultIndex, $hotelCode);
    //            $_SESSION['HOTEL_ROOM_DETAIL'] = $hotelRoomD;
    //
    //            $detail = array('hotelInfo' => $hotelInfo, 'hotelRoomD' => $hotelRoomD);
    //            echo json_encode($detail);
    //        }
    //    }

    public function getHotelDetailApiAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $strTokenidRequest = $this->getRequest()->getParam('tokenid');
            $resultIndex = $this->getRequest()->getParam('resultIndex');
            $hotelCode = $this->getRequest()->getParam("hotelCode");
            $userip = $this->getRequest()->getParam('userip');
            $tokenid = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();
            //$tokenid = $this->getRequest()->getParam('tokenid');
            $traceid = $this->getRequest()->getParam('traceid');
            $objApi = new Travel_Model_ApiIntegration();
            $hotelInfo = $objApi->getHotelInfo($resultIndex, $hotelCode, $userip, $tokenid, $traceid);

            if ($hotelInfo['HotelInfoResult']['ResponseStatus'] != '1') {

                $objHotel = new Travel_Model_TblBuyHotel();
                $dataUpdate = array('IsExpired' => '1');
                $Where['TokenId = ?'] = $strTokenidRequest;
                $objHotel->updateTraceIdExpired($dataUpdate, $Where);
            }

            $_SESSION['HOTELINFO'] = $hotelInfo;
            $hotelRoomD = $objApi->getHotelRoomDetail($userip, $tokenid, $traceid, $resultIndex, $hotelCode);
            $_SESSION['HOTEL_ROOM_DETAIL'] = $hotelRoomD;
            $detail = array('hotelInfo' => $hotelInfo, 'hotelRoomD' => $hotelRoomD);
            echo json_encode($detail);
        }
    }

    public function getHotelDetailForPackageAction()
    {

        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            ######## Code on 28th Dec ##############

            $itenaryID = $this->getRequest()->getParam('itnID');
            $inventoryID = $this->getRequest()->getParam('invID');
            $cityID = $this->getRequest()->getParam('cityID');
            $adults = $this->getRequest()->getParam('adults');
            $child = $this->getRequest()->getParam('child');
            $hotelname = $this->getRequest()->getParam('hotelname');
            $hotelsource = $this->getRequest()->getParam('hotelsource');
            $hotelsourceID = $this->getRequest()->getParam('hotelsourceID');
            $starrating = $this->getRequest()->getParam('starrating');
            $daysnum = $this->getRequest()->getParam('daysnum');
            $nightcount = $this->getRequest()->getParam('nightcount');

            ###### Code End On 28th Dec ############



            $resultIndex = $this->getRequest()->getParam('strresultindex');
            $hotelCode = $this->getRequest()->getParam("hotelcode");
            $userip = $this->getRequest()->getParam('userip');
            $tokenid = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();
            //$tokenid = $this->getRequest()->getParam('tokenid');
            $traceid = $this->getRequest()->getParam('traceid');
            if ($hotelsource == 'TBO') {
                $objApi = new Travel_Model_ApiIntegration();
                $hotelInfo = $objApi->getHotelInfo($resultIndex, $hotelCode, $userip, $tokenid, $traceid);
                /*
                if($hotelInfo['HotelInfoResult']['ResponseStatus'] != '1') {
                    $objHotel = new Travel_Model_TblBuyHotel();
                    $dataUpdate = array( 'IsExpired' => '1');
                    $Where['TraceId = ?'] = $traceid;
                    $objHotel->updateTraceIdExpired($dataUpdate,$Where);

                }
                */

                if ($hotelInfo['HotelInfoResult']['ResponseStatus'] != '1') {

                    $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                    $intGTXCityId =  $sessionhotelDirectSearchData->params['hotelXrefCityId'];


                    $objHotel = new Travel_Model_TblBuyHotel();
                    $dataUpdate = array('IsExpired' => '1');
                    $Where['CitySysId = ?'] = $intGTXCityId;
                    $objHotel->updateTraceIdExpired($dataUpdate, $Where);
                }


                $_SESSION['HOTELINFO'] = $hotelInfo;
                $hotelRoomD = $objApi->getHotelRoomDetail($userip, $tokenid, $traceid, $resultIndex, $hotelCode);
                $_SESSION['HOTEL_ROOM_DETAIL'] = $hotelRoomD;
                $detail = array('hotelInfo' => $hotelInfo, 'hotelRoomD' => $hotelRoomD);
            } else {
                $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                $sessionhotelDirectSearchData->params['apiSourceSysId'] = 4;
                $sessionhotelDirectSearchData->params['strTraceId'] = $traceid;
                $sessionhotelDirectSearchData->params['strHotelCode'] = $hotelCode;
                $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRoomInfo($sessionhotelDirectSearchData->params);
                if (isset($arrResponseData['hotels'][0]['rates'])) {
                    $detail = $arrResponseData['hotels'][0]['rates'];
                } else {
                    $detail = array();
                }
                //$detail = $arrResponseData[0]['rates'];
            }
            $this->view->detail = $detail;
            $this->view->itenaryID = $itenaryID;
            $this->view->inventoryID = $inventoryID;
            $this->view->cityID = $cityID;
            $this->view->adults = $adults;
            $this->view->child = $child;
            $this->view->hotelname = $hotelname;
            $this->view->hotelsource = $hotelsource;
            $this->view->hotelsourceID = $hotelsourceID;
            $this->view->starrating = $starrating;
            $this->view->daysnum = $daysnum;
            $this->view->nightcount = $nightcount;
        }
    }



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

    public function blockRoomDetailsAction()
    {

        $objApi = new Travel_Model_ApiIntegration();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $arrHotelRoomDetail = $sessionhotelDirectSearchData->params['hotelDetailArr'];
            $selectArr = !empty($this->getRequest()->getParam('roomDetail')) ? $this->getRequest()->getParam('roomDetail') : $arrHotelRoomDetail;
            $tokenId = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();
            $_SESSION['authenticationtokenId'] = $tokenId;
            $resultIndex = $this->getRequest()->getParam('resultIndex');
            $_SESSION['resultIndex'] = $resultIndex;
            $_SESSION['noOfRooms'] = $noOfRooms = !empty($this->getRequest()->getParam('noOfRooms')) ? $this->getRequest()->getParam('noOfRooms') : $_SESSION['noOfRooms'];
            $roomindexID = $this->getRequest()->getParam('roomindexID');
            $noofRes = count($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails']);




            //$_SESSION['TRACEID'] = $traceId;
            //$_SESSION['TOKENID'] = $tokenId;
            $_SESSION['HotelCode'] = $selectArr['hotelInfo']['HotelInfoResult']['HotelDetails']['HotelCode'];
            $j = $roomindexID - 1;
            //            echo "<pre>";
            //            print_r($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]);
            //            exit;
            for ($i = 0; $i < $noOfRooms; $i++) {

                //if ($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['RoomIndex'] == $roomindexID) {
                $rooms[] = array(
                    "RoomIndex" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['RoomIndex'], ".\r\n"),
                    "RoomTypeCode" => htmlspecialchars($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['RoomTypeCode']),
                    "RatePlanCode" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['RatePlanCode'], ".\r\n"),
                    "RoomTypeName" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['RoomTypeName'], ".\r\n"),
                    "BedTypeCode" => null,
                    "BedTypeDescription" => '',
                    "SmokingPreference" => "0",
                    "Supplements" => null,
                    'Price' => array(
                        "CurrencyCode" => "INR",
                        "RoomPrice" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['RoomPrice'], ".\r\n"),
                        "Tax" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['Tax'], ".\r\n"),
                        "ExtraGuestCharge" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['ExtraGuestCharge'], ".\r\n"),
                        "ChildCharge" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['ChildCharge'], ".\r\n"),
                        "OtherCharges" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['OtherCharges'], ".\r\n"),
                        "Discount" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['Discount'], ".\r\n"),
                        "PublishedPrice" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPrice'], ".\r\n"),
                        "PublishedPriceRoundedOff" => (int) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPriceRoundedOff'], ".\r\n"),
                        "OfferedPrice" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPrice'], ".\r\n"),
                        "OfferedPriceRoundedOff" => (int) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPriceRoundedOff'], ".\r\n"),
                        "AgentCommission" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentCommission'], ".\r\n"),
                        "AgentMarkUp" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentMarkUp'], ".\r\n"),
                        "ServiceTax" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['ServiceTax'], ".\r\n"),
                        "TDS" => (float) trim($selectArr['hotelRoomD']['GetHotelRoomResult']['HotelRoomsDetails'][$j]['Price']['TDS'], ".\r\n")
                    )
                );
                //}
                // $j++;
            }
            $objGest = new Travel_Model_Tbltbbcuser();
            $_SESSION['SELECTED_HTL_ID'] = $objGest->getAccomId($selectArr['hotelInfo']['HotelInfoResult']['HotelDetails']['HotelCode']);

            $datahRoom = array(
                "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                "TokenId" => $tokenId,
                "TraceId" => trim($selectArr['hotelRoomD']['GetHotelRoomResult']['TraceId']),
                "ResultIndex" => $resultIndex,
                "HotelCode" => $selectArr['hotelInfo']['HotelInfoResult']['HotelDetails']['HotelCode'],
                "HotelName" => $selectArr['hotelInfo']['HotelInfoResult']['HotelDetails']['HotelName'],
                "GuestNationality" => 'IN',
                "NoOfRooms" => $noOfRooms,
                "ClientReferenceNo" => "0",
                "IsVoucherBooking" => "true",
                "HotelRoomsDetails" => $rooms


            );
            $blkRoom = $objApi->blockRoom($datahRoom);
            //echo "<pre>";print_r($datahRoom);exit;
            $intErrorCode = $blkRoom['BlockRoomResult']['Error']['ErrorCode'];
            $strErrorMessage = $blkRoom['BlockRoomResult']['Error']['ErrorMessage'];

            if ($intErrorCode == 0) {

                $_SESSION['blkRoom'] = $blkRoom;
                $response['ERROR']['CODE']      = $intErrorCode;
                $response['ERROR']['MESSAGE']   = $strErrorMessage;
                $response['HOTELINFO']['API_SOURCE_ID'] = 3;
                $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
                $sessionPreBookingHotelDetails->params =  $response;
                $msg = 'success';
                $response = json_encode(array('success' => true, 'msg' => $msg));
            } else {
                $response['ERROR']['CODE']      = $intErrorCode;
                $response['ERROR']['MESSAGE']   = $strErrorMessage;
                $response['HOTELINFO']['API_SOURCE_ID'] = 3;
                $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
                $sessionPreBookingHotelDetails->params =  $response;

                $msg = $strErrorMessage . '<br/>Please try again after some time or contact administrator for more details. ';
                $response = json_encode(array('success' => false, 'msg' => $msg));
            }

            echo $response;
            exit;

            //
            //
            //
            //
            //            echo "<pre>";
            //            print_r($datahRoom);
            //            print_r($blkRoom);
            //            exit;




            //$this->_redirect('/buyhotel/hotel-guest-detail');
        }
    }

    public function bookRoomAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $intXRefTrxNo = $this->getRequest()->getParam('txnid');
        $strTrxStatus = $this->getRequest()->getParam('status');

        if ($strTrxStatus == "success" && !empty($intXRefTrxNo)) {
            if ($_SESSION['USER_DETAILS_HTL'][0]['Title'] == '1') {
                $gender = 'mr';
            } else if ($_SESSION['USER_DETAILS_HTL'][0]['Title'] == '2') {
                $gender = 'miss';
            } else {
                $gender = 'mrs';
            }
            $j = 0;
            $hotelPassenger[] = array(
                "Title" => $gender,
                "FirstName" => trim($_SESSION['USER_DETAILS_HTL'][0]['FirstName']),
                "Middlename" => null,
                "LastName" => trim($_SESSION['USER_DETAILS_HTL'][0]['LastName']),
                "Phoneno" => null,
                "Email" => null,
                "PaxType" => 1,
                "LeadPassenger" => true,
                "Age" => 0,
                "PassportNo" => null,
                "PassportIssueDate" => null,
                "PassportExpDate" => null
            );
            $rooms[] = array(
                "RoomIndex" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomIndex'], ".\r\n"),
                "RoomTypeCode" => htmlspecialchars($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomTypeCode']),
                "RoomTypeName" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomTypeName'], ".\r\n"),
                "RatePlanCode" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RatePlanCode'], ".\r\n"),
                "BedTypeCode" => null,
                "SmokingPreference" => "0",
                "Supplements" => null,
                'Price' => array(
                    "CurrencyCode" => "INR",
                    "RoomPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['RoomPrice'], ".\r\n"),
                    "Tax" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['Tax'], ".\r\n"),
                    "ExtraGuestCharge" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ExtraGuestCharge'], ".\r\n"),
                    "ChildCharge" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ChildCharge'], ".\r\n"),
                    "OtherCharges" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OtherCharges'], ".\r\n"),
                    "Discount" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['Discount'], ".\r\n"),
                    "PublishedPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPrice'], ".\r\n"),
                    "PublishedPriceRoundedOff" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPriceRoundedOff'], ".\r\n"),
                    "OfferedPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPrice'], ".\r\n"),
                    "OfferedPriceRoundedOff" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPriceRoundedOff'], ".\r\n"),
                    "AgentCommission" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentCommission'], ".\r\n"),
                    "AgentMarkUp" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentMarkUp'], ".\r\n"),
                    "ServiceTax" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ServiceTax'], ".\r\n"),
                    "TDS" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['TDS'], ".\r\n")
                ),
                "HotelPassenger" => $hotelPassenger
            );
            $datahRoom = array(
                "ResultIndex" => $_SESSION['resultIndex'],
                "HotelCode" => $_SESSION['HotelCode'],
                "HotelName" => $_SESSION['HOTELINFO']['HotelInfoResult']['HotelDetails']['HotelName'],
                "GuestNationality" => 'IN',
                "NoOfRooms" => $_SESSION['noOfRooms'],
                "ClientReferenceNo" => "0",
                "IsVoucherBooking" => "true",
                "HotelRoomsDetails" => $rooms,
                "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                "TokenId" => $_SESSION['TOKENID'],
                "TraceId" => $_SESSION['blkRoom']['BlockRoomResult']['TraceId']
            );

            $objApi = new Travel_Model_ApiIntegration();
            $_SESSION['BOOKING_RES'] = $objApi->bookRoom($datahRoom);
            $bookingRes = array("BookingId" => $_SESSION['BOOKING_RES']['BookResult']['BookingId'], "EndUserIp" => "172.16.0.137", "TokenId" => $_SESSION['TOKENID']);
            $objApi = new Travel_Model_ApiIntegration();
            echo $objApi->getBookingDetails($bookingRes);
        }
    }

    public function hotelGuestDetailAction()
    {

        $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
        //echo "<pre>";print_r($sessionhotelDirectSearchData->params);exit;
        $intCustomerSysIdIfCRM = $sessionhotelDirectSearchData->params['customerId'];  // if Flow comes from CRM
        $intTPSysIdIfCRM = !empty($sessionhotelDirectSearchData->params['TPSysId']) ? $sessionhotelDirectSearchData->params['TPSysId'] : '0';  // if Flow comes from CRM
        $intTPIntSysIdIfCRM = $sessionhotelDirectSearchData->params['TPIntSysId'];  // if Flow comes from CRM
        $hotelTotalRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];  // if Flow comes from CRM
        $memberDetails = $sessionhotelDirectSearchData->params['memberDetails'];  // if Flow comes from CRM

        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->viewRenderer->setNoRender(true);
            $this->_helper->layout->disableLayout();

            $intCustomerIdRequest = trim($this->getRequest()->getParam('customerId'));
            $intCustomerMemberSysIdRequest = !empty(trim($this->getRequest()->getParam('intCustomerMemberSysId'))) ? trim($this->getRequest()->getParam('intCustomerMemberSysId')) : '';
            $relation = trim($this->getRequest()->getParam('relation'));
            $initial = trim($this->getRequest()->getParam('initial'));
            $firstName = trim($this->getRequest()->getParam('firstName'));
            $lastName = trim($this->getRequest()->getParam('lastName'));
            $mobilNo = trim($this->getRequest()->getParam('mobilNo'));
            $emailId = trim($this->getRequest()->getParam('emailId'));
            $specialReq = trim($this->getRequest()->getParam('specialReq'));

            $checkInDate = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
            $explode_checkin_date = explode("/", $checkInDate);
            $checkInDate = $explode_checkin_date[2] . '-' . $explode_checkin_date[1] . '-' . $explode_checkin_date[0];
            $checkOutDate = $sessionhotelDirectSearchData->params['hotelToDateSession'];
            $explode_checkout_date = explode("/", $checkOutDate);
            $checkOutDate = $explode_checkout_date[2] . '-' . $explode_checkout_date[1] . '-' . $explode_checkout_date[0];

            $roomaarayMemInfo = array();
            $roomArrayProposal = array();
            $g = 0;
            for ($i = 1; $i <= count($memberDetails); $i++) {
                $roomaarayMemInfo[$i]['adult'] = $memberDetails[$g]['AdultPax'];
                $roomaarayMemInfo[$i]['child']['childcount'] = $memberDetails[$g]['ChildPax'];

                $childcount = $memberDetails[$g]['ChildPax'];
                $childnum = '';
                for ($j = 1; $j <= $childcount; $j++) {
                    $childnum = $childnum . ',' . $memberDetails[$g]['ChildsAge'];
                    $roomaarayMemInfo[$i]['child']['childage'] = trim($childnum, ",");
                }

                //create array for proposal
                $roomArrayProposal[$i]['Adult']  =  $memberDetails[$g]['AdultPax'];
                $roomArrayProposal[$i]['Child']  =  $memberDetails[$g]['ChildPax'];
                $roomArrayProposal[$i]['bedtype']  = 'none';
                $roomArrayProposal[$i]['departuredate'] = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
                $roomArrayProposal[$i]['returndate'] = $sessionhotelDirectSearchData->params['hotelToDateSession'];
                //$roomaaray[$i]['child'] = $this->_request->getParam('select-noOfChild'.$i);
                $g++;
            }
            $roomaarayinfo = json_encode($roomaarayMemInfo);
            $roomArrayProposal = json_encode($roomArrayProposal);


            $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
            $ROOM_DESCRIPTION = isset($sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_DESC']) ? $sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_DESC'] : '';
            $data['Salutation']  = $initial;
            $data['Relation']  = $relation;
            $data['FirstName'] = $firstName;
            $data['LastName']  = $lastName;
            $data['ContactNumber'] = $mobilNo;
            $data['EmailId'] = $emailId;
            $data['specialReq'] = $specialReq;
            $data['customerSysId'] = $intCustomerIdRequest;
            $data['InventoryType'] = 1;
            $data['CurrencyType'] = 1;
            $data['AdultPax'] = $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
            $data['ChildPax'] = $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
            $data['ChildsAge'] = $sessionhotelDirectSearchData->params['totalMemberCount']['ChildsAge'];
            $data['TotalPax'] = ($sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'] + $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax']);
            $data['StartDate'] = $checkInDate;
            $data['ValidTill'] = $checkOutDate;
            $data['CurrencyType'] = 1;
            $data['RoomInfoJson'] = $roomArrayProposal;
            $data['RoomMemInfoJson'] = $roomaarayinfo;
            $data['RoomTypeStr'] = isset($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][0]['RoomTypeName']) ? $_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][0]['RoomTypeName'] : '';
            $data['RoomTypeStrGRN'] = $ROOM_DESCRIPTION;
            $data['SourcePlaceSysId'] = $sessionhotelDirectSearchData->params['hotelXrefCityId'];
            $data['DestPlaceSysId'] = 0;
            $data['SourcePlaceName'] = $sessionhotelDirectSearchData->params['hotelCityTitle'];
            $data['DestPlaceName'] = '';
            $data['Countries'] = $sessionhotelDirectSearchData->params['countryCode'];
            $data['hotelCityTitle'] = $sessionhotelDirectSearchData->params['hotelCityTitle'];
            $data['hotelTotalNights'] = $sessionhotelDirectSearchData->params['hotelTotalNights'];
            $data['hotelStarRating'] = intval($sessionhotelDirectSearchData->params['hotelStarRating']);
            $data['TemplatePckSysId'] = $intTPSysIdIfCRM;



            //code added by Er Amit Kumar Dubey for lead source and leadstage on 3 march 2017 at 4:46 PM
            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            $intLeadSourceSysId = $this->_crmcustomerObj->getLeadSource($this->intLoggedinUserAgencySysId, 'Agency'); // for Master LeadSouce Creation
            $leadsource = (isset($intLeadSourceSysId[0]['LeadSourceSysId']) && !empty($intLeadSourceSysId[0]['LeadSourceSysId'])) ? $intLeadSourceSysId[0]['LeadSourceSysId'] : 0;

            $this->_leadstageObj = new Travel_Model_TblLeadStage();
            $getStageList = $this->_leadstageObj->getLeadStageSatus('New');
            $leadstage = (isset($getStageList[0]['TPStatusSysId']) && !empty($getStageList[0]['TPStatusSysId'])) ? $getStageList[0]['TPStatusSysId'] : 0;
            $data['LeadSourceSysId'] = $leadsource;
            $data['LeadStageSysId'] = $leadstage;
            //end of code added by Er Amit Kumar Dubey for lead source and leadstage on 3 march 2017 at 4:46 PM
            $objGest = new Travel_Model_Tbltbbcuser();
            if (empty($intCustomerIdRequest)) {
                //echo "<pre>"; print_r($data); exit;
                $intCustomerSysIdDb = $objGest->createAgencyCustomer($data);
                $data['customerSysId'] = $intCustomerSysIdDb;

                $checkCustomerrecordChanged = $objGest->getCustomerDetailsAll(trim($data['ContactNumber']), trim($data['EmailId']), trim($data['Salutation']), trim($data['Relation']), trim($data['FirstName']), trim($data['LastName']), $this->intLoggedinUserAgencySysId);
                $checkCustomerMMMBRrecordChanged = $objGest->getCustomerAndMembersDetailsAll(trim($data['ContactNumber']), trim($data['EmailId']), trim($data['Salutation']), trim($data['Relation']), trim($data['FirstName']), trim($data['LastName']), $this->intLoggedinUserAgencySysId);

                //echo count($checkCustomerrecordChanged);die;
                if (count($checkCustomerrecordChanged) == 0 && count($checkCustomerMMMBRrecordChanged) == 0) {
                    $intCustomerMemberSysId = $objGest->createAgencyCustomerMember($data);
                    $data['customerMemberSysId'] = $intCustomerMemberSysId;
                } else {
                    $data['customerMemberSysId'] = '0';
                }


                //$data['customerMemberSysId'] = '0';
                //$intCustomerMemberSysId = $objGest->createAgencyCustomerMember($data);
                //$data['customerMemberSysId'] = $intCustomerMemberSysId;
                if (!empty($intCustomerSysIdDb)) {
                    $arrTravelPlanIds = $objGest->createCustomerTravelPlanAndAll($data);
                    $intTpSysId = $arrTravelPlanIds['intTpSysId'];
                    $intTpIntSysId = $arrTravelPlanIds['intTpIntSysId'];
                }
            } else if (!empty($intCustomerIdRequest) && $relation != '0') {
                if (empty($intCustomerMemberSysIdRequest)) {
                    $intCustomerMemberSysId = $objGest->createAgencyCustomerMember($data);
                } else {
                    $intCustomerMemberSysId = $intCustomerMemberSysIdRequest;
                }

                $data['customerMemberSysId'] = $intCustomerMemberSysId;
                if (!empty($intCustomerMemberSysId)) {
                    $arrTravelPlanIds = $objGest->createCustomerTravelPlanAndAll($data);
                    $intTpSysId = $arrTravelPlanIds['intTpSysId'];
                    $intTpIntSysId = $arrTravelPlanIds['intTpIntSysId'];
                }
            } else if (!empty($intCustomerIdRequest) && $relation == '0') {
                //$intCustomerMemberSysIdDb = $objGest->createAgencyCustomerMember($data);
                $checkCustomerrecordChanged = $objGest->getCustomerDetailsAll(trim($data['ContactNumber']), trim($data['EmailId']), trim($data['Salutation']), trim($data['Relation']), trim($data['FirstName']), trim($data['LastName']), $this->intLoggedinUserAgencySysId);
                //echo count($checkCustomerrecordChanged);die;
                //echo "<pre>";print_r($checkCustomerrecordChanged); die;
                if (count($checkCustomerrecordChanged) == 0) {
                    $intCustomerMemberSysId = $objGest->createAgencyCustomerMember($data);
                    $data['customerMemberSysId'] = $intCustomerMemberSysId;
                } else {
                    $data['customerMemberSysId'] = '0';
                }
                if (!empty($intCustomerIdRequest)) {
                    $arrTravelPlanIds = $objGest->createCustomerTravelPlanAndAll($data);
                    $intTpSysId = $arrTravelPlanIds['intTpSysId'];
                    $intTpIntSysId = $arrTravelPlanIds['intTpIntSysId']; // Id for TB_Agency_Customer_TravelPlan_Itenary && TB_Agency_Customer_TravelPlan_Accom
                }
            }

            if (!empty($intCustomerSysIdDb)) {
                $intCustomerIdRequest = $intCustomerSysIdDb;
            }

            if (!empty($intCustomerIdRequest) && !empty($intTpSysId)) {
                $response = json_encode(array('success' => true, 'msg' => 'Success', 'cid' => base64_encode($intCustomerIdRequest), 'tid' => base64_encode($intTpSysId), 'it_id' => base64_encode($intTpIntSysId)));
            } else {
                $msg = 'Oops! There might be some technical error, Please try again after some time. ';
                $response = json_encode(array('success' => false, 'msg' => $msg, 'cid' => '', 'tid' => ''));
            }

            echo $response;
            exit;
        }




        $this->view->strSearchPageUrl = "/buyhotel/hotel-results";
        $objGest = new Travel_Model_Tbltbbcuser();
        $this->view->TPSysId  =  $intTpSysId = base64_decode(trim($this->getRequest()->getParam('tid')));
        $this->view->intCustomerSysId = $intCustomerSysId = base64_decode(trim($this->getRequest()->getParam('cid')));
        if (!empty($intCustomerSysIdIfCRM) && empty($intTpSysId)) {
            $this->view->intCustomerSysId = $intCustomerSysId = $intCustomerSysIdIfCRM;
            $this->view->TPSysId  =  $intTpSysId = $intTPSysIdIfCRM;
            $this->view->TPSysId  =  $intTpSysId = $intTPSysIdIfCRM;
        }

        if (!empty($intCustomerSysId)) {
            // for CRM Member Details
            $objBuyHotel = new Travel_Model_TblBuyHotel();
            $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
            //echo "<pre>";print_r($getCustomerDetail);exit;
            $intMemberSysId = @$getCustomerDetail['MemberSysId'];
            if (!empty($intMemberSysId)) {
                $this->view->intMemberSysId = $intMemberSysId;
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            } else {
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            }
        }

        $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
        $intAPISourceId = $sessionPreBookingHotelDetails->params['HOTELINFO']['API_SOURCE_ID'];
        if (!empty($intAPISourceId) && $intAPISourceId == "4") {
            $this->render("capture-guest-details");
        }
    }



    public function hotelVoucherAction()
    {

        $this->_helper->layout->disableLayout();

        $this->view->TPSysId  =  $intTpSysId = base64_decode(trim($this->getRequest()->getParam('tid')));;
        $this->view->intCustomerSysId = $intCustomerSysId = base64_decode(trim($this->getRequest()->getParam('cid')));

        $objBuyHotel = new Travel_Model_TblBuyHotel();
        $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
        $intMemberSysId = @$getCustomerDetail['MemberSysId'];
        if (!empty($intMemberSysId)) {
            $this->view->intMemberSysId = $intMemberSysId;
            $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
            $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
            $this->view->CustomerTitle = $getCustomerDetail['Title'];
            $this->view->CustomerRelation = $getCustomerDetail['Relation'];
            $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
            $this->view->CustomerLastName = $getCustomerDetail['LastName'];
        } else {
            $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
            $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
            $this->view->CustomerTitle = $getCustomerDetail['Title'];
            $this->view->CustomerRelation = $getCustomerDetail['Relation'];
            $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
            $this->view->CustomerLastName = $getCustomerDetail['LastName'];
        }




        $arrBookingDetails = $objBuyHotel->getBookingDetails($intTpSysId);
        $this->view->arrBookingDetails = json_decode($arrBookingDetails[0]['APIBookingRes'], 1);

        // print_r($this->view->arrBookingDetails); exit;


        $objgetAgencyAgent = new Travel_Model_TblAgencyCustomerTrx();
        $res = $objgetAgencyAgent->getAgentDetail();
        $_SESSION['AGENTDET'] = $res;
    }

    //    public function hotelVouchrAction() {
    //
    //        $this->_helper->layout->disableLayout();
    //        $objgetAgencyAgent = new Travel_Model_TblAgencyCustomerTrx();
    //        $res = $objgetAgencyAgent->getAgentDetail();
    //        $_SESSION['AGENTDET'] = $res;
    //    }

    public function makePaymentAction()
    {



        //        $html = new Zend_View();
        //        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
        //        //$URL='cid:'.$agencyCustomerDetails['CustomerSysId']."@@"."aid:".$agencysysID;
        //        //$encryptData=$this->getEnc($URL);
        //        $html->assign('type', 'HotelBookingPaymentConfirmationEmail');
        //        $html->assign('data', @$travelPlanDetail);
        //        $html->assign('getAgentDetail',@$getAgentDetail);
        //        $html->assign('agencyDetails',@$getAgencyDetail);
        //        $html->assign('ARR_SALUTION',@$ARR_SALUTION);
        //        //$html->assign('URL', $encryptData);
        //        echo $paymentconfirmText = $html->render('email-template.phtml');exit;


        //echo "<pre>";print_r($_REQUEST);exit;

        $objTrx = new Travel_Model_TblAgencyCustomerTrx();
        $intXRefTrxNo = $this->getRequest()->getParam('txnid');
        $strTrxStatus = $this->getRequest()->getParam('status');
        $TrxSysId = $this->getRequest()->getParam('TrxSysId');
        $TPSysId = $this->getRequest()->getParam('TPSysId');

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

        //Invoice Number...
        $strInvoiceNumber = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->generateInvoiceNumbers($this->intLoggedinUserAgencySysId);

        $data = array("InvoiceId" => $strInvoiceNumber);
        $objTrx->updateInvoiceNumber($data, $TrxSysId);
        //echo $strInvoiceNumber;exit;
        //Invoice Number...

        $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
        $API_SOURCE_ID = $sessionPreBookingHotelDetails->params['HOTELINFO']['API_SOURCE_ID'];
        $ROOMPRICE = $sessionPreBookingHotelDetails->params['ROOMPRICE']['NET_PRICE'];

        $intCustomerSysId = base64_decode(trim($this->getRequest()->getParam('cid')));
        $intTpSysId = base64_decode(trim($this->getRequest()->getParam('tid')));
        $intTpIntSysId = base64_decode(trim($this->getRequest()->getParam('it_id')));


        if (!empty($intCustomerSysId)) {

            $objBuyHotel = new Travel_Model_TblBuyHotel();
            $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
            $intMemberSysId = @$getCustomerDetail['MemberSysId'];
            $ARR_SALUTION = unserialize(ARR_SALUTION);
            if (!empty($intMemberSysId)) {
                $this->view->intMemberSysId = $intMemberSysId;
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $gender = $ARR_SALUTION[$getCustomerDetail['Title']];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $customerFirstName = $getCustomerDetail['FirstName'];
                $customerLastName = $getCustomerDetail['LastName'];
            } else {
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $gender = $ARR_SALUTION[$getCustomerDetail['Title']];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $customerFirstName = $getCustomerDetail['FirstName'];
                $customerLastName = $getCustomerDetail['LastName'];
            }
            if ($getCustomerDetail['Title'] == 1) {
                $strTitle = "Mr.";
            } elseif ($getCustomerDetail['Title'] == 2) {
                $strTitle = "Mrs.";
            } else {
                $strTitle = "Miss.";
            }

            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $strselectNationality = $sessionhotelDirectSearchData->params['selectNationality'];
        }


        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $travelPlanDetais = $this->_crmcusttravelplan->CheckCustomerWithLeadId($TPSysId);
        if ($API_SOURCE_ID == "4") { //echo $strTrxStatus."HI"; exit;

            if ($strTrxStatus == "success") {
                //echo "<pre>";print_r($sessionPreBookingHotelDetails->params);exit;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['PAXES']['DETAILS']['TITLE'] = $strTitle;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['PAXES']['DETAILS']['NAME'] = $customerFirstName;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['PAXES']['DETAILS']['LASTNAME'] = $customerLastName;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['PAXES']['DETAILS']['TYPE'] = "AD";

                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['TITLE'] = $strTitle;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['NAME'] = $customerFirstName;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['LASTNAME'] = $customerLastName;
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['EMAIL_ID'] = $getCustomerDetail['EmailId'];
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['PHONE_NO'] = $getCustomerDetail['Contacts'];
                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['ROOMPRICE']['NET_PRICE'] = $ROOMPRICE;

                $sessionPreBookingHotelDetails->params['GRN_PRE_BOOKING_DATA']['HOLDER']['DETAILS']['NATIONALITY'] = $strselectNationality;

                $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                $sessionPreBookingHotelDetails->params['memberDetails'] = $sessionhotelDirectSearchData->params['memberDetails'];

                $response = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->apiHotelBooking($sessionPreBookingHotelDetails->params);
                $ERROR_CODE = $response['ERROR']['CODE'];
                $ERROR_MESSAGE = $response['ERROR']['MESSAGE'];
                //echo "<pre>";print_r($response);
                if (empty($ERROR_CODE) && empty($ERROR_MESSAGE)) {
                    $arrHotelBookingResponse = isset($response['BOOKING_RESPONSE']) ? $response['BOOKING_RESPONSE'] : '';
                    $intServiceTaxAmount = !empty($arrHotelBookingResponse['price']['breakdown']['servicetax'][0]['amount']) ? $arrHotelBookingResponse['price']['breakdown']['servicetax'][0]['amount'] : '0';
                    $strBookingStatus = isset($response['BOOKING_RESPONSE']['status']) ? $response['BOOKING_RESPONSE']['status'] : '';
                    $strBookingId = isset($response['BOOKING_RESPONSE']['booking_id']) ? $response['BOOKING_RESPONSE']['booking_id'] : '';
                    $strBookingRef = isset($response['BOOKING_RESPONSE']['booking_reference']) ? $response['BOOKING_RESPONSE']['booking_reference'] : '';

                    $objBuyHotel = new Travel_Model_TblBuyHotel();
                    //                    $dataBooking = array(
                    //                        "APIBookingRes" => json_encode($arrHotelBookingResponse)
                    //                    );





                    //send email to customer

                    $travelplanObj = new Travel_Model_CRM_CustomerTravelPlan();
                    $travelPlanDetail = $travelplanObj->GetTravelPlanCustomerDetailsPax($intTpSysId);


                    $roomType = isset($sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_TYPE']) ? $sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_TYPE'] : '';
                    $hotelNorms = isset($sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_INSTRUCTIONS']) ? $sessionPreBookingHotelDetails->params['ROOMINFO']['ROOM_INSTRUCTIONS'] : '';
                    $travelPlanDetail[0]['ACCOMROOMTitle'] = $roomType;
                    $travelPlanDetail[0]['HOTELPOLICY'] = $hotelNorms;


                    //echo "<pre>";print_r($travelPlanDetail);exit;
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
                    //$URL='cid:'.$agencyCustomerDetails['CustomerSysId']."@@"."aid:".$agencysysID;
                    //$encryptData=$this->getEnc($URL);
                    $agencyStaffObj = new Travel_Model_TblAgencyStaff();
                    $agentDetail = $agencyStaffObj->getUserDetailsById($travelPlanDetail[0]['AgentSysId']);
                    $AgencySysId = $travelPlanDetail[0]['AgencySysId'];
                    $getAgentDetail = array('AgentName' => $agentDetail['FirstName'] . " " . $agentDetail['LastName'], 'AgentContact' => $agentDetail['ContactNo1'], 'AgentEmail' => $agentDetail['EmailId']);
                    $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                    $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
                    $getAgencyDetail['fullAddress'] = isset($agencyAddress['CityName']) ? $agencyAddress['CityName'] . $agencyState . $agencyCountry : '';
                    $html->assign('type', 'HotelBookingPaymentConfirmationEmail');
                    $html->assign('data', $travelPlanDetail);
                    $html->assign('getAgentDetail', $getAgentDetail);
                    $html->assign('agencyDetails', $getAgencyDetail);
                    $html->assign('ARR_SALUTION', $ARR_SALUTION);
                    $html->assign('bookingresponse', $response);
                    $html->assign('hotelsource', 4);
                    //$html->assign('URL', $encryptData);
                    $paymentconfirmText = $html->render('email-template.phtml');
                    $html->assign('type', 'HotelBookingConfirmationEmailText');
                    $html->assign('data', $travelPlanDetail);
                    $html->assign('getAgentDetail', $getAgentDetail);
                    $html->assign('agencyDetails', $getAgencyDetail);
                    $html->assign('ARR_SALUTION', $ARR_SALUTION);

                    $bookingConfirmText = $html->render('email-template.phtml');

                    $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
                    $this->smtpUserName = $aConfig['smtpUserName'];
                    $this->smtpPassword = $aConfig['smtpPassword'];
                    $this->smtpPort     = $aConfig['smtpPort'];
                    $this->smtpHost     = $aConfig['smtpHost'];
                    $this->fromEmail    = $aConfig['fromEmail'];
                    $this->fromName     = $aConfig['fromName'];
                    $emailId            = '' . trim($travelPlanDetail[0]['EmailId']) . '';
                    $emailData1         = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => stripslashes($travelPlanDetail[0]['hotelCityTitle']) . ' Trip Payment Receipt', 'to' => array(trim($emailId)), 'bodyHtml' => $paymentconfirmText, 'bodyText' => '');
                    $emailData2         = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => stripslashes($travelPlanDetail[0]['hotelCityTitle']) . ' Trip Booking Details', 'to' => array(trim($emailId)), 'bodyHtml' => $bookingConfirmText, 'bodyText' => '');
                    try {
                        //echo "success";

                        $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                        $arrEmailStatistics = array(
                            "TPSysId" => $TPSysId,
                            "TypeSysId" => 1,  // 1 For Email 2 For SMS
                            "AgencySysId" => $this->intLoggedinUserAgencySysId,
                            "AgentSysId" => $this->intLoggedinUserId,
                            "Title" => $paymentconfirmText,
                            "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                            "Status" => 0,
                            "RefSysId" => "",
                            "RefSysStatus" => "",
                            "CreateDate" => date('Y-m-d H:i:s')
                        );
                        $arrEmailStatistics2 = array(
                            "TPSysId" => $TPSysId,
                            "TypeSysId" => 1,  // 1 For Email 2 For SMS
                            "AgencySysId" => $this->intLoggedinUserAgencySysId,
                            "AgentSysId" => $this->intLoggedinUserId,
                            "Title" => $bookingConfirmText,
                            "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                            "Status" => 0,
                            "RefSysId" => "",
                            "RefSysStatus" => "",
                            "CreateDate" => date('Y-m-d H:i:s')
                        );


                        $this->mailSentByElastice($emailData1, $arrEmailStatistics, 1, $travelPlanDetail[0]['CustomerSysId']);
                        $this->mailSentByElastice($emailData2, $arrEmailStatistics2, 1, $travelPlanDetail[0]['CustomerSysId']);
                        $msg = "success";
                    } catch (Exception $err) {
                        //print_r($err, true);
                        $msg = "failed";
                    }
                    //end of send email to customer




























                    if (!empty($TPSysId)) { //print_r($dataBooking); exit;
                        //$objBuyHotel->updateBookingDetails($dataBooking,$TPSysId);
                        if (!empty($strBookingStatus) && $strBookingStatus == "confirmed") {
                            $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '17'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING CONFIRMED
                        } else {
                            $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '7'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING FAILED
                        }
                        if (!empty($strBookingId)) {
                            $data = array(
                                "XRefBookingId" => $strBookingId . "/" . $strBookingRef,
                                //"XServiceTaxAmount" => $intServiceTaxAmount,
                                "APIBookingRes" => json_encode($response)
                            );
                        } else {
                            $data = array(
                                "XRefBookingId" => $strBookingRef,
                                //"XServiceTaxAmount" => $intServiceTaxAmount,
                                "APIBookingRes" => json_encode($response)
                            );
                        }

                        $objTrx->updateAccomoWithBookingID($data, $intTpIntSysId);
                    }
                    //echo "<pre>";print_r($arrHotelBookingResponse);exit;
                    $_SESSION['PAYMENT_MES'] = "";
                    //$this->view->redirectUrl = "/buyhotel/booking-confirmation/cid/".base64_encode(trim($intCustomerSysId))."/tid/".base64_encode(trim($intTpSysId))."/it_id/".base64_encode(trim($intTpIntSysId));
                    $this->_redirect("/buyhotel/booking-confirmation/cid/" . base64_encode(trim($intCustomerSysId)) . "/tid/" . base64_encode(trim($intTpSysId)) . "/it_id/" . base64_encode(trim($intTpIntSysId)));
                    exit;
                } else {

                    $urlData = array(
                        "customerSysId" => $intCustomerSysId,
                        "TPSysId" => $intTpSysId,
                        "intTpIntSysId" => $intTpIntSysId,
                        "guid" => $guid,
                        "TrxSysId" => $TrxSysId
                    );

                    $strUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataEncode($urlData);

                    $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '7'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING FAILED
                    $_SESSION['PAYMENT_MES'] = "Oops! We are enable to complete your request right now. please try again or contact adminstrator for more details.";
                    $this->_redirect("/buyhotel/process-refund/data/" . $strUrlData);  // To process refund
                    exit;


                    //                    $this->_redirect("/buyhotel/booking-confirmation/cid/".base64_encode(trim($intCustomerSysId))."/tid/".base64_encode(trim($intTpSysId))."/it_id/".base64_encode(trim($intTpIntSysId)));
                    //                    exit;


                }
            } else {
                $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '6'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING FAILED
                $_SESSION['PAYMENT_MES'] = "Payment unsuccessful";
                $this->_redirect("/buyhotel/booking-confirmation/cid/" . base64_encode(trim($intCustomerSysId)) . "/tid/" . base64_encode(trim($intTpSysId)) . "/it_id/" . base64_encode(trim($intTpIntSysId)));
                exit;
            }
        } else {

            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $arrMemberDetails = $sessionhotelDirectSearchData->params['memberDetails'];
            //echo "<pre>";print_r($arrMemberDetails);
            $intNoOfAdults = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
            $intNoOfChild = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
            $intTotalPaxCount = $intNoOfAdults + $intNoOfChild;

            if ($strTrxStatus == "success") {
                //$noOfRooms = $_SESSION['noOfRooms'];
                $j = 0;
                for ($i = 0; $i < count($arrMemberDetails); $i++) {
                    $hotelPassenger = array();
                    $AdultPaxTotal = $arrMemberDetails[$i]['AdultPax'];
                    $ChildPaxTotal = $arrMemberDetails[$i]['ChildPax'];
                    if ($AdultPaxTotal > 0) {
                        for ($m = 0; $m < $AdultPaxTotal; $m++) {
                            $hotelPassenger[] = array(
                                "Title" => $gender,
                                "FirstName" => trim($customerFirstName),
                                "Middlename" => "",
                                "LastName" => trim($customerLastName),
                                "Phoneno" => trim($getCustomerDetail['Contacts']),
                                "Email" => trim($getCustomerDetail['EmailId']),
                                "PaxType" => 1,
                                "LeadPassenger" => ($m == 0) ? true : false,
                                "Age" => 0,
                                "PassportNo" => "J3578965",
                                "PassportIssueDate" => "0001-01-01T00:00:00",
                                "PassportExpDate" => "0001-01-01T00:00:00"
                            );
                        }
                    }
                    if ($ChildPaxTotal > 0) {
                        $arrChildPaxTotal = explode(",", $arrMemberDetails[$i]['ChildsAge']);
                        for ($m = 0; $m < $ChildPaxTotal; $m++) {
                            $hotelPassenger[] = array(
                                "Title" => $gender,
                                "FirstName" => trim($customerFirstName),
                                "Middlename" => "",
                                "LastName" => trim($customerLastName),
                                "Phoneno" => trim($getCustomerDetail['Contacts']),
                                "Email" => trim($getCustomerDetail['EmailId']),
                                "PaxType" => 2,
                                "LeadPassenger" => false,
                                "Age" => $arrChildPaxTotal[$m],
                                "PassportNo" => "J3578965",
                                "PassportIssueDate" => "0001-01-01T00:00:00",
                                "PassportExpDate" => "0001-01-01T00:00:00"
                            );
                        }
                    }



                    $rooms[] = array(
                        "RoomIndex" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomIndex'], ".\r\n"),
                        "RoomTypeCode" => htmlspecialchars($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomTypeCode']),
                        "RoomTypeName" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomTypeName'], ".\r\n"),
                        "RatePlanCode" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RatePlanCode'], ".\r\n"),
                        "BedTypeCode" => null,
                        "SmokingPreference" => "0",
                        "Supplements" => null,
                        'Price' => array(
                            "CurrencyCode" => "INR",
                            "RoomPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['RoomPrice'], ".\r\n"),
                            "Tax" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['Tax'], ".\r\n"),
                            "ExtraGuestCharge" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ExtraGuestCharge'], ".\r\n"),
                            "ChildCharge" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ChildCharge'], ".\r\n"),
                            "OtherCharges" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OtherCharges'], ".\r\n"),
                            "Discount" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['Discount'], ".\r\n"),
                            "PublishedPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPrice'], ".\r\n"),

                            "PublishedPriceRoundedOff" => (int) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['PublishedPriceRoundedOff'], ".\r\n"),
                            "OfferedPrice" => (float) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPrice'], ".\r\n"),
                            "OfferedPriceRoundedOff" => (int) trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['OfferedPriceRoundedOff'], ".\r\n"),

                            "AgentCommission" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentCommission'], ".\r\n"),
                            "AgentMarkUp" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['AgentMarkUp'], ".\r\n"),
                            "ServiceTax" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['ServiceTax'], ".\r\n"),
                            "TDS" => trim($_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['Price']['TDS'], ".\r\n")
                        ),
                        "HotelPassenger" => $hotelPassenger
                    );
                    //$j++;
                }





                $tokenId = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();
                $datahRoom = array(
                    "ResultIndex" => $_SESSION['resultIndex'],
                    "HotelCode" => $_SESSION['HotelCode'],
                    "HotelName" => $_SESSION['HOTELINFO']['HotelInfoResult']['HotelDetails']['HotelName'],
                    "GuestNationality" => 'IN',
                    "NoOfRooms" => $_SESSION['noOfRooms'],
                    "ClientReferenceNo" => 0,
                    "IsVoucherBooking" => true,
                    "HotelRoomsDetails" => $rooms,
                    "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                    "TokenId" => $tokenId,
                    "TraceId" => $_SESSION['blkRoom']['BlockRoomResult']['TraceId']
                );
                //echo "<pre>";print_r($datahRoom);exit;

                //Write Request Logs starts...
                //            $strFilePath = "apihotels/book/".$tokenId."book_request.json";
                //            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath,  json_encode($datahRoom,JSON_PRETTY_PRINT));
                //Write Request Logs starts...


                $objApi = new Travel_Model_ApiIntegration();
                $_SESSION['BOOKING_RES'] = $arrHotelBookingResponse = $objApi->bookRoom($datahRoom);
                $strHotelBookingStatus = $arrHotelBookingResponse['BookResult']['HotelBookingStatus'];

                $objBuyHotel = new Travel_Model_TblBuyHotel();
                //                    $dataBooking = array(
                //                        "APIBookingRes" => json_encode($arrHotelBookingResponse)
                //                        //"XRefTrxNo" => $intXRefTrxNo,
                //                    );


                $strBookingStatus = @$arrHotelBookingResponse['BookResult']['HotelBookingStatus'];
                $strBookingId = @$arrHotelBookingResponse['BookResult']['BookingId'];
                $strBookingRef = @$arrHotelBookingResponse['BookResult']['BookingRefNo'];
                if (!empty($TPSysId)) { //print_r($dataBooking); exit;
                    //$objBuyHotel->updateBookingDetails($dataBooking,$TPSysId);
                    $travelPlanDetais = $this->_crmcusttravelplan->CheckCustomerWithLeadId($TPSysId);
                    if (!empty($strBookingStatus) && $strBookingStatus == "Confirmed") {
                        $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '17'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING CONFIRMED
                    } else {
                        $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '7'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING FAILED
                    }

                    $data = array(
                        "XRefBookingId" => $strBookingId . "/" . $strBookingRef,
                        "APIBookingRes" => json_encode($arrHotelBookingResponse)
                    );
                    $objTrx->updateAccomoWithBookingID($data, $intTpIntSysId);
                }














                //send email to customer

                $travelplanObj = new Travel_Model_CRM_CustomerTravelPlan();
                $travelPlanDetail = $travelplanObj->GetTravelPlanCustomerDetailsPax($intTpSysId);
                $travelPlanDetail[0]['ACCOMROOMTitle'] = $_SESSION['blkRoom']['BlockRoomResult']['HotelRoomsDetails'][$j]['RoomTypeName'];
                //$travelPlanDetail[0]['HOTELPOLICY'] = $hotelNorms;

                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/proposal/');
                //$URL='cid:'.$agencyCustomerDetails['CustomerSysId']."@@"."aid:".$agencysysID;
                //$encryptData=$this->getEnc($URL);
                $agencyStaffObj = new Travel_Model_TblAgencyStaff();
                $agentDetail = $agencyStaffObj->getUserDetailsById($travelPlanDetail[0]['AgentSysId']);
                $AgencySysId = $travelPlanDetail[0]['AgencySysId'];
                $getAgentDetail = array('AgentName' => $agentDetail['FirstName'] . " " . $agentDetail['LastName'], 'AgentContact' => $agentDetail['ContactNo1'], 'AgentEmail' => $agentDetail['EmailId']);
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId);
                $getAgencyDetail['fullAddress'] = isset($agencyAddress['CityName']) ? $agencyAddress['CityName'] . $agencyState . $agencyCountry : '';
                $html->assign('type', 'HotelBookingPaymentConfirmationEmail');
                $html->assign('data', $travelPlanDetail);
                $html->assign('getAgentDetail', $getAgentDetail);
                $html->assign('agencyDetails', $getAgencyDetail);
                $html->assign('ARR_SALUTION', $ARR_SALUTION);
                //$html->assign('URL', $encryptData);
                $paymentconfirmText = $html->render('email-template.phtml');
                $html->assign('type', 'HotelBookingConfirmationEmailText');
                $html->assign('data', $travelPlanDetail);
                $html->assign('getAgentDetail', $getAgentDetail);
                $html->assign('agencyDetails', $getAgencyDetail);
                $html->assign('ARR_SALUTION', $ARR_SALUTION);

                $bookingConfirmText = $html->render('email-template.phtml');

                $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
                $this->smtpUserName = $aConfig['smtpUserName'];
                $this->smtpPassword = $aConfig['smtpPassword'];
                $this->smtpPort     = $aConfig['smtpPort'];
                $this->smtpHost     = $aConfig['smtpHost'];
                $this->fromEmail    = $aConfig['fromEmail'];
                $this->fromName     = $aConfig['fromName'];
                $emailId            = '' . trim($travelPlanDetail[0]['EmailId']) . '';
                $emailData1         = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => stripslashes($travelPlanDetail[0]['hotelCityTitle']) . ' Trip Payment Receipt', 'to' => array(trim($emailId)), 'bodyHtml' => $paymentconfirmText, 'bodyText' => '');
                $emailData2         = array('fromEmail' => $this->fromEmail, 'fromName' => $this->fromName, 'subject' => stripslashes($travelPlanDetail[0]['hotelCityTitle']) . ' Trip Booking Details', 'to' => array(trim($emailId)), 'bodyHtml' => $bookingConfirmText, 'bodyText' => '');
                try {
                    //echo "success";
                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $arrEmailStatistics = array(
                        "TPSysId" => $TPSysId,
                        "TypeSysId" => 1,  // 1 For Email 2 For SMS
                        "AgencySysId" => $this->intLoggedinUserAgencySysId,
                        "AgentSysId" => $this->intLoggedinUserId,
                        "Title" => $paymentconfirmText,
                        "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => date('Y-m-d H:i:s')
                    );
                    $arrEmailStatistics2 = array(
                        "TPSysId" => $TPSysId,
                        "TypeSysId" => 1,  // 1 For Email 2 For SMS
                        "AgencySysId" => $this->intLoggedinUserAgencySysId,
                        "AgentSysId" => $this->intLoggedinUserId,
                        "Title" => $bookingConfirmText,
                        "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => date('Y-m-d H:i:s')
                    );
                    $this->mailSentByElastice($emailData1, $arrEmailStatistics, 1, $travelPlanDetail[0]['CustomerSysId']);
                    $this->mailSentByElastice($emailData2, $arrEmailStatistics2, 1, $travelPlanDetail[0]['CustomerSysId']);
                    $msg = "success";
                } catch (Exception $err) {
                    //print_r($err, true);
                    $msg = "failed";
                }
                //end of send email to customer












                //$objTrx->updateAccomoWithBookingID($data,$TPSysId);
                $paymentDetail = $this->getRequest()->getPost();
                $_SESSION['PAYMENT_RESPONSE'] = $paymentDetail;



                //if(!empty($strHotelBookingStatus)){
                $bookingRes = array("BookingId" => $_SESSION['BOOKING_RES']['BookResult']['BookingId'], "EndUserIp" => $_SERVER['REMOTE_ADDR'], "TokenId" => $tokenId);
                $objApi = new Travel_Model_ApiIntegration();
                $_SESSION['BOOKING_DETAILS'] = $arrBookingDetails = $objApi->getBookingDetails($bookingRes);
                $this->_redirect("/buyhotel/booking-confirmation/cid/" . base64_encode(trim($intCustomerSysId)) . "/tid/" . base64_encode(trim($intTpSysId)) . "/it_id/" . base64_encode(trim($intTpIntSysId)));

                //}

            } else {
                $objBuyHotel->updateBookingStatusTravelPlan(array("StatusType" => '6'), $TPSysId, $travelPlanDetais[0]['MasterTPSysId']); // FOR BOOKING FAILED
                $_SESSION['PAYMENT_MES'] = "Payment unsuccessful";
                $this->_redirect("/buyhotel/booking-confirmation/cid/" . base64_encode(trim($intCustomerSysId)) . "/tid/" . base64_encode(trim($intTpSysId)) . "/it_id/" . base64_encode(trim($intTpIntSysId)));
            }
        }
    }



    public function processRefundAction()
    {


        $strUrlData  =  $this->getRequest()->getParam('data');
        $arrUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataDecode($strUrlData);
        //echo "<pre>";print_r($arrUrlData);//exit;

        $this->view->intCustomerSysId = $intCustomerSysId = $arrUrlData['customerSysId'];
        $this->view->intTpSysId = $intTpSysId = $arrUrlData['TPSysId'];
        $this->view->intTpIntSysId = $intTpIntSysId = $arrUrlData['intTpIntSysId'];
        $this->view->strGuid = $strGuid = $arrUrlData['guid'];
        $this->view->TrxSysId = $TrxSysId = $arrUrlData['TrxSysId'];

        $fullBaseUrl = $this->view->baseUrl();
        $this->view->refundUrl = $fullBaseUrl . "/payment/booking-refund";
        $this->view->strReturnURL = $fullBaseUrl . "/buyhotel/booking-confirmation/cid/" . base64_encode($intCustomerSysId) . "/tid/" . base64_encode($intTpSysId) . "/it_id/" . base64_encode($intTpIntSysId);
        $this->view->strErrorURL = $fullBaseUrl . "/buyhotel/booking-confirmation/cid/" . base64_encode($intCustomerSysId) . "/tid/" . base64_encode($intTpSysId) . "/it_id/" . base64_encode($intTpIntSysId);
        $this->view->intPlanType = "2";
        $this->view->strTrxType = "R";



        if (!empty($intCustomerSysId)) {
            // for CRM Member Details
            $objBuyHotel = new Travel_Model_TblBuyHotel();
            $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
            $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
        }



        $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
        $NO_OF_ROOMS = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_ROOMS'];
        $ARR_ROOMPRICE = $sessionPreBookingHotelDetails->params['ROOMPRICE'];
        $NO_OF_CHILD = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_CHILD'];
        $NO_OF_ADULTS = $sessionPreBookingHotelDetails->params['ROOMINFO']['NO_OF_ADULTS'];


        if (count($ARR_ROOMPRICE) > 0 && !empty($ARR_ROOMPRICE)) {
            $intRoomPrice = 0;
            $intTax = 0;
            $intServiceFee = 0;
            //for ($i = 1; $i<=$NO_OF_ROOMS; $i++){
            $strCurrencyCode = $ARR_ROOMPRICE['CURRENCY'];
            $intRoomPrice += $ARR_ROOMPRICE['PRICE'];
            $intTax += $ARR_ROOMPRICE['SURCHARGE_TAX'];
            $intServiceFee += $ARR_ROOMPRICE['SERVICE_FEE'];
            //}
        }



        $intRoomPrice = round($intRoomPrice);
        $this->view->intRoomCount =  $intRoomCount = $_SESSION['noOfRooms'];
        $this->view->intNigthsCount =  $intNigthsCount = $_SESSION['nights'];
        $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
        $intNoOfAdults = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
        $intNoOfChild = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
        $intTotalPaxCount = $intNoOfAdults + $intNoOfChild;
        $strCountryCode = $sessionhotelDirectSearchData->params['countryCode'];

        $arrHotelPriceAndMarkupsDetails = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($intRoomPrice, "0", $intNigthsCount, $intRoomCount, $strCountryCode);
        if (!empty($arrHotelPriceAndMarkupsDetails)) {
            $intBasePrice = $arrHotelPriceAndMarkupsDetails['intBasePrice'];
            $intSTaxOnBasePrice = $arrHotelPriceAndMarkupsDetails['intSTaxOnBasePrice'];
            $intPriceWithMarkUpsAndSTax = $arrHotelPriceAndMarkupsDetails['intPriceWithMarkUpsAndSTax'];
            $intGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intGTXMarkUp'];
            $intSTaxOnGTXMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnGTXMarkUp'];
            $intGTXMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intGTXMarkUpWithSTax'];
            $intAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUp'];
            $intSTaxOnAgencyMarkUp = $arrHotelPriceAndMarkupsDetails['intSTaxOnAgencyMarkUp'];
            $intAgencyMarkUpWithSTax = $arrHotelPriceAndMarkupsDetails['intAgencyMarkUpWithSTax'];
            $intNetSTax = $arrHotelPriceAndMarkupsDetails['intNetSTax'];
        } else {
            $intBasePrice = 0;
            $intSTaxOnBasePrice = 0;
            $intPriceWithMarkUpsAndSTax = 0;
            $intGTXMarkUp = 0;
            $intSTaxOnGTXMarkUp = 0;
            $intGTXMarkUpWithSTax = 0;
            $intAgencyMarkUp = 0;
            $intSTaxOnAgencyMarkUp = 0;
            $intAgencyMarkUpWithSTax = 0;
            $intNetSTax = 0;
        }

        $intTotalRoomPrice = ($intBasePrice) + $intGTXMarkUpWithSTax;
        $intRoomFarePerNightPerRoom = ($intTotalRoomPrice / $intNigthsCount) / $intRoomCount;
        $intAllApplicableSTax = $intSTaxOnBasePrice + $intSTaxOnGTXMarkUp + $intSTaxOnAgencyMarkUp;
        $intTotalNetPayable = $intTotalRoomPrice + $intAgencyMarkUpWithSTax;

        $arrServiceTaxOnNetPayable = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intTotalNetPayable, "H", 9);
        $intServiceTaxOnNetPayable = !empty($arrServiceTaxOnNetPayable['serviceTaxAmount']) ? $arrServiceTaxOnNetPayable['serviceTaxAmount'] : 0;

        $intTotalNetPayable = ($intTotalNetPayable + $intServiceTaxOnNetPayable);


        $arrServiceTaxOnBaseAmount = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intBasePrice, "H", 9);
        $intServiceTaxOnBaseAmount = !empty($arrServiceTaxOnBaseAmount['serviceTaxAmount']) ? $arrServiceTaxOnBaseAmount['serviceTaxAmount'] : 0;

        $arrSTaxOnGTXMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intGTXMarkUp, "H", 9);
        $intSTaxOnGTXMarkUp = !empty($arrSTaxOnGTXMarkUp['serviceTaxAmount']) ? $arrSTaxOnGTXMarkUp['serviceTaxAmount'] : 0;

        $arrSTaxOnAgencyMarkUp = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax($intAgencyMarkUp, "H", 9);
        $intSTaxOnAgencyMarkUp = !empty($arrSTaxOnAgencyMarkUp['serviceTaxAmount']) ? $arrSTaxOnAgencyMarkUp['serviceTaxAmount'] : 0;




        $arrPriceAndMarkups = array(
            "intAgentMarkUpAmount" => 0,
            "intAgencyMarkUpAmount" => $intAgencyMarkUp,
            "intGTXMarkUpAmount" => $intGTXMarkUp,
            "intTotalAmount" => ($intBasePrice),
            "intTax" => $intServiceTaxOnBaseAmount,
            "GTXServiceTaxAmount" => $intSTaxOnGTXMarkUp,
            "AgentServiceTaxAmount" => $intSTaxOnAgencyMarkUp,
            "AgentsCustomServiceTaxAmount" => "0",
            "Pax" => $intTotalPaxCount,
            "SupplierSourceStr" => "API",
            "MarketPlaceId" => "1",
            "TotalDiscount" => "0",
            "CurrencyType" => "1"
        );
        //echo "<pre>";print_r($arrPriceAndMarkups);echo "</pre>";//exit;
        $strPriceAndMarkups = json_encode($arrPriceAndMarkups);
        $this->view->stringData = $strStringData = $this->getEnc($strPriceAndMarkups);

        if (!empty($intPriceWithMarkUpsAndSTax)) {
            $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intTotalNetPayable;
        } else {
            $this->view->intGrandPayableAmount = $intGrandPayableAmount = $intBasePrice;
        }




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

        $this->view->guid = $strGuid;
        $this->view->walletCode = $this->walletCode($this->intLoggedinUserAgencySysId, $this->view->guid, $intGrandPayableAmount, $this->intLoggedinUserId, $intTpSysId, $intCustomerSysId, $strStringData);
        $this->view->securecode = $this->secureCode($this->intLoggedinUserAgencySysId, $this->view->guid);
    }








    public function sessionExAction()
    {
        $this->_helper->layout->disableLayout();
        session_unset($_SESSION['SEARCH']);

        session_unset($_SESSION['chekInDate']);
        session_unset($_SESSION['chekOutDate']);
        session_unset($_SESSION['nights']);
        session_unset($_SESSION['noOfAdults']);
        session_unset($_SESSION['noOfRooms']);
        session_unset($_SESSION['getdata']);
    }

    public function getSuplierDetailAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $id = $this->getRequest()->getParam('id');
            $obj = new Travel_Model_TblBuyHotel();
            $res = $obj->getSuplierData($id);

            echo json_encode($res);
        }
    }

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

        $id = $this->getRequest()->getParam('id');
        $InventoryType = $this->getRequest()->getParam('InventoryType');
        $_SESSION['SELECTED_HTL_ID'] = $id;
        $obj = new Travel_Model_TblBuyHotel();
        $obj1 = new Travel_Model_TblAccomoRooms();
        $res = $obj->getHtlInventyData($id, $InventoryType);
        $rooms = $obj->gethtlInventryInduData($id, $InventoryType);
        $_SESSION['BOOK_ROM_INVENTORY'] = $rooms;
        echo json_encode($res);
        //print_r($res1);
    }

    public function saveSuplierAmtAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $amount = $this->getRequest()->getParam("amount");

            $_SESSION['SUPLIERAMT'] = $amount;
        }

        echo 'true';
    }

    public function hotelSendEmailFormAction()
    {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isPost()) {

            $objHotel = new Travel_Model_TblBuyHotel();
            $this->view->arrMPType = $objHotel->getAllMPType();

            //$Objcustomertravelplan=new Travel_Model_CRM_CustomerTravelPlan();
            //$taxdetailforagency=$Objcustomertravelplan->getAgencyStandardTax($this->intLoggedinUserAgencySysId);
            $taxdetailforagency = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiServiceTax('', "H", 8);
            $this->_helper->viewRenderer->setNoRender(true);
            $data = $this->getRequest()->getParam('data');
            $this->view->data = $data;
            //$this->view->Tax = (trim($taxdetailforagency['ServiceTaxPercentage'])>0)?trim(floatval($taxdetailforagency['ServiceTaxPercentage'])):0;
            $this->view->type = 'hotelSendEmailForm';
            $this->render('ajaxHtml');
        }
    }

    public function hotelPreviewFormAction()
    {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isPost()) {
            $this->_helper->viewRenderer->setNoRender(true);
            $data = $this->getRequest()->getParam('data');

            $rateType = $this->getRequest()->getParam('rateType');
            $CustomFinalPrice = $this->getRequest()->getParam('CustomFinalPrice');

            //echo "<pre>";print_r($CustomFinalPrice);exit;



            $customerId = $this->getRequest()->getParam('customerId');
            $noOfAdults = $this->getRequest()->getParam('noOfAdults');
            $noOfChilds = $this->getRequest()->getParam('noOfChilds');
            $finalPrice = $this->getRequest()->getParam('finalPrice');
            $netPrice = $this->getRequest()->getParam('netPrice');

            $AgencyMarkUp = $this->getRequest()->getParam('AgencyMarkUp');
            $GTXmarkUp = $this->getRequest()->getParam('GTXmarkUp');
            $markUp = $this->getRequest()->getParam('markUp');
            $TotalTaxes = $this->getRequest()->getParam('TotalTaxes');
            $leadId = $this->getRequest()->getParam('leadId');
            $getCustomerDetail = '';
            $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
            if (isset($customerId) && !empty($customerId)) {
                $customerId = base64_decode($customerId);
                $getCustomerDetail = $this->_crmcustomerObj->GetCustomerById($customerId);
            }
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $Objcustomertravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $taxdetailforagency = $Objcustomertravelplan->getAgencyStandardTax($this->intLoggedinUserAgencySysId);

            //$userip = new Zend_Session_Namespace('userip1');
            //echo "test==>".$userip->userip1;
            //die;
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($sessionLogin_user->intLoggedinUserAgencySysId);
            // $this->view->Tax = (trim($taxdetailforagency['Tax'])>0)?trim($taxdetailforagency['Tax']):0;
            $getAgentDetail = array('AgentName' => $sessionLogin_user->FirstName . " " . $sessionLogin_user->LastName, 'AgentContact' => $sessionLogin_user->contactnum);


            $this->view->rateType = $rateType;
            $this->view->CustomFinalPrice = $CustomFinalPrice;


            $this->view->AgencyMarkUp = $AgencyMarkUp;
            $this->view->GTXmarkUp = $GTXmarkUp;
            $this->view->TotalTaxes = $TotalTaxes;
            $this->view->finalPrice = $finalPrice;
            $this->view->netPrice = $netPrice;
            $this->view->markUp = $markUp;
            $this->view->noOfAdults = $noOfAdults;
            $this->view->leadId = $leadId;
            $this->view->noOfChilds = $noOfChilds;
            $this->view->customerDetails = $getCustomerDetail;
            $this->view->agentDetails = $getAgentDetail;
            $this->view->agencyDetails = $getAgencyDetail;
            $this->view->data = $data;
            $this->view->type = 'hotelPreviewForm';
            $this->render('ajaxHtml');
        }
    }

    public function getValFormHelperAction()
    {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isPost()) {

            $this->_helper->viewRenderer->setNoRender(true);

            $CostCurrency = $this->getRequest()->getParam('costCur');
            $markUpType = $this->getRequest()->getParam('markup');
            $DOccupMarkUp = $this->getRequest()->getParam('dOccupMarkUp');
            $DOccupCost = $this->getRequest()->getParam('DOccupCost');

            echo Zend_Controller_Action_HelperBroker::getStaticHelper('CurrencyConversion')->InvToCurrency($CostCurrency, $markUpType, $DOccupMarkUp, $DOccupCost);
        }
    }
    public function getAccomodationRoomDetailAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $objHotel = new Travel_Model_TblBuyHotel();
        $markup = $objHotel->getAgencyMarkup();

        try {
            if ($this->_request->isXmlHttpRequest()) {
                $AccomSysId = $this->getRequest()->getParam('id');
            }
            $objAccomo = new Travel_Model_TblBuyHotel();
            $objAccImg = new Travel_Model_TblAccomoImg();
            $objRomms = new Travel_Model_TblAccomoRooms();


            $accomoTitle = $objAccomo->getAccomodation($AccomSysId);
            $accImg = $objAccImg->getAccomoImage($AccomSysId);
            $accRooms = $objRomms->getRoomResult($AccomSysId);
            $accomoDetail = $objAccomo->getAccomodationbriefWherID($AccomSysId);
            $vaTit = array();
            foreach ($accRooms as $valRTitle) {

                $vaTit[$valRTitle['RoomTitle']][] = array('title' => trim($valRTitle['Title']), 'cost' => trim($valRTitle['DOccupCost']), 'DOccupMarkUp' => trim($markup[0]['SOccupMarkUp']), 'MarkUpType' => trim($markup[0]['SOccupMarkUp']), 'AminitiesMask' => trim($valRTitle['AminitiesMask']));
            }

            $accomoMap = $objRomms->getAccomoMap($AccomSysId);
            foreach ($accomoMap as $map) {
                $hotel = 'Hotel ' . $map['Title'] . ' ' . trim($map['Address']);
                $mapHotel = str_replace(" ", "+", $hotel);
                $mapRes = '<iframe src="http://maps.google.com/maps?q=' . $mapHotel . '&loc:' . trim($map['GeoLat']) . '+' . trim($map['GeoLong']) . '&z=9&output=embed" width="600" height="450"></iframe>';
                $mapHotelRes = str_replace("++", "+", $mapRes);
                $mapHotelRs = str_replace(",+,+", "+", $mapHotelRes);
            }
            $res = array('accomoDetail' => $accomoDetail, 'accImg' => $accImg, 'accomoTitle' => $accomoTitle, 'accRooms' => $accRooms, 'mapHotelRs' => $mapHotelRs, 'vaTit' => $vaTit);

            $_SESSION['ROOM_DETAIL_HTL_DETAIL'] = $res;

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





    public function searchResultInventoryAction() {}
    public function searchResultApiAction() {}
    public function starRating($starCount = NULL)
    {
        $stars = floatval($starCount);
        $result = '';
        for ($x = 1; $x <= $stars; $x++) {
            $result .= '<span class="fa fa-star text-danger"></span>';
        }
        if (strpos($stars, '.')) {
            $result .= '<span class="fa fa-star-half-full text-danger"></span>';
            $x++;
        }
        while ($x <= 5) {
            $result .= '<span class="fa fa-star-o text-danger"></span>';
            $x++;
        }
        return $result;
    }

    public function getPriceMarkupAction()
    {
        $this->_helper->layout->disableLayout();
        //try{
        if ($this->_request->isXmlHttpRequest()) {

            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $intNoOfNights = $sessionhotelDirectSearchData->params['hotelTotalNights'];
            $intNoOfRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];
            $strCountryCode = $sessionhotelDirectSearchData->params['countryCode'];

            $minpric = $this->getRequest()->getParam('minpric');
            $netPublichPrice = $minpric * $intNoOfRooms;
            $arrPriceAndMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($netPublichPrice, "0", $intNoOfNights, $intNoOfRooms, $strCountryCode);
            //echo "<pre>";print_r($arrPriceAndMarkUps);echo "</pre>";
            if (!empty($arrPriceAndMarkUps)) {
                $intBasePrice = $arrPriceAndMarkUps['intBasePrice'];
                $intSTaxOnBasePrice = $arrPriceAndMarkUps['intSTaxOnBasePrice'];
                $intPriceWithMarkUpsAndSTax = $arrPriceAndMarkUps['intPriceWithMarkUpsAndSTax'];
                $intGTXMarkUp = $arrPriceAndMarkUps['intGTXMarkUp'];
                $intSTaxOnGTXMarkUp = $arrPriceAndMarkUps['intSTaxOnGTXMarkUp'];
                $intGTXMarkUpWithSTax = $arrPriceAndMarkUps['intGTXMarkUpWithSTax'];
                $intAgencyMarkUp = $arrPriceAndMarkUps['intAgencyMarkUp'];
                $intSTaxOnAgencyMarkUp = $arrPriceAndMarkUps['intSTaxOnAgencyMarkUp'];
                $intAgencyMarkUpWithSTax = $arrPriceAndMarkUps['intAgencyMarkUpWithSTax'];
            } else {
                $intPriceWithMarkUpsAndSTax = 0;
                $intAgencyMarkUp = 0;
            }

            if (!empty($intPriceWithMarkUpsAndSTax)) {
                echo $intPriceWithMarkUpsAndSTax . "###" . $intAgencyMarkUp;
            } else {
                echo $intBasePrice . "###" . $intAgencyMarkUp;
            }

            exit;
        }
    }





    /* Added by Pardeep Panchal Starts*/

    public function saveSearchQueryAction()
    {

        $this->_helper->layout->disableLayout();
        $front = Zend_Controller_Front::getInstance();
        $front->setParam('noViewRenderer', true);

        if ($this->getRequest()->isPost()) {
            $searchType = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('searchType')));
            $leadRemark = $this->_HtmlPurifier->filter($this->getRequest()->getPost('leadRemark'));
            $searchData = array();
            $memberdata = array();
            $hotelTotalRooms = $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectRoom'));
            $f = 1;
            for ($i = 0; $i < $hotelTotalRooms; $i++) {
                $childsAge = '';
                $childsAgeComma = '';
                $AdultPax = $this->_HtmlPurifier->filter($this->getRequest()->getPost('noOfAdults' . $f));
                $ChildPax = $this->_HtmlPurifier->filter($this->getRequest()->getPost('select-noOfChild' . $f));
                if ($ChildPax > 0) {
                    for ($v = 1; $v <= $ChildPax; $v++) {
                        $childsAge[] = $this->_HtmlPurifier->filter($this->getRequest()->getPost('select-childAge_' . $f . '_' . $v));
                    }
                }

                $childsAgeComma = ($childsAge != '') ? implode(',', $childsAge) : '';


                $memberdata[] = array(
                    'AdultPax' => $AdultPax,
                    'ChildPax' => $ChildPax,
                    'ChildsAge' => $childsAgeComma
                );
                $f++;
            }
            //print_r($memberdata);

            $customerId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('customerId')));
            if (null != $customerId && !empty($customerId) && $searchType == 'CRMHOTELSEARCH') {
                $getCustomerDetail = $this->_crmcustomerObj->GetCustomerWithDetails($customerId);
            }
            $createDate = date('Y-m-d H:i:s');

            $customerEmailId = isset($getCustomerDetail['EmailId']) ? $getCustomerDetail['EmailId'] : '';
            //print_r($getCustomerDetail);die;
            $totalMemberCount = Zend_Controller_Action_HelperBroker::getStaticHelper('ArrayCalculation')->calculateArrayValues($memberdata);
            $searchData = array(
                'hotelCityTitle' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('Hotel_name_city')),
                'hotelFromDateSession' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('chekInDate')),
                'hotelToDateSession' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('chekOutDate')),
                'hotelTotalNights' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('nights')),
                'selectNationality' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectNationality')),
                'countryCode' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('countryCode')),
                'searchType' => $searchType,
                'leadRemark' => $leadRemark,
                'customername' => isset($getCustomerDetail['FullName']) ? $getCustomerDetail['FullName'] : '',
                'emailID' => $customerEmailId,
                'searchType' => $searchType,
                'searchType' => $searchType,
                'customerId' => $customerId,
                'TPSysId' => $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('editLeadId'))),
                'TPIntSysId' => $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('editTravelItenaryId'))),
                'hotelTotalRooms' => $hotelTotalRooms,
                'hotelStarRating' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectStarRating')),
                'hotelXrefCityId' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('hidden_selected_hotel_cityid')),
                'hidden_selected_hotel_id' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('hidden_selected_hotel_id')),
                'totalMemberCount' => $totalMemberCount,
                'memberDetails' => $memberdata
            );
            //print_r($searchData);die;
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $sessionhotelDirectSearchData->params = $searchData;
            if (!empty($sessionhotelDirectSearchData->params)) {
                //print_r($sessionhotelDirectSearchData->params);die;
                $response = array('success' => true);
                echo json_encode($response);
                exit;
            } else {
                $response = array('success' => false);
                echo json_encode($response);
                exit;
            }
        }
    }




    public function searchResultsAction()
    {

        $sessionHotelRecordInfo = new Zend_Session_Namespace('sessionHotelRecordInfo');
        //        error_reporting(E_ALL);
        $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
        // echo "<pre>"; print_r($sessionhotelDirectSearchData->params);die;
        //assign new value
        if (null != $this->getRequest()->getPost('selectRoom')) {
            $searchData = array();
            $memberdata = array();
            $hotelTotalRooms = $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectRoom'));
            $searchType = $this->_request->getParam('searchType') ? base64_decode($this->_request->getParam('searchType')) : '0';
            $customerId = $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('customerId')));
            $leadRemark = $this->_HtmlPurifier->filter($this->getRequest()->getPost('leadRemark'));
            if (null != $customerId && !empty($customerId) && $searchType == 'CRMHOTELSEARCH') {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $getCustomerDetail = $this->_crmcustomerObj->GetCustomerWithDetails($customerId);
            }
            $createDate = date('Y-m-d H:i:s');
            $customerEmailId = isset($getCustomerDetail['EmailId']) ? $getCustomerDetail['EmailId'] : '';

            $f = 1;
            $TotAdultCount = 0;
            $TotChildCount = 0;
            for ($i = 0; $i < $hotelTotalRooms; $i++) {
                $childsAge = '';
                $childsAgeComma = '';
                $AdultPax = $this->_HtmlPurifier->filter($this->getRequest()->getPost('noOfAdults' . $f));
                $ChildPax = $this->_HtmlPurifier->filter($this->getRequest()->getPost('select-noOfChild' . $f));
                $TotAdultCount += (int)$AdultPax;
                $TotChildCount += (int)$ChildPax;
                if ($ChildPax > 0) {
                    for ($v = 1; $v <= $ChildPax; $v++) {
                        $childsAge[] = $this->_HtmlPurifier->filter($this->getRequest()->getPost('select-childAge_' . $f . '_' . $v));
                    }
                }
                $childsAgeComma = ($childsAge != '') ? implode(',', $childsAge) : '';
                $memberdata[] = array(
                    'AdultPax' => $AdultPax,
                    'ChildPax' => $ChildPax,
                    'ChildsAge' => $childsAgeComma
                );
                $f++;
            }

            //echo "hhhh".print_r($getCustomerDetail);die;

            $totalMemberCount = Zend_Controller_Action_HelperBroker::getStaticHelper('ArrayCalculation')->calculateArrayValues($memberdata);
            $searchData = array(
                'hotelCityTitle' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('Hotel_name_city')),
                'hotelFromDateSession' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('chekInDate')),
                'hotelToDateSession' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('chekOutDate')),
                'hotelTotalNights' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('nights')),
                'hotelTotalRooms' => $hotelTotalRooms,
                'selectNationality' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectNationality')),
                'countryCode' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('countryCode')),
                'searchType' => $searchType,
                'customerId' => $customerId,
                'leadRemark' => $leadRemark,
                'customername' => isset($getCustomerDetail['FullName']) ? $getCustomerDetail['FullName'] : '',
                'emailID' => $customerEmailId,
                'TPSysId' => $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('editLeadId'))),
                'TPIntSysId' => $this->_HtmlPurifier->filter(base64_decode($this->getRequest()->getPost('editTravelItenaryId'))),
                'hotelStarRating' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('selectStarRating')),
                'hotelXrefCityId' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('hidden_selected_hotel_cityid')),
                'hidden_selected_hotel_id' => $this->_HtmlPurifier->filter($this->getRequest()->getPost('hidden_selected_hotel_id')),
                'totalMemberCount' => $totalMemberCount,
                'memberDetails' => $memberdata
            );
            //print_r($searchData);die;
            $sessionhotelDirectSearchData->params = $searchData;
        }
        //print_r($sessionhotelDirectSearchData->params);die;
        //#end of assign new value
        $strCheckInDate = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
        $strCheckOutDate = $sessionhotelDirectSearchData->params['hotelToDateSession'];
        $intNoOfNights = $sessionhotelDirectSearchData->params['hotelTotalNights'];
        $strselectNationality = $sessionhotelDirectSearchData->params['selectNationality'];
        $strcountryCode = $sessionhotelDirectSearchData->params['countryCode'];
        $objCountry = new Travel_Model_TblCountry();
        $intCountryId = $objCountry->getCountryIdByCode($strcountryCode);
        $intCountryId = !empty(trim($intCountryId)) ? trim($intCountryId) : '0';
        $intGTXCityId = $this->view->intGTXCityId = $sessionhotelDirectSearchData->params['hotelXrefCityId'];
        $intHotelCityId = $sessionhotelDirectSearchData->params['hidden_selected_hotel_id'];
        $intNoOfRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];
        $intNoOfAdults = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
        $intNoOfChild = (int) $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
        $intTotalPaxCount = $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'] + $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
        $intChildAge = $sessionhotelDirectSearchData->params['totalMemberCount']['ChildsAge'];
        if (isset($sessionhotelDirectSearchData->params['RoomMemInfoJson'])) {
            $strRoomMemInfoJson = $sessionhotelDirectSearchData->params['RoomMemInfoJson'];
        } else {
            $sessionhotelDirectSearchData->params['RoomMemInfoJson'] = '';
        }
        //$strRoomMemInfoJson = $sessionhotelDirectSearchData->params['RoomMemInfoJson'] ? $sessionhotelDirectSearchData->params['RoomMemInfoJson'] : '';
        $memberDetails = $sessionhotelDirectSearchData->params['memberDetails'];
        $intMaxRating = $sessionhotelDirectSearchData->params['hotelStarRating'];
        $intMinRating = $sessionhotelDirectSearchData->params['hotelStarRating'];
        $tokenId = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();




        ############### Code Added By Shobhit ###############
        $cityID = $this->_request->getParam('cityID') ? $this->_request->getParam('cityID') : '0';
        $srchtype = $this->_request->getParam('srchtype') ? $this->_request->getParam('srchtype') : '0';
        $pkgcatype = $this->_request->getParam('pkgcattype') ? $this->_request->getParam('pkgcattype') : '0';
        $tpintsysID = $this->_request->getParam('tpintsysID') ? $this->_request->getParam('tpintsysID') : '';
        $cityname = $this->_request->getParam('cityname') ? $this->_request->getParam('cityname') : '';
        $nights = $this->_request->getParam('nights') ? $this->_request->getParam('nights') : '';
        $day = $this->_request->getParam('day') ? $this->_request->getParam('day') : '';
        $packageId = $this->_request->getParam('packageId') ? $this->_request->getParam('packageId') : '0';
        $selectRoom = $this->_request->getParam('selectRoom') ? $this->_request->getParam('selectRoom') : '0';
        $selectNationality = $this->_request->getParam('selectNationality') ? $this->_request->getParam('selectNationality') : '';
        $paxcount = $this->_request->getParam('paxcount') ? $this->_request->getParam('paxcount') : '0';
        $chekInDate = $this->_request->getParam('chekInDate') ? $this->_request->getParam('chekInDate') : '01/01/1970';
        $chekOutDate = $this->_request->getParam('chekOutDate') ? $this->_request->getParam('chekOutDate') : '01/01/1970';
        $cdate = DateTime::createFromFormat('d/m/Y', $chekInDate);
        $checkinDateFormat = strtotime($cdate->format('Y-m-d')); // => 2013-12-24
        $codate = DateTime::createFromFormat('d/m/Y', $chekOutDate);
        $checkoutdate = strtotime($codate->format('Y-m-d'));
        $days_between = ceil(abs($checkoutdate - $checkinDateFormat) / 86400);
        $adults = array();
        for ($i = 1; $i <= $selectRoom; $i++) {
            $adults['adult'][$i] = $this->_request->getParam('noOfAdults' . $i);
            $adults['child'][$i] = $this->_request->getParam('select-noOfChild' . $i);
        }
        $memberinfo = json_encode($adults);

        $roomaaray = array();
        for ($i = 1; $i <= $selectRoom; $i++) {
            $roomaaray[$i]['adult'] = $this->_request->getParam('noOfAdults' . $i);
            $roomaaray[$i]['child']['childcount'] = $this->_request->getParam('select-noOfChild' . $i);

            $childcount = $this->_request->getParam('select-noOfChild' . $i);
            $childnum = '';
            for ($j = 1; $j <= $childcount; $j++) {
                $childnum = $childnum . ',' . $this->_request->getParam('select-childAge_' . $i . '_' . $j);
                $roomaaray[$i]['child']['childage'] = trim($childnum, ",");
            }

            //$roomaaray[$i]['child'] = $this->_request->getParam('select-noOfChild'.$i);
        }
        $roomaarayinfo = json_encode($roomaaray);
        $sessionhotelDirectSearchData->params['RoomMemInfoJson'] = $roomaarayinfo;
        $strRoomMemInfoJson = $sessionhotelDirectSearchData->params['RoomMemInfoJson'];

        //die;
        ############### Code End By Shobhit ###############

        if (!$this->_request->isXmlHttpRequest()) {


            /* For Displaying Temprary Result set of hotels */
            $objTempHotel = new Travel_Model_TblBuyHotel();
            if (!empty($intGTXCityId)) {
                $objTempHotel->strCondition .= " CitySysId = '" . $intGTXCityId . "'";
            }
            $arrTempHotelList = $objTempHotel->getTempHotelSearchResultList();
            $this->view->arrTempHotelList = $arrTempHotelList;
            /* For Displaying Temprary Result set of hotels */


            $sessionHotelRecordInfo->params['intSessionHotelRecordCount'] = 0;  // Set Total Records to '0' on page Refresh...

            //            $objPropertyType = new Travel_Model_TblPropertyType();
            //            $arrPropertyType = $objPropertyType->getPropertyType();
            //            $this->view->arrPropertyType = $arrPropertyType;


            $objAmenities = new Travel_Model_TblAmenities();
            $objAmenities->strCondition = " AminityId IN ( 1,2,3,4,5,8,10,12 )";
            $arrAminitiesList = $objAmenities->getAminitiesList();
            $this->view->arrAminitiesList = $arrAminitiesList;
            // For Filter DropDown Ends....


            $this->view->searchParams = $sessionhotelDirectSearchData->params;

            // For Harpreet Code will remove later...
            $_SESSION['SEARCH'] = $sessionhotelDirectSearchData->params;
            //print_r($_SESSION['SEARCH']);
            $_SESSION['chekInDate'] = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
            $_SESSION['chekOutDate'] = $sessionhotelDirectSearchData->params['hotelToDateSession'];
            $_SESSION['nights'] = $intNoOfNights;
            $_SESSION['noOfAdults'] = $intNoOfAdults;
            $_SESSION['intTotalPaxCount'] = $intTotalPaxCount;
            $_SESSION['noOfRooms'] =  $sessionhotelDirectSearchData->params['hotelTotalRooms'];
            // For Harpreet Code will remove later...

        }


        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();


            $sourcepkg = !empty($this->getRequest()->getPost('sourcepkg')) ? $this->getRequest()->getPost('sourcepkg') : '0';
            $strResultsSource = !empty($this->getRequest()->getPost('strResultsSource')) ? $this->getRequest()->getPost('strResultsSource') : 'BOTH';
            $intPageNumber = !empty($this->getRequest()->getPost('page')) ? $this->getRequest()->getPost('page') : '1';
            $intfilterFlag = trim($this->getRequest()->getPost('filterFlag'));
            $intLimitPerPage = HOTEL_SEARCH_PER_PAGE_LIMIT;
            if (!empty($this->getRequest()->getPost('sourcepkg'))) { // Condition For Shobhit
                $sessionHotelRecordInfo->params['intSessionHotelRecordCount'] = 1;  // Set Total Records to '0' on page Refresh...
                if ($intPageNumber > 1) {
                    $intfilterFlag = 0;
                } else {
                    $intfilterFlag = 1;
                }
            }

            $strfilterByPrice = trim($this->getRequest()->getPost('filterByPrice'));
            $strfilterByHotelName = trim($this->getRequest()->getPost('filterByHotelName'));
            $arrfilterByPrice = array();
            if (!empty($strfilterByPrice)) {
                $arrfilterByPrice = explode(",", $strfilterByPrice);
            }

            $strFilterByRatings = trim($this->getRequest()->getPost('filterByRatings'));
            $arrFilterByRatings = array();
            if (isset($strFilterByRatings) && $strFilterByRatings != "") {
                $arrFilterByRatings = explode(",", $strFilterByRatings);
            }
            //$strFilterByPropertyType = trim($this->getRequest()->getPost('filterByPropertyType'));
            $strFilterByPropertyType = trim($this->getRequest()->getPost('strResultsSource'));
            $arrFilterByPropertyType = array();
            if (!empty($strFilterByPropertyType)) {
                $arrFilterByPropertyType = explode(",", $strFilterByPropertyType);
            }
            $strfilterByAmenities = trim($this->getRequest()->getPost('filterByAmenities'));
            $arrFilterByAmenities = array();
            if (!empty($strfilterByAmenities)) {
                $arrFilterByAmenities = explode(",", $strfilterByAmenities);
            }
            $strOrderBy = trim($this->getRequest()->getPost('orderBy'));
            $strOnRequest = trim($this->getRequest()->getPost('onRequest'));

            $objHotel = new Travel_Model_TblBuyHotel();
            $objHotel->strResultsSource = $strResultsSource;

            $objHotel->strCondition = '';

            if (!empty($intGTXCityId)) {
                $objHotel->strCondition .= " t1.CitySysId = '" . $intGTXCityId . "'";
            }


            //echo "<pre>";print_r($sessionhotelDirectSearchData->params);echo "</pre>";exit;

            if (!empty($arrfilterByPrice)) {
                $objHotel->strCondition .= " AND (  ";
                $intP = 1;
                foreach ($arrfilterByPrice as $priceSagments) {
                    $arrPriceSagments = explode("-", $priceSagments);
                    $intPriceSeg1 = !empty($arrPriceSagments[0]) ? $arrPriceSagments[0] : 0;
                    $intPriceSeg2 = !empty($arrPriceSagments[1]) ? $arrPriceSagments[1] : 0;
                    if (!empty($arrPriceSagments[0]) && !empty($arrPriceSagments[1])) {
                        $objHotel->strCondition .= " ( MinPublishedFare >=  '" . $intPriceSeg1 . "' AND MinPublishedFare <= '" . $intPriceSeg2 . "' )";
                        if (count($arrfilterByPrice) > $intP) {
                            $objHotel->strCondition .= " OR ";
                        }
                        $intP++;
                    }
                }
                $objHotel->strCondition .= " ) ";
            }



            if (!empty($arrFilterByRatings)) {
                $objHotel->strCondition .= " AND (  ";
                $intR = 1;
                foreach ($arrFilterByRatings as $ratingValue) {

                    $objHotel->strCondition .= "  Stars =  '" . $ratingValue . "' ";
                    $objHotel->strCondition .= " OR Stars =  '" . $ratingValue . ".5' ";
                    if (count($arrFilterByRatings) != $intR) {
                        $objHotel->strCondition .= " OR ";
                    }
                    $intR++;
                }
                $objHotel->strCondition .= " ) ";
            } else {
                if ($intMaxRating != '6' && !empty($intMaxRating)) {
                    $objHotel->strCondition .= " AND Stars =  '" . $intMaxRating . "' ";
                }
            }

            //echo $objHotel->strCondition;

            //            if(!empty($arrFilterByPropertyType) > 0){
            //                $objHotel->strCondition .= " AND (  ";
            //                $intPT = 1;
            //                    foreach ($arrFilterByPropertyType as $pTypeValue){
            //                        $objHotel->strCondition .= "  PropertyType =  '".$pTypeValue."' ";
            //                        if(count($arrFilterByPropertyType) != $intPT){
            //                            $objHotel->strCondition .= " OR ";
            //                        }
            //                        $intPT++;
            //                    }
            //                $objHotel->strCondition .= " ) ";
            //            }


            if (!empty($arrFilterByAmenities)) {
                $objHotel->strCondition .= " AND (  ";
                $intPT = 1;
                foreach ($arrFilterByAmenities as $amenitiesValue) {
                    $objHotel->strCondition .= " SUBSTRING(convert(varchar, AccoAminitiesMask, 120)," . ($amenitiesValue + 1) . ",1) =  '1' ";
                    if (count($arrFilterByAmenities) != $intPT) {
                        $objHotel->strCondition .= " OR ";
                    }
                    $intPT++;
                }
                $objHotel->strCondition .= " ) ";
            }
            //echo $objHotel->strCondition; exit;
            if (!empty($strfilterByHotelName)) {
                $objHotel->strCondition .= " AND t1.Title LIKE '%" . $strfilterByHotelName . "%'";
            }

            $arrRoomMemInfoJson = json_decode($strRoomMemInfoJson, true);
            if (!empty($arrRoomMemInfoJson)) {
                $strRoomPaxInfo = '';
                for ($i = 1; $i <= count($arrRoomMemInfoJson); $i++) {
                    $strRoomPaxInfo .= $arrRoomMemInfoJson[$i]['adult'] . "-N,";
                }
                $strRoomPaxInfo = trim($strRoomPaxInfo, ',');
                $objHotel->strRoomPaxInfo =  $strRoomPaxInfo; // For Inventory Rates

            } else {
                $strRoomPaxInfo = "1-N";
                $objHotel->strRoomPaxInfo =  $strRoomPaxInfo;
            }


            if (!empty($strCheckInDate) && !empty($strCheckOutDate)) {
                $objHotel->strCheckInDateTime   = trim($strCheckInDate);
                $objHotel->strCheckOutDateTime  = trim($strCheckOutDate);
            }

            if ($intTotalPaxCount > 0) {
                $objHotel->intTotalPaxCount =  $intTotalPaxCount;
            } else if ($paxcount > 0) {
                $objHotel->intTotalPaxCount =  $paxcount;
            }
            if ($intNoOfRooms > 0) {
                $objHotel->intTotalRoomCount =  $intNoOfRooms;
            } else if ($selectRoom > 0) {
                $objHotel->intTotalRoomCount =  $selectRoom;
            }
            if ($intNoOfNights > 0) {
                $objHotel->intTotalNightCount =  $intNoOfNights;
            } else if ($nights > 0) {
                $objHotel->intTotalNightCount =  $nights;
            }
            if (!empty($strselectNationality)) {
                $objHotel->strNationality = $strselectNationality;
            } else if (!empty($selectNationality)) {
                $objHotel->strNationality =  $selectNationality;
            }



            // Condition used only For Inventory
            if (!empty($strCheckInDate)) {
                $arrCheckInDate = explode("/", $strCheckInDate);
                if (!empty($arrCheckInDate)) {
                    $strCheckInDateNew = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
                }
            }

            if (!empty($strCheckOutDate)) {
                $arrCheckOutDate = explode("/", $strCheckOutDate);
                if (!empty($arrCheckOutDate)) {
                    $strCheckOutDateNew = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];
                }
            }
            if (!empty($strCheckInDateNew) && !empty($strCheckOutDateNew)) {
                $objHotel->strCheckInDate   = " $strCheckInDateNew ";
                $objHotel->strCheckOutDate  = " $strCheckOutDateNew ";
            }


            if (!empty($strOnRequest)) {
                $objHotel->onRequest = " $strOrderBy ";
            } else {
                $objHotel->orderBy = " $strOrderBy ";
            }



            //exit;
            // Condition used only For Inventory Ends...

            $objHotel->intLimitPerPage = $intLimitPerPage;
            $objHotel->intPageNumber = $intPageNumber;
            $arrSearchedHotelList = $objHotel->getHotelSearchResultList();
            if ($sessionHotelRecordInfo->params['intSessionHotelRecordCount'] > 0 || $intfilterFlag == 0) {  // Shows results from DB...
                //                 echo "HI===";exit;
                $this->view->arrSearchedHotelList = $arrSearchedHotelList;

                if ($sourcepkg == '1') {
                    $this->view->cityname = $cityname;
                    $this->view->days = $day;
                    $this->view->cityID = $cityID;
                    $this->view->tpintsysID = $tpintsysID;
                    $this->view->packageId = $packageId;
                    $this->view->selectRoom = $selectRoom;
                    $this->view->memberinfo = $memberinfo;
                    $this->view->daysbetween = $days_between;
                    $this->view->checkinDate = $chekInDate;
                    $this->view->checkOutDate = $chekOutDate;
                    $this->view->roominfo = $roomaarayinfo;
                    $this->view->nights = $nights;
                    $this->render('search-hotel-list-pkg');
                }
                if ($sourcepkg == '2') {

                    $this->view->cityname = $cityname;
                    $this->view->days = $day;
                    $this->view->cityID = $cityID;
                    $this->view->tpintsysID = $tpintsysID;
                    $this->view->packageId = $packageId;
                    $this->view->selectRoom = $selectRoom;
                    $this->view->memberinfo = $memberinfo;
                    $this->view->daysbetween = $days_between;
                    $this->view->checkinDate = $chekInDate;
                    $this->view->checkOutDate = $chekOutDate;
                    $this->view->roominfo = $roomaarayinfo;
                    $this->view->nights = $nights;
                    $this->view->pkgcatype = $pkgcatype;
                    $this->render('search-hotel-list-pkg-byo');
                } else {
                    $this->view->intGTXCityId = $intGTXCityId;
                    $this->view->intNoOfNights = $intNoOfNights;
                    $this->view->intNoOfRooms = $intNoOfRooms;
                    $this->render('search-hotel-list');
                }
                exit;
            } else {  // API Look Up For Hotels.....


                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->searchApiHotelsNew($sessionhotelDirectSearchData->params);
                //                echo "<pre>";print_r($apiResponse);exit;

                $intResponseStatus = $apiResponse['HotelSearchResult']['ResponseStatus'];
                $this->view->intErrorCode  = $intErrorCode = $apiResponse['HotelSearchResult']['ErrorCode'];

                if ($intResponseStatus == 1 && $intErrorCode == 0) {

                    $arrHotelResults = $apiResponse['Hotels'];
                    $CreateDate = date('Y-m-d H:i:s');
                    if (count($arrHotelResults) > 0 && !empty($arrHotelResults)) {


                        //$arrAlreadyExistsHotels = $objHotel->getHotelShortNameByGTXCityId($intGTXCityId);  // Get All Hotels Info On perticular City Id And Check If Hotel Alredy Exists in Our DB B4 inserting...


                        foreach ($arrHotelResults as $resValue) {

                            $strTraceId     = $resValue['TraceId'];
                            $strTokenId     = $resValue['TokenId'];
                            $intAPICityId   = $resValue['APICityId'];
                            $strHotelCode = trim($resValue["HotelCode"]);
                            //if (!in_array($strHotelCode, $arrAlreadyExistsHotels,true)) {
                            $strHotelPictureUrl = $resValue['HotelPicture'];
                            $data = array(
                                'IsAgentSpec' => '0',
                                'ICSourceSysId' => $resValue["ApiSourceSysId"],
                                'ShortName' => trim($resValue["HotelCode"]),
                                'Title' => trim($resValue['HotelName']),
                                'ResultIndex' => trim($resValue['ResultIndex']),
                                'TraceId' => trim($strTraceId),
                                'TokenId' => trim($strTokenId),
                                'AliasAndMeta' => '',
                                'PlaceSysId_XRef' => 0,
                                'Icon' => '',
                                'ThumnailImg' => '',
                                'DetailImg' => trim($resValue['HotelPicture']),
                                'Stars' => !empty($resValue['StarRating']) ? trim($resValue['StarRating']) : '0',
                                'Rating' => !empty($resValue['AgencyRating']) ? trim($resValue['AgencyRating']) : '0',
                                'Popularity' => '0',
                                'AwardRecognizations' => !empty($resValue['AwardRecognizations']) ? 'TripAdvisor' : '',
                                'AwardURL' => !empty($resValue['AwardURL']) ? trim($resValue['AwardURL']) : '',
                                'PropertyType' => '1',
                                'EconomyType' => '1',
                                'AccoAminitiesMask' => trim($resValue['AccoAminitiesMask']),
                                'MaxPaxCount' => $intTotalPaxCount,
                                'RoomCounts' => $intNoOfRooms,
                                'NightCount' => $intNoOfNights,
                                'Nationality' => $strselectNationality,
                                'Brief' => trim($resValue['HotelDescription']),
                                'CheckinTime' => trim($strCheckInDate),
                                'CheckOutTime' => trim($strCheckOutDate),
                                'CurrencyType' => 1,
                                'MinPublishedFare' => ($resValue['PublishedPrice']),
                                "MinCommissionEarned" => ($resValue['AgentCommission']),
                                'IsDayLightApp' => '0',
                                'GeoLat' => trim($resValue['Latitude']),
                                'GeoLong' => trim($resValue['Longitude']),
                                'Address' => ucfirst($resValue['HotelAddress']),
                                'Location' => '',
                                'PinCode' => '',
                                'APICityId' => $intAPICityId,
                                'CitySysId' => $intGTXCityId,
                                'ZoneSysId' => '0',
                                'ZoneType' => '0',
                                'StateSysId' => '0',
                                'ContSysId' => $intCountryId,
                                'PrimaryContact' => '0',
                                'SecondaryContact' => '0',
                                'OtherContacts' => '0',
                                'ApproveBy' => '1',
                                'CreateDate' => $CreateDate,
                                'UpdateDate' => $CreateDate,
                                'ApproveDate' => $CreateDate,
                                'IsApproved' => '1',
                                'IsActive' => '1',
                                'IsExpired' => '0',
                                'IsMarkForDel' => '0'
                            );


                            //                                echo "<pre>";
                            //                                print_r($data);
                            //                                exit;

                            $intLastInsertedId = $objHotel->insertApiHotels($data);
                            //$objHotel->deleteApiHotelsImages($intLastInsertedId);
                            if (!empty($intLastInsertedId)) {
                                $imgData = array(
                                    'AccomSysId' => $intLastInsertedId,
                                    'Seq' => 1,
                                    'ImgType' => 2,
                                    'HotelCode' => trim($resValue["HotelCode"]),
                                    'CitySysId' => $intGTXCityId,
                                    'ImageType' => 'FullImage',
                                    'ImageURL' => $strHotelPictureUrl,
                                    'UpdateDate' => $CreateDate,
                                    'CreateDate' => $CreateDate,
                                    'IsActive' => 1,
                                    'IsMarkForDel' => 0,
                                );
                                $objHotel->insertApiHotelsImages($imgData);
                            }
                            /*} else { // update Hotel Info....
                                $dataUpdate = array(
                                        'ResultIndex' => trim($resValue['ResultIndex']),
                                        'TraceId' => trim($strTraceId),
                                        'TokenId' => trim($tokenId),
                                        'Stars' => !empty($resValue['StarRating']) ? trim($resValue['StarRating']) : '0',
//                                        'Rating' => !empty($resValue['AgencyRating']) ? trim($resValue['AgencyRating']) : '0',
//                                        'AwardURL' => !empty($resValue['AwardURL']) ? trim($resValue['AwardURL']) : '',
//                                        'GeoLat' => trim($resValue['Latitude']),
//                                        'GeoLong' => trim($resValue['Longitude']),
//                                        'Address' => ucfirst($resValue['HotelAddress']),
                                        'ContSysId' => $intCountryId,
//                                        'CheckinTime' => $strCheckInDate,
//                                        'CheckOutTime' => $strCheckOutDate,
                                        'CurrencyType' => 1,
                                        'MaxPaxCount' => $intTotalPaxCount,
                                        'RoomCounts' => $intNoOfRooms,
                                        'NightCount' => $intNoOfNights,
                                        'Nationality' => $strselectNationality,
                                        'MinPublishedFare' => ($resValue['PublishedPrice']),
                                        "MinCommissionEarned" => ($resValue['AgentCommission']),
//                                        'UpdateDate' => $CreateDate,
                                        'IsExpired' => '0'
                                    );
//                                echo $resValue["HotelCode"];
//                                echo "<pre>";print_r($dataUpdate);exit;
                                $Where['ShortName = ?'] = $resValue["HotelCode"];
                                $objHotel->updateApiHotelsInfo($dataUpdate,$Where);

                            }*/
                        }
                    }


                    if ($intPageNumber == 1) {
                        // For Total Records count...
                        $objHotel->strSelectedView = 'Count';
                        $intSearchedHotelCount = $objHotel->getHotelSearchResultList();
                        $this->view->intSearchedHotelCount = $intSearchedHotelCount;
                    }

                    $objHotel->strSelectedView = '';
                    // fetch Hotel results after Insert / Update Operation..
                    $arrSearchedHotelList = $objHotel->getHotelSearchResultList();
                    //echo "<pre>";print_r($arrSearchedHotelList);exit;
                    // For Pagination....
                    $page = $this->_getParam('page', $intPageNumber);
                    $arrSearchedHotelList = Zend_Paginator::factory($arrSearchedHotelList);
                    $arrSearchedHotelList->setItemCountPerPage($intLimitPerPage);
                    $arrSearchedHotelList->setCurrentPageNumber($page);
                    // For Pagination....

                    $this->view->arrSearchedHotelList = $arrSearchedHotelList;
                    if ($sourcepkg == '1') {
                        $this->view->cityname = $cityname;
                        $this->view->days = $day;
                        $this->view->nights = $nights;
                        $this->view->cityID = $cityID;
                        $this->view->tpintsysID = $tpintsysID;
                        $this->view->packageId = $packageId;
                        $this->view->selectRoom = $selectRoom;
                        $this->view->memberinfo = $memberinfo;
                        $this->view->daysbetween = $days_between;
                        $this->view->checkinDate = $chekInDate;
                        $this->view->checkOutDate = $chekOutDate;
                        $this->view->roominfo = $roomaarayinfo;
                        $this->render('search-hotel-list-pkg');
                    }
                    if ($sourcepkg == '2') {
                        $this->view->cityname = $cityname;
                        $this->view->days = $day;
                        $this->view->nights = $nights;
                        $this->view->cityID = $cityID;
                        $this->view->tpintsysID = $tpintsysID;
                        $this->view->packageId = $packageId;
                        $this->view->selectRoom = $selectRoom;
                        $this->view->memberinfo = $memberinfo;
                        $this->view->daysbetween = $days_between;
                        $this->view->checkinDate = $chekInDate;
                        $this->view->checkOutDate = $chekOutDate;
                        $this->view->roominfo = $roomaarayinfo;
                        $this->view->pkgcatype = $pkgcatype;
                        $this->render('search-hotel-list-pkg-byo');
                    } else {
                        $this->view->intGTXCityId = $intGTXCityId;
                        $this->view->intNoOfNights = $intNoOfNights;
                        $this->view->intNoOfRooms = $intNoOfRooms;
                        $this->render('search-hotel-list');
                    }
                    exit;
                } else {

                    // Condition in any case if Only Inventory Hotel Founds...
                    $objHotel->strSelectedView = '';
                    // fetch Hotel results after Insert / Update Operation..
                    $arrSearchedHotelList = $objHotel->getHotelSearchResultList();
                    if (!empty($arrSearchedHotelList)) {
                        // For Pagination....
                        $this->view->intSearchedHotelCount['total'] = count($arrSearchedHotelList);
                        $page = $this->_getParam('page', $intPageNumber);
                        $arrSearchedHotelList = Zend_Paginator::factory($arrSearchedHotelList);
                        $arrSearchedHotelList->setItemCountPerPage($intLimitPerPage);
                        $arrSearchedHotelList->setCurrentPageNumber($page);
                        // For Pagination....
                        $this->view->arrSearchedHotelList = $arrSearchedHotelList;

                        if ($sourcepkg == '1') {
                            $this->view->cityname = $cityname;
                            $this->view->days = $day;
                            $this->view->cityID = $cityID;
                            $this->view->nights = $nights;
                            $this->view->tpintsysID = $tpintsysID;
                            $this->view->packageId = $packageId;
                            $this->view->selectRoom = $selectRoom;
                            $this->view->memberinfo = $memberinfo;
                            $this->view->daysbetween = $days_between;
                            $this->view->checkinDate = $chekInDate;
                            $this->view->checkOutDate = $chekOutDate;
                            $this->view->roominfo = $roomaarayinfo;
                            $this->render('search-hotel-list-pkg');
                        }
                        if ($sourcepkg == '2') {
                            $this->view->cityname = $cityname;
                            $this->view->days = $day;
                            $this->view->nights = $nights;
                            $this->view->cityID = $cityID;
                            $this->view->tpintsysID = $tpintsysID;
                            $this->view->packageId = $packageId;
                            $this->view->selectRoom = $selectRoom;
                            $this->view->memberinfo = $memberinfo;
                            $this->view->daysbetween = $days_between;
                            $this->view->checkinDate = $chekInDate;
                            $this->view->checkOutDate = $chekOutDate;
                            $this->view->roominfo = $roomaarayinfo;
                            $this->view->pkgcatype = $pkgcatype;
                            $this->render('search-hotel-list-pkg-byo');
                        } else {
                            $this->view->intGTXCityId = $intGTXCityId;
                            $this->render('search-hotel-list');
                        }

                        // Condition in any case if Only Inventory Hotel Founds...

                    } else {
                        $this->view->intErrorCode = 0;
                        //                        $this->view->strResponseStatus = $apiResponse['HotelSearchResult']['ResponseStatus'];
                        //                        $this->view->intErrorCode = $apiResponse['HotelSearchResult']['Error']['ErrorCode'];
                        //                        $this->view->strErrorMessage = $apiResponse['HotelSearchResult']['Error']['ErrorMessage'];
                        //                        $strTraceId = $apiResponse['HotelSearchResult']['TraceId'];
                        if ($sourcepkg == '1') {
                            $this->view->cityname = $cityname;
                            $this->view->days = $day;
                            $this->view->nights = $nights;
                            $this->view->cityID = $cityID;
                            $this->view->tpintsysID = $tpintsysID;
                            $this->view->packageId = $packageId;
                            $this->view->selectRoom = $selectRoom;
                            $this->view->memberinfo = $memberinfo;
                            $this->view->daysbetween = $days_between;
                            $this->view->checkinDate = $chekInDate;
                            $this->view->checkOutDate = $chekOutDate;
                            $this->view->roominfo = $roomaarayinfo;
                            $this->render('search-hotel-list-pkg');
                        }
                        if ($sourcepkg == '2') {
                            $this->view->cityname = $cityname;
                            $this->view->days = $day;
                            $this->view->nights = $nights;
                            $this->view->cityID = $cityID;
                            $this->view->tpintsysID = $tpintsysID;
                            $this->view->packageId = $packageId;
                            $this->view->selectRoom = $selectRoom;
                            $this->view->memberinfo = $memberinfo;
                            $this->view->daysbetween = $days_between;
                            $this->view->checkinDate = $chekInDate;
                            $this->view->checkOutDate = $chekOutDate;
                            $this->view->roominfo = $roomaarayinfo;
                            $this->view->pkgcatype = $pkgcatype;
                            $this->render('search-hotel-list-pkg-byo');
                        } else {
                            $this->view->intGTXCityId = $intGTXCityId;
                            $this->render('search-hotel-list');
                        }
                    }
                    exit;
                }
            }

            exit;
        }
    }



    public function bookingConfirmationAction()
    {

        $this->view->intCustomerSysId = $intCustomerSysId = base64_decode(trim($this->getRequest()->getParam('cid')));
        $this->view->intTpSysId = $intTpSysId = base64_decode(trim($this->getRequest()->getParam('tid')));


        $travelplanObj = new Travel_Model_CRM_CustomerTravelPlan();
        $travelPlanDetailSplReq = $travelplanObj->GetPublicPageLeadList($intCustomerSysId, $this->intLoggedinUserAgencySysId, $intTpSysId);
        $this->view->travelPlanDetailSplReq = $travelPlanDetailSplReq;

        if (!empty($intCustomerSysId)) {
            // for CRM Member Details
            $objBuyHotel = new Travel_Model_TblBuyHotel();
            $getCustomerDetail = $objBuyHotel->GetAgencyCustomerDetailsForBooking($intCustomerSysId, $intTpSysId);
            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $travelPlanDetail = $this->_crmcusttravelplan->GetTravelPlanCustomerDetails($intTpSysId);
            $uid = $travelPlanDetail[0]['CustomerSysId'] . ':' . $travelPlanDetail[0]['TPSysId'] . ':' . $travelPlanDetail[0]['MasterTPSysId'];
            $uid = $this->getEnc($uid);
            $intMemberSysId = @$getCustomerDetail['MemberSysId'];
            if (!empty($intMemberSysId)) {
                $this->view->intMemberSysId = $intMemberSysId;
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            } else {
                $this->view->CustomerMobile = $getCustomerDetail['Contacts'];
                $this->view->CustomerEmail = $getCustomerDetail['EmailId'];
                $this->view->CustomerTitle = $getCustomerDetail['Title'];
                $this->view->CustomerRelation = $getCustomerDetail['Relation'];
                $this->view->CustomerFirstName = $getCustomerDetail['FirstName'];
                $this->view->CustomerLastName = $getCustomerDetail['LastName'];
            }
        }
        $this->view->uid = $uid;
        $this->view->travelPlanDetail = $travelPlanDetail;


        $arrHotelBookingDetails = $objBuyHotel->viewHotelBookingDetails($intTpSysId);
        $strXRefBookingId = $arrHotelBookingDetails[0]['XRefBookingId'];
        if (!empty($strXRefBookingId)) {
            $arrXRefBookingId = explode("/", $strXRefBookingId);
            $this->view->strBookingId = $strBookingId = $arrXRefBookingId[0];
            $this->view->strBookingRefId = $strBookingRefId = $arrXRefBookingId[1];
        }

        $objBuyHotel = new Travel_Model_TblBuyHotel();
        $arrHotelInfo = $objBuyHotel->getHotelInfoById($_SESSION['SELECTED_HTL_ID']);
        $strTokenId = $arrHotelInfo['TokenId'];
        $dataUpdate = array('IsExpired' => '1');
        $Where['TokenId = ?'] = $strTokenId;
        $objBuyHotel->updateTraceIdExpired($dataUpdate, $Where);
    }





    public function getApiHotelRoomInfoAction()
    {

        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {

            $_SESSION['SELECTED_HTL_ID'] = $intAccomSysId = trim($this->getRequest()->getParam('intAccomSysId'));

            $strHotelCode = trim($this->getRequest()->getParam('strShortName'));

            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $sessionhotelDirectSearchData->params['strHotelCode'] = $strHotelCode;


            $this->view->hotelCityTitle = $sessionhotelDirectSearchData->params['hotelCityTitle'];

            $sessionhotelDirectSearchData->params['apiSourceSysId'] = $this->getRequest()->getParam('intICSourceSysId');
            $sessionhotelDirectSearchData->params['strTraceId']     = $strTraceId = $this->getRequest()->getParam('strTraceId');
            $sessionhotelDirectSearchData->params['strResultIndex'] = $strResultIndex = $this->getRequest()->getParam('strResultIndex');
            $sessionhotelDirectSearchData->params['strHotelCode']   = $strHotelCode = $this->getRequest()->getParam('strShortName');

            //echo "<pre>";print_r($sessionhotelDirectSearchData->params);exit;

            $objHotel = new Travel_Model_TblBuyHotel();
            // For Hotel Basic Details From DB...
            $arrHotelDetails = $objHotel->getHotelInfoById($intAccomSysId);
            $this->view->arrHotelDetails = $arrHotelDetails;
            // For Hotel Basic Details From DB...

            $arrHotelAminity = $objHotel->getHotelMappedAmenities($strHotelCode);
            $this->view->arrhotelAminity = $arrHotelAminity;
            $this->render('api-room-detail-info');
        }
    }



    public function getApiHotelRoomsAction()
    {

        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $apiSourceSysId = $sessionhotelDirectSearchData->params['apiSourceSysId'];
            if (!empty($apiSourceSysId) && $apiSourceSysId == '3') {



                $strTraceId             = $sessionhotelDirectSearchData->params['strTraceId'];
                $strHotelCode           = $sessionhotelDirectSearchData->params['strHotelCode'];
                $strResultIndex         = isset($sessionhotelDirectSearchData->params['strResultIndex']) ? $sessionhotelDirectSearchData->params['strResultIndex'] : '';
                $tokenId  = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->authenticateAPI();


                $objApi = new Travel_Model_ApiIntegration();
                $hotelInfo = $objApi->getHotelInfo($strResultIndex, $strHotelCode, $_SERVER['REMOTE_ADDR'], $tokenId, $strTraceId);
                //echo "<pre>";print_r($hotelInfo);exit;
                $_SESSION['HOTELINFO'] = $hotelInfo;


                if ($hotelInfo['HotelInfoResult']['ResponseStatus'] != '1') {
                    //                        echo "<pre>";print_r($hotelInfo);exit;
                    $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                    $intGTXCityId =  $sessionhotelDirectSearchData->params['hotelXrefCityId'];
                    $objHotel = new Travel_Model_TblBuyHotel();
                    $dataUpdate = array('IsExpired' => '1');
                    $Where['CitySysId = ?'] = $intGTXCityId;
                    $objHotel->updateTraceIdExpired($dataUpdate, $Where);

                    echo "0###No rooms available.";
                    exit;
                }



                $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRoomInfo($sessionhotelDirectSearchData->params);
                $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                $sessionhotelDirectSearchData->params['hotelRoomDetail'] = $arrResponseData;
                $_SESSION['HOTEL_ROOM_DETAIL'] = $arrResponseData;



                $sessionhotelDirectSearchData->params['hotelDetailArr'] = array('hotelInfo' => $hotelInfo, 'hotelRoomD' => $arrResponseData);

                if (!empty($arrResponseData)) {
                    //echo "<pre>";print_r($arrResponseData);echo "</pre>";
                    if ($arrResponseData['GetHotelRoomResult']['ResponseStatus'] == '1') {

                        $this->view->apiSourceSysId = $apiSourceSysId;
                        $this->view->strTraceId = isset($arrResponseData['GetHotelRoomResult']['TraceId']) ? $arrResponseData['GetHotelRoomResult']['TraceId'] : '';
                        $this->view->strErrorMessage = isset($arrResponseData['GetHotelRoomResult']['Error']['ErrorMessage']) ? $arrResponseData['GetHotelRoomResult']['Error']['ErrorMessage'] : '';
                        $this->view->arrResponseData = isset($arrResponseData['GetHotelRoomResult']['HotelRoomsDetails']) ? $arrResponseData['GetHotelRoomResult']['HotelRoomsDetails'] : '';
                    } else {
                        $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                        $intGTXCityId =  $sessionhotelDirectSearchData->params['hotelXrefCityId'];
                        $objHotel = new Travel_Model_TblBuyHotel();
                        $dataUpdate = array('IsExpired' => '1');
                        $Where['CitySysId = ?'] = $intGTXCityId;
                        $objHotel->updateTraceIdExpired($dataUpdate, $Where);

                        $this->view->apiSourceSysId = $apiSourceSysId;
                        $this->view->strTraceId = '';
                        $this->view->strErrorMessage = 'No rooms available.';
                        $this->view->arrResponseData = '';

                        echo "0###No rooms available.";
                        exit;
                    }
                } else {
                    $this->view->apiSourceSysId = $apiSourceSysId;
                    $this->view->strTraceId = '';
                    $this->view->strErrorMessage = 'No rooms available.';
                    $this->view->arrResponseData = '';

                    echo "0###No rooms available.";
                    exit;
                }

                //

            } else if (!empty($apiSourceSysId) && $apiSourceSysId == '4') {
                $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRoomInfo($sessionhotelDirectSearchData->params);
                //echo "<pre>";print_r($arrResponseData);exit;
                if (!empty($arrResponseData)) {
                    $this->view->apiSourceSysId = $apiSourceSysId;
                    $this->view->strTraceId = isset($arrResponseData['search_id']) ? $arrResponseData['search_id'] : '';
                    $this->view->strErrorMessage = !empty($arrResponseData['errors'][0]['messages'][0]) ? $arrResponseData['errors'][0]['messages'][0] : '';
                    $this->view->arrResponseData = !empty($arrResponseData['hotels'][0]['rates']) ? $arrResponseData['hotels'][0]['rates'] : '';
                } else {
                    $this->view->apiSourceSysId = $apiSourceSysId;
                    $this->view->strTraceId = '';
                    $this->view->strErrorMessage = 'No rooms available.';
                    $this->view->arrResponseData = '';
                }
            } else {
                $this->view->strTraceId = '';
                $this->view->strErrorMessage = 'No rooms available.';
                $this->view->arrResponseData = '';
            }

            $this->render('api-rooms');
        }
    }


    public function getApiHotelImagesAction()
    {

        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {

            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $strTraceId = $sessionhotelDirectSearchData->params['strTraceId'];
            $strHotelCode = $sessionhotelDirectSearchData->params['strHotelCode'];
            $apiSourceSysId = $sessionhotelDirectSearchData->params['apiSourceSysId'];



            if ($apiSourceSysId == '3') {

                $objHotel = new Travel_Model_TblBuyHotel();
                $intAccomSysId = $objHotel->getHotelInfoByShortCode($strHotelCode, $strTraceId);

                $arrHotelImages = $objHotel->getAccomdationImagesByAccomSysId($intAccomSysId);
                if (!empty($arrHotelImages)) {
                    foreach ($arrHotelImages as $imgUrl) {
                        echo '<div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 ">
                                <img src="' . $imgUrl['Details'] . '" alt="image" width="180" height="140" style="margin-top:4%">
                            </div>';
                    }
                } else {
                    echo '<div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 ">
                                No image available to display !
                            </div>';
                }
            } else {

                $objHotel = new Travel_Model_TblBuyHotel();
                $intAccomSysId = $objHotel->getHotelInfoByShortCode($strHotelCode, $strTraceId);
                //$intImagesCount = $objHotel->countApiHotelsImages(trim($strHotelCode));
                $intImagesCount = $objHotel->getAccomdationImagesByAccomSysId($intAccomSysId);
                //echo "<pre>";print_r($arrHotelImages);exit;
                if (count($intImagesCount) < 2) {
                    //Get Grn Hotel Images...
                    $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRoomImages($strHotelCode);
                    //echo "<pre>";print_r($arrResponseData);exit;
                    if ($arrResponseData['errors'] == 0) {
                        if (!empty($arrResponseData['images'])) {
                            $CreateDate = date('Y-m-d H:i:s');
                            //$intAccomSysId = $objHotel->getHotelInfoByShortCode($strHotelCode,$strTraceId);
                            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
                            $intGTXCityId = $sessionhotelDirectSearchData->params['hotelXrefCityId'];
                            $Seq = 1;
                            foreach ($arrResponseData['images'] as $imgValue) {
                                $imgPath = GRN_HOTEL_IMAGES_CDN_URL . "/" . $imgValue['path'];

                                $imgData = array(
                                    'AccomSysId' => $intAccomSysId,
                                    'Seq' => $Seq,
                                    'ImgType' => 2,
                                    'HotelCode' => trim($strHotelCode),
                                    'CitySysId' => $intGTXCityId,
                                    'ImageType' => 'FullImage',
                                    'ImageURL' => $imgPath,
                                    'UpdateDate' => $CreateDate,
                                    'CreateDate' => $CreateDate,
                                    'IsActive' => 1,
                                    'IsMarkForDel' => 0,
                                );
                                $objHotel->insertApiHotelsImages($imgData);
                                $Seq++;
                            }
                        }
                    }
                }

                //Get Grn Hotel Images...


                // For Hotel Basic Details From DB...
                $arrHotelImages = $objHotel->getAccomdationImagesByAccomSysId($intAccomSysId);
                //echo "<pre>";print_r($arrHotelImages);exit;
                // For Hotel Basic Details From DB...

                if (!empty($arrHotelImages)) {
                    foreach ($arrHotelImages as $imgUrl) {
                        echo '<div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 ">
                            <img src="' . $imgUrl['Details'] . '" alt="image" width="180" height="140" style="margin-top:4%">
                        </div>';
                    }
                } else {
                    echo '<div class="col-md-3 col-sm-4 col-xs-12 m-col-md-3 ">
                            No image available to display !
                        </div>';
                }
            }
        }
    }



    public function getApiHotelRateInfoAction()
    { // rechecking checking rates

        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {

            $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');
            $sessionHotelSearchParams = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $arrCheckInDate = explode("/", $sessionHotelSearchParams->params['hotelFromDateSession']);
            $arrCheckOutDate = explode("/", $sessionHotelSearchParams->params['hotelToDateSession']);

            $strCheckInDate = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
            $strCheckOutDate = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];


            $intApiSource = trim($this->getRequest()->getParam('apiSource'));
            if ($intApiSource == '4') {
                $strApiSource = "GRN";
            } else {
                $strApiSource = "TBO";
            }
            $strTraceId = trim($this->getRequest()->getParam('strTraceId'));
            $strRoomRateKey = trim($this->getRequest()->getParam('strRoomRateKey'));
            $strRoomGroupCode = trim($this->getRequest()->getParam('strRoomGroupCode'));

            $data = array(
                "apiSource"         => $intApiSource,
                "strTraceId"        => $strTraceId,
                "strRoomRateKey"    => $strRoomRateKey,
                "strRoomGroupCode"  => $strRoomGroupCode,
                "strCheckInDate"  => $strCheckInDate,
                "strCheckOutDate"  => $strCheckOutDate
            );

            $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRateInfo($data);
            //echo "<pre>";print_r($arrResponseData);exit;

            if (!empty($arrResponseData) && empty($arrResponseData['ERROR']['CODE'])) {
                $sessionPreBookingHotelDetails->params =  $arrResponseData;
                $response = array('success' => true, 'msg' => '');
                echo json_encode($response);
                exit;
            } else {
                $response = array('success' => false, 'msg' => 'there might be some technical error');
                echo json_encode($response);
                exit;
            }

            exit;
        }
    }

    public function cancelHotelBookingAction()
    {

        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        if ($this->_request->isXmlHttpRequest()) {

            $sessionPreBookingHotelDetails = new Zend_Session_Namespace('sessionPreBookingHotelDetails');

            $data = array(
                "API_SOURCE_ID"     => $API_SOURCE_ID,
                "BOOKING_REFERENCE_ID" => $BOOKING_REFERENCE,
                "REQUEST_TYPE" => $BOOKING_REFERENCE,
                "CANCELLATION_REMARKS" => $BOOKING_REFERENCE
            );


            $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->cancelHotelBooking($data);


            if (!empty($arrResponseData) && empty($arrResponseData['ERROR']['CODE'])) {
                $sessionPreBookingHotelDetails->params =  $arrResponseData;
                $response = array('success' => true, 'msg' => '');
                echo json_encode($response);
                exit;
            } else {
                $response = array('success' => false, 'msg' => 'there might be some technical error');
                echo json_encode($response);
                exit;
            }

            exit;
        }
    }





    public function guestdetailAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $mobilNo = trim($this->getRequest()->getParam('mobilNo'));
            $EmailId = trim($this->getRequest()->getParam('emailId'));
            $intMemberSysIdRequest = trim($this->getRequest()->getParam('intMemberSysId'));
            if (!empty($mobilNo)) {
                //$objGest = new Travel_Model_Tbltbbcuser();
                //$result = $objGest->getCustomerAndMembersDetails($mobilNo);
                //check customer agency added by Er Amit Kumar Dubey on 2 march 2017 at 4:50 PM
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $IsAgencyCusTExist = $this->_crmcustomerObj->ChkMobileWithResponseUpdate($mobilNo, $this->intLoggedinUserAgencySysId);
                //$IsAgencyCusTExist=$this->_crmcustomerObj->ChkEmailMobileWithResponse('',$mobilNo,$this->intLoggedinUserAgencySysId);
                $result = array();
                if (!empty($IsAgencyCusTExist)) {
                    $result['MEMBERS'] = $this->_crmcustomerObj->GetCustomerMembersById($this->intLoggedinUserAgencySysId, $IsAgencyCusTExist['CustomerSysId']);
                    $result['SELF'] = $IsAgencyCusTExist;
                } else {
                    $mmbr = $this->_crmcustomerObj->GetCustomerMembersByMobile($this->intLoggedinUserAgencySysId, $mobilNo, $intMemberSysIdRequest);
                    if (!empty($mmbr)) {
                        $result['MEMBERS'] = $this->_crmcustomerObj->GetCustomerMembersByMobile($this->intLoggedinUserAgencySysId, $mobilNo, $intMemberSysIdRequest);
                        $IsAgencyCusTExist = $this->_crmcustomerObj->GetCustomerWithDetails($result['MEMBERS'][0]['CustomerSysId']);
                        $result['SELF'] = $IsAgencyCusTExist;
                    }
                }
                //print_r($result);die;
                $response = '';
                if (!empty($result)) {
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
                    $html->assign('type', 'customerMembersList');
                    $html->assign('data', $result);
                    $bodyText = $html->render('ajax-html.phtml');
                    $response = array('status' => 'success', 'data' => $bodyText, 'CustomerSysId' => $result['SELF']['CustomerSysId'], 'EmailId' => trim($result['SELF']['EmailId']), 'Title' => trim(@$result['SELF']['Title']), 'FirstName' => trim($result['SELF']['FirstName']), 'LastName' => trim($result['SELF']['LastName']), 'DOB' => !empty($result['SELF']['DOB']) ? trim($result['SELF']['DOB']->format('d-M-y')) : '', 'Address' => trim(@$result['SELF']['Address']), 'Contacts' => trim($result['SELF']['Contacts']));
                } else {
                    $response = array('status' => 'failed', 'msg' => 'No Record Availbale!');
                }
                echo json_encode($response);

                exit;
            }
        }
    }



    /* Added By Pardeep Panchal Ends */


    //function used for get detail for on request supplier detail on hotel search created by Er Amit Kumar Dubey on 26 dec 2016 at 12:53 PM
    public function hotelSupplierSendEmailFormAction()
    {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isPost()) {
            $this->_helper->viewRenderer->setNoRender(true);
            $data = $this->getRequest()->getParam('data');
            $dataRes = $this->_HtmlPurifier->filter(base64_decode($data));
            $dataRes = json_decode($dataRes, true);
            $arrSupplierDetails = array();
            if (!empty($dataRes)) {
                $supplierSysId = $dataRes['SupplierSysId'];
                if ($supplierSysId > 0) {
                    $objSupplier = new Travel_Model_TblSupplier();
                    $arrSupplierDetails = $objSupplier->getSupplierById($supplierSysId);
                }
                //$inventSysId=$dataRes['InvnItemSysId'];
                //$hotelid=$dataRes['hotelId'];
            }
            //echo "<pre>";print_r($dataRes);die;
            $this->view->data = $dataRes;
            $this->view->supplierDetails = $arrSupplierDetails;
            $this->view->type = 'hotelSupplierSendEmailForm';
            $this->render('ajaxHtml');
        }
    }
    //code added by Er Amit Kumar Dubey created on 3 march 2017 at 11:01 AM
    public function memberguestdetailAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {
            $mobilNo = trim($this->getRequest()->getParam('mobilNo'));
            $email_id = trim($this->getRequest()->getParam('email_id'));
            $AgencySysId = trim($this->getRequest()->getParam('AgencySysId'));
            $ARR_SALUTION = unserialize(ARR_SALUTION_TJ);
            $ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
            // echo "<pre>";
            // print_r($mobilNo);
            // echo "<pre>";
            // print_r($email_id);

            $intMemberSysIdRequest = trim($this->getRequest()->getParam('intMemberSysId'));
            if (!empty($mobilNo)) {

                //check customer agency
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                //$IsAgencyCusTExist = $this->_crmcustomerObj->ChkMobileWithResponseUpdate($mobilNo, $this->intLoggedinUserAgencySysId, null, $email_id);
                $IsAgencyCusTExist = $this->_crmcustomerObj->ChkMobileWithResponseUpdate($mobilNo, $AgencySysId, null, $email_id);

                $IsB2BAgent = (isset($IsAgencyCusTExist['IsB2BAgent']) && $IsAgencyCusTExist['IsB2BAgent'] == 1) ? $IsAgencyCusTExist['IsB2BAgent'] : 0;
                $result = array();
                if (!empty($IsAgencyCusTExist)) {
                    //$result['MEMBERS'] = $this->_crmcustomerObj->GetCustomerMembersById($this->intLoggedinUserAgencySysId, $IsAgencyCusTExist['CustomerSysId']);
                    $result['MEMBERS'] = $this->_crmcustomerObj->GetCustomerMembersById($AgencySysId, $IsAgencyCusTExist['CustomerSysId']);
                    $result['SELF'] = $IsAgencyCusTExist;
                    if ($IsB2BAgent == 1) {
                        $resultNew = array_values(array_merge([], $this->_crmcustomerObj->GetCustomerMembersById($AgencySysId, $IsAgencyCusTExist['CustomerSysId'])));
                    } else {
                        $resultNew = array_values(array_merge([$IsAgencyCusTExist], $this->_crmcustomerObj->GetCustomerMembersById($AgencySysId, $IsAgencyCusTExist['CustomerSysId'])));
                    }
                } else {
                    $resultNew = [$IsAgencyCusTExist];
                }
                $responseArray = [];
                if ($resultNew) {
                    foreach ($resultNew as $key => $val) {
                        $paxType = !empty($val['paxType']) ? $val['paxType'] : 0;
                        $CustomerTitle = $val['Title'];
                        $DOB_ = (array)$val['DOB'];
                        $PassportExpiry_ = (array)$val['PassportExpiry'];
                        $PassportIssue_ = (array)$val['PassportIssue'];

                        if (!empty($DOB_['date']) && date('Y-m-d', strtotime($DOB_['date'])) != '1900-01-01') {
                            $DOB = ($DOB_['date'] != '0000-00-00') ? date('d/m/Y', strtotime($DOB_['date'])) : '';
                        } else {
                            $DOB = '';
                        }
                        // echo "<pre>";
                        // print_r($val);
                        // echo "</pre>";
                        if (!empty($PassportExpiry_['date']) && date('Y-m-d', strtotime($PassportExpiry_['date'])) != '1900-01-01') {
                            $PassportExpiry = ($PassportExpiry_['date'] != '0000-00-00') ? date('d/m/Y', strtotime($PassportExpiry_['date'])) : '';
                        } else {
                            $PassportExpiry = '';
                        }
                        if (!empty($PassportIssue_['date']) && date('Y-m-d', strtotime($PassportIssue_['date'])) != '1900-01-01') {
                            $PassportIssue = ($PassportIssue_['date'] != '0000-00-00') ? date('d/m/Y', strtotime($PassportIssue_['date'])) : '';
                        } else {
                            $PassportIssue = '';
                        }
                        if ($paxType == 1 || $paxType == 0) {
                            $CustomerTitle = $ARR_SALUTION[$CustomerTitle];
                        } elseif ($paxType == 2) {
                            $CustomerTitle = $ARR_SALUTION_CHILD[$CustomerTitle];
                        } else {
                            $CustomerTitle = $ARR_SALUTION_CHILD[$CustomerTitle];
                        }
                        $val['DOB'] = $DOB;
                        $val['CustomerTitle'] = $CustomerTitle;
                        $val['PassportExpiry'] = $PassportExpiry;
                        $val['PassportIssue'] = $PassportIssue;
                        if ($key == 0) {
                            $val['MemberSysId'] = $val['CustomerSysId'];

                            $responseArray['_' . $val['CustomerSysId']] = $val;
                        } else {

                            $responseArray['_' . $val['MemberSysId']] = $val;
                        }
                    }
                }
                $response = '';
                if (!empty($result)) {
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight/');
                    $html->assign('type', 'customerMembersList');
                    $html->assign('data', $result);
                    $bodyText = $html->render('ajax-html.phtml');
                    $response = array('status' => 'success', 'data' => $bodyText, 'resultNew' => $resultNew, 'responseArray' => $responseArray, 'CustomerSysId' => $result['SELF']['CustomerSysId'], 'EmailId' => trim($result['SELF']['EmailId']), 'Title' => trim($result['SELF']['Title']), 'FirstName' => trim($result['SELF']['FirstName']), 'LastName' => trim($result['SELF']['LastName']), 'DOB' => trim($result['SELF']['DOB']->format('d-M-y')), 'PassportExpiry' => trim($result['SELF']['PassportExpiry']->format('d-M-y')), 'PassportNo' => trim($result['SELF']['PassportNo']), 'Address' => trim($result['SELF']['Address']), 'Contacts' => trim($result['SELF']['Contacts']), 'CitySysId' => trim(@$result['SELF']['CitySysId']), 'cityTitle' => trim(@$result['SELF']['cityTitle']));
                } else {
                    $response = array('status' => 'failed', 'msg' => 'No Record Availbale!');
                }

                echo json_encode($response);

                exit;
            }
        }
    }



    public function countryJsonAction()
    {
        $objCon = new Travel_Model_TblCountry();
        $arrConList = $objCon->getAllCountrylist();
        $arrDest = [];
        foreach ($arrConList as $key => $rr) {
            $arrDest[trim($rr['Code'])] = trim(addslashes($rr['Title']));
        }


        $arrDest = array_map('utf8_encode', $arrDest);
        $strJson = json_encode($arrDest);



        $strPath = $_SERVER["DOCUMENT_ROOT"] . "/public/country.json";

        $strFolder = trim($strPath, basename($strPath)); //exit;

        if (!file_exists($strFolder)) {  // if folder does not exists...
            mkdir($strFolder, 0777, true);
        }

        file_put_contents($strPath, $strJson); // wirte data to respective file...


        exit;
    }






    public function getRanges($intMin, $intMax, $intRanges = 3)
    {

        $intRange = $intMax - $intMin;
        $intIncrement = abs($intRange / $intRanges);
        $arrRanges = array();

        for ($i = 0; $i < $intRanges; $i++) {
            $arrRanges[] = $i == 0 || $i == ($intRanges - 1) ? $i == 0 ? $intMin : $intMax : $intMin + ($i * $intIncrement);
        }

        return $arrRanges;
    }
    public function renderRanges($arrRanges, $strSelected = '', $strName = 'ranges')
    {

        $DataArray = [];
        foreach ($arrRanges as $intIndex => $intRange) {
            $intMin = $intIndex == 0 ? $intRange : $arrRanges[($intIndex - 1)];
            $intMax = $intIndex == 0 ? $arrRanges[($intIndex + 1)] : $intRange;
            $DataArray[] = ceil($intMin) . '-' . ceil($intMax);
        }
        return array_unique($DataArray);
    }
    // New Function For Api Hotels.............###########################################################################

    public function hotelResultsAction()
    {
        $post = $this->getRequest()->getParams();
        $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
        $objTempFlight = new Travel_Model_TblFlight();
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
            // ini_set('display_errors', 1);
            // ini_set('display_startup_errors', 1);
            // error_reporting(E_ALL);

            $searchID = $post['searchID'];
            $SearchQueryid = isset($post['SearchQueryid']) ? $post['SearchQueryid'] : '';
            $FlightTempData = $objTempFlight->GetFlightTempData($searchID);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            $searchids = isset($arrUrlData['searchids']) ? $arrUrlData['searchids'] : [];
            $hotelCityTitle = $SearchParams['hotelCityTitle'];
            $memberDetails = $SearchParams['memberDetails'];
            $hotelStarRating = (int) $SearchParams['hotelStarRating'];
            $nights = (int) $SearchParams['hotelTotalNights'];
            $rooms = (int) $SearchParams['hotelTotalRooms'];
            $AdultPax = (int) $SearchParams['totalMemberCount']['AdultPax'];
            $ChildPax = (int) $SearchParams['totalMemberCount']['ChildPax'];
            $MemberCount = ($AdultPax + $ChildPax);

            $CheckApiActive = $objTempFlight->checkActiveAPI($this->intLoggedinUserAgencySysId, 2);
            $CheckApiActiveTJ = $objTempFlight->checkActiveAPI($this->intLoggedinUserAgencySysId, 4);

            $APISourceSysId = (isset($CheckApiActive['APISourceSysId']) && !empty($CheckApiActive['APISourceSysId'])) ? $CheckApiActive['APISourceSysId'] : '';
            $APISourceSysIdTJ = (isset($CheckApiActiveTJ['APISourceSysId']) && !empty($CheckApiActiveTJ['APISourceSysId'])) ? $CheckApiActiveTJ['APISourceSysId'] : '';

            $strCheckInDate = $SearchParams['hotelFromDateSession'];
            $strCheckOutDate = $SearchParams['hotelToDateSession'];

            if (!empty($strCheckInDate)) {
                $arrCheckInDate = explode("/", $strCheckInDate);
                if (!empty($arrCheckInDate)) {
                    $strCheckInDateNew = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
                }
            }

            if (!empty($strCheckOutDate)) {
                $arrCheckOutDate = explode("/", $strCheckOutDate);
                if (!empty($arrCheckOutDate)) {
                    $strCheckOutDateNew = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];
                }
            }

            $residence = '106';
            $roominfo = [];
            $RoomGuests = [];
            $memberdata = [];
            $stars = [];
            if ($memberDetails) {
                foreach ($memberDetails as $key => $value) {
                    $adult = (int) $value['AdultPax'];
                    $child = (int) $value['ChildPax'];
                    $childArray = explode(',', $value['ChildsAge']);

                    $roominfo[$key] = array(
                        'numberOfAdults' => $adult,
                        'numberOfChild' => $child,
                    );
                    if ($child > 0) {
                        $roominfo[$key]['childAge'] = $childArray;
                    }
                    $RoomGuests[]        = ['NoOfAdults' => $adult, 'NoOfChild' => $child, 'ChildAge' => $childArray];
                    $childAges = [];
                    if (isset($childArray[0]) && !empty($childArray[0] && $child == '1')) {
                        $childAges[0] = $childArray[0];
                    }
                    if (isset($childArray[0]) && !empty($childArray[0] && $child == '2')) {
                        $childAges[0] = $childArray[0];
                        $childAges[1] =  $childArray[1];
                    }
                    $memberdata[] = array(
                        'NoOfAdults' => (int)$adult,
                        'NoOfChild' =>  (int)$child,
                        'ChildAge' => $childAges
                    );
                }
            }

            $searchCriteria['city'] = $SearchParams['hidden_selected_hotel_id'];
            $searchCriteria['currency'] = 'INR';
            $searchCriteria['nationality'] = $residence;
            for ($i = 1; $i < $hotelStarRating; $i++) {
                $stars[] = (int)$i;
            }
            $fsc = false;
            if (isset($SearchParams['special']) && $SearchParams['special'] == 'on') {
                $fsc = true;
            }
            $searchPreferences['ratings'] = ($hotelStarRating == 6) ? [3, 4, 5] : $stars;
            $searchPreferences['fsc'] = $fsc;

            $searchQuery = array(
                'checkinDate' => date('Y-m-d', strtotime($strCheckInDateNew)),
                'checkoutDate' => date('Y-m-d', strtotime($strCheckOutDateNew)),
                'roomInfo' => $roominfo,
                'searchCriteria' => $searchCriteria,
                'searchPreferences' => $searchPreferences,
            );

            $tbo_json = array(
                'CheckInDate'   => date('d/m/Y', strtotime($strCheckInDateNew)),
                'NoOfNights'   => $SearchParams['hotelTotalNights'],
                'CountryCode'   => $SearchParams['tboCountryCode'],
                'CityId'   => $SearchParams['tboCityId'], //'10409',
                'IsTBOMapped'   => true,
                'ResultCount'   => null,
                'PreferredCurrency'   => 'INR',
                'GuestNationality'   => $SearchParams['selectNationality'],
                'NoOfRooms'   => count($roominfo),
                'RoomGuests'   => $memberdata,
                'PreferredHotel'    => '',
                'MaxRating'    => 5,
                'MinRating'    => 0,
                'ReviewScore'    => null,
                'IsNearBySearchAllowed'    => false
            );
            $minHotelRating = min($searchPreferences['ratings']);
            $maxHotelRating = max($searchPreferences['ratings']);
            $tbo_json['MaxRating'] = $maxHotelRating;
            $tbo_json['MinRating'] = $minHotelRating;

            $searchdata = array(
                'hotelsearchdata' => array('searchQuery' => $searchQuery, 'sync' => false),
                'searchID' => $searchID,
                'MemberCount' => $MemberCount,
                'destination' => $hotelCityTitle,
                'PlanType' => 2,
                'MPType' => 1,
                'interNationalSearch' => false,
                'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
            );
            //if ($this->intLoggedinUserAgencySysId == 1 || $this->intLoggedinUserAgencySysId == 2656) {
            $searchNew = ['SearchQueryid' => $SearchQueryid];
            $getData['SecurityKey'] = trim($this->agencyDetails['SecurityKey']);
            $URL = GTX_API_URL . '/hotel/v2/search';

            $Response = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->apiHttpRequest($searchNew, $getData, $URL);
            //$Response = [];
            $ResultStatus = isset($Response['status']) ? $Response['status'] : false;
            if ($ResultStatus == 1) {
                $MinPriceRange = $Response['MinPriceRange'];
                $MaxPriceRange = $Response['MaxPriceRange'];

                $arrRange = $this->renderRanges($this->getRanges($MinPriceRange, $MaxPriceRange, 7));
                $Response['PriceRange'] = $arrRange;

                echo json_encode($Response);
                exit;
            } else {
                echo json_encode(['status' => false]);
                exit;
            }
            //}
            //$SecurityKey = 'F38C55F4-5771-4EED-AAB2-D1CE094AEB4E'; //$this->agencyDetails['SecurityKey'];
            $SecurityKey = $this->agencyDetails['SecurityKey'];
            // $str = file_get_contents($this->baseUrl . '/public/hotellist.json');
            // $apiResponse = json_decode($str, true);
            $apiResponse = [];
            if ($APISourceSysIdTJ == '4') {
                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getHotelSearchId($searchdata, $SecurityKey);
            }

            $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : 0;
            if ($APISourceSysId == '2') {
                $ResponseStatus = true;
            }

            if ($ResponseStatus == 1) {

                $hotelrqst = [
                    // 'searchData' => $hotelrqst,
                    'searchID' => $searchID,
                    'MemberCount' => $MemberCount,
                    'destination' => $hotelCityTitle,
                    'rooms' => $rooms,
                    'nights' => $nights,
                    'PlanType' => 2,
                    'MPType' => 1,
                    'interNationalSearch' => false,
                ];

                if ($APISourceSysIdTJ == '4') {
                    $hotelrqst["TPJ"] = [
                        "post" => [
                            "searchId" => isset($apiResponse['data']['searchIds'][0]) ? $apiResponse['data']['searchIds'][0] : '',
                        ]
                    ];
                }
                if ($APISourceSysId == '2') {
                    $hotelrqst["TBO"] = [
                        'post' => $tbo_json
                    ];
                }

                $Response = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getHotelSearchResult($hotelrqst, $SecurityKey);
                //$Response = json_decode($str, true);

                // echo "<pre>";
                // print_r(($Response));
                // exit;
                $ResultStatus = $Response['status'];
                if ($ResultStatus == 1) {
                    $MinPriceRange = $Response['MinPriceRange'];
                    $MaxPriceRange = $Response['MaxPriceRange'];

                    $arrRange = $this->renderRanges($this->getRanges($MinPriceRange, $MaxPriceRange, 7));
                    $Response['PriceRange'] = $arrRange;

                    echo json_encode($Response);
                    exit;
                } else {
                    echo json_encode(['status' => false]);
                    exit;
                }
            } else {
                echo json_encode(['status' => false]);
                exit;
            }
            //$apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getHotelSearchResult($searchdata, $this->intLoggedinUserAgencySysId);

            echo "<pre>";
            print_r($apiResponse);
            echo "<pre>";
            print_r($arrUrlData);
            die;

            // Old code from here
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $intNoOfNights = $sessionhotelDirectSearchData->params['hotelTotalNights'];
            $intNoOfRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];
            $strcountryCode = $sessionhotelDirectSearchData->params['countryCode'];
            $arrmemberDetails = $sessionhotelDirectSearchData->params['memberDetails'];

            //$arrmemberDetails = json_decode($sessionhotelDirectSearchData->params['RoomMemInfoJson'],1);
            if (!empty($arrmemberDetails)) {
                $arrMembers = [];
                $arrTotalMemberCount = [];
                $IntRoom = $TotalAdultPax = $TotalChildPax = 0;
                if (!empty($arrmemberDetails)) {
                    $arrMembers = [];
                    $IntRoom = 0;
                    foreach ($arrmemberDetails as $memDetails) {
                        $arrMembers[$IntRoom]['Adult'] = $memDetails['AdultPax'];
                        $arrMembers[$IntRoom]['Child'] = $memDetails['ChildPax'];
                        $IntRoom++;
                    }
                }
            }

            // API Look Up For Hotels.....
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->searchApiHotelsNew($sessionhotelDirectSearchData->params, "B2B");


            // Inventory Part..............

            $intGTXCityId = $sessionhotelDirectSearchData->params['hotelXrefCityId'];

            $objHotel = new Travel_Model_TblBuyHotel();
            $objHotel->strCondition = '';
            if (!empty($intGTXCityId)) {
                $objHotel->strCondition .= " t1.CitySysId = '" . $intGTXCityId . "'";
            }


            $strCheckInDate = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
            $strCheckOutDate = $sessionhotelDirectSearchData->params['hotelToDateSession'];



            // Condition used only For Inventory
            if (!empty($strCheckInDate)) {
                $arrCheckInDate = explode("/", $strCheckInDate);
                if (!empty($arrCheckInDate)) {
                    $strCheckInDateNew = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
                }
            }

            if (!empty($strCheckOutDate)) {
                $arrCheckOutDate = explode("/", $strCheckOutDate);
                if (!empty($arrCheckOutDate)) {
                    $strCheckOutDateNew = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];
                }
            }
            if (!empty($strCheckInDateNew) && !empty($strCheckOutDateNew)) {
                $objHotel->strCheckInDate   = " $strCheckInDateNew ";
                $objHotel->strCheckOutDate  = " $strCheckOutDateNew ";
            }



            $arrInventoryHotels = $objHotel->getInventoryHotels();

            //                echo "<pre>";print_r($arrInventoryHotels);exit;


            $INV_I = (!empty(@$apiResponse['Hotels'])) ? empty(@$apiResponse['Hotels']) : 0;
            $checkDuplicateHotel = array();
            foreach ($arrInventoryHotels as $invHotels) {
                if (!in_array($invHotels['AccomSysId'], $checkDuplicateHotel)) {
                    $checkDuplicateHotel[] =   $invHotels['AccomSysId'];
                    $PublishedPrice = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getTotalCostOfHotelByTravelersNew($invHotels, $arrMembers);

                    //                    $arrPriceAndMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($PublishedPrice,"0",$intNoOfNights,$intNoOfRooms,$strcountryCode);
                    //                    //echo "<pre>";print_r($arrPriceAndMarkUps);exit;
                    $PublishedPrice = round($PublishedPrice * $intNoOfNights);
                    $intRoomFarePerNightPerPerson = round(($PublishedPrice / $intNoOfNights) / $intNoOfRooms);
                    //$intAgencyMarkUp = ($arrPriceAndMarkUps['intAgencyMarkUp']);



                    $apiResponse['Hotels'][$INV_I]['ApiSourceSysId'] = 'Inv';
                    $apiResponse['Hotels'][$INV_I]['TraceId'] = $invHotels['AccomSysId'];  // In Case of inventory Hotels this will fetch Hotel detail
                    $apiResponse['Hotels'][$INV_I]['TokenId'] = '';
                    $apiResponse['Hotels'][$INV_I]['APICityId'] = '';
                    $apiResponse['Hotels'][$INV_I]['HotelCode'] = '';
                    $apiResponse['Hotels'][$INV_I]['HotelName'] = $invHotels['HotelName'];
                    $apiResponse['Hotels'][$INV_I]['ResultIndex'] = $invHotels['InvnItemSysId'];  // In Case of inventory Hotels this will fetch Hotel detail;
                    $apiResponse['Hotels'][$INV_I]['HotelPicture'] = $invHotels['DetailImg'];
                    $apiResponse['Hotels'][$INV_I]['StarRating'] = $invHotels['Stars'];
                    $apiResponse['Hotels'][$INV_I]['AgencyRating'] = '';
                    $apiResponse['Hotels'][$INV_I]['AwardRecognizations'] = '';
                    $apiResponse['Hotels'][$INV_I]['AwardURL'] = '';
                    $apiResponse['Hotels'][$INV_I]['AccoAminitiesMask'] = '';
                    $apiResponse['Hotels'][$INV_I]['HotelDescription'] = '';
                    $apiResponse['Hotels'][$INV_I]['OfferPrice'] = $PublishedPrice;
                    $apiResponse['Hotels'][$INV_I]['PublishedPrice'] = $PublishedPrice;
                    $apiResponse['Hotels'][$INV_I]['PerNight'] = $intRoomFarePerNightPerPerson;
                    $apiResponse['Hotels'][$INV_I]['amarkup'] = 0;
                    $apiResponse['Hotels'][$INV_I]['AgentCommission'] = 0;
                    $apiResponse['Hotels'][$INV_I]['Latitude'] = '';
                    $apiResponse['Hotels'][$INV_I]['Longitude'] = '';
                    $apiResponse['Hotels'][$INV_I]['HotelAddress'] = $invHotels['Address'];
                    $apiResponse['Hotels'][$INV_I]['hotelsource'] = "INV";
                    $apiResponse['Hotels'][$INV_I]['EType'] = $invHotels['EconomyTypeTitle'];
                    $apiResponse['Hotels'][$INV_I]['MPType'] = $invHotels['MealPlanTypeTitle'];
                    $INV_I++;
                }
            }
            // Inventory Part..............


            //For Price Range Filters...........
            $priceArr = [];
            if (isset($apiResponse['Hotels']) && count($apiResponse['Hotels']) > 0) {
                foreach ($apiResponse['Hotels'] as $value) {
                    $publishedfare = isset($value['PublishedPrice']) ? round($value['PublishedPrice']) : 0;
                    if (!in_array($publishedfare, $priceArr)) {
                        $priceArr[] = $publishedfare;
                    }
                }
            }

            // price ranges....
            sort($priceArr);
            $last = end($priceArr);
            $start = 0;
            $fraction = 2500;
            $priceArr[] = $last + $fraction;
            $maximum = end($priceArr); ///exit;
            $arrRange = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getPriceDropdown($start, $maximum, $fraction, $priceArr);
            $arrR = [];
            foreach ($arrRange as $range) {
                $arrR[] = [
                    "type" => "price",
                    "range" => $range,
                    "on" => false
                ];
            }
            $apiResponse['pricerange'] = $arrR;
            //For Price Range Filters...........


            //echo "<pre>";print_r($apiResponse);exit;

            $strJsonData = json_encode($apiResponse);

            // Write response to JSON File....
            $UniqueSessionId = Zend_Session::getId();
            $strPath = $_SERVER["DOCUMENT_ROOT"] . "/public/data/hotel-search";

            $strFolder = trim($strPath, basename($strPath));
            if (!file_exists($strFolder)) {  // if folder does not exists...
                mkdir(@$strFolder, 0777, true);
            }

            //delete old files...
            $filePathToDelete = $_SERVER['DOCUMENT_ROOT'] . "/public/data/hotel-search";
            Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->deleteSearchJsonFile($filePathToDelete);
            //delete old files...

            $strFile = $_SERVER["DOCUMENT_ROOT"] . "/public/data/hotel-search/hotel_search_" . $UniqueSessionId . ".txt";
            file_put_contents($strFile, $strJsonData);
            // Write response to JSON File Ends....

            echo json_encode(["success" => true, "msg" => "", "sessionId" => $UniqueSessionId]);
            exit;
        } else {
            $searchID = $post['searchID'];

            $FlightTempData = $objTempFlight->GetFlightTempData($searchID);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $searchids = isset($arrUrlData['searchids']) ? $arrUrlData['searchids'] : [];

            $this->view->TaxPercentage = 18;
            $this->view->baseUrl = $this->baseUrl;
            $this->view->LoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $post['searchID'];
            $this->view->searchids = json_encode($searchids);
            $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $this->view->searchParams = $sessionhotelDirectSearchData->params;


            if (isset($sessionhotelDirectSearchData->params['customerId']) && !empty($sessionhotelDirectSearchData->params['customerId'])) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = isset($sessionhotelDirectSearchData->params['customerId']) ? $this->_crmcustomerObj->GetAgencyCustomerById(trim($sessionhotelDirectSearchData->params['customerId'])) : '';
                $sessionhotelDirectSearchData->params['customername'] = trim($customerDetails['FirstName']) . "&nbsp;" . trim($customerDetails['LastName']);
                $this->view->customerDetails = $customerDetails;
            }

            $AdultPax = $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
            $ChildPax = $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];
            $intTotalPaxCount = $AdultPax + $ChildPax;


            // For Harpreet Code will remove later...
            $_SESSION['SEARCH'] = $sessionhotelDirectSearchData->params;
            //print_r($_SESSION['SEARCH']);
            $_SESSION['chekInDate'] = $sessionhotelDirectSearchData->params['hotelFromDateSession'];
            $_SESSION['chekOutDate'] = $sessionhotelDirectSearchData->params['hotelToDateSession'];
            $_SESSION['nights'] = $sessionhotelDirectSearchData->params['hotelTotalNights'];
            $_SESSION['noOfAdults'] = $AdultPax;
            $_SESSION['intTotalPaxCount'] = $intTotalPaxCount;
            $_SESSION['noOfRooms'] =  $sessionhotelDirectSearchData->params['hotelTotalRooms'];
            // For Harpreet Code will remove later...
            $agencyModel = new Travel_Model_TblAgency();
            $getActiveSenderEmailIdArr = $agencyModel->getActiveSenderEmailID($this->intLoggedinUserAgencySysId);
            $SenderEmailSysId = isset($_SESSION['AgencyUser']['user']->SenderEmailSysId) ? $_SESSION['AgencyUser']['user']->SenderEmailSysId : 0;
            $this->view->getActiveSenderEmailIdArr = $getActiveSenderEmailIdArr;
            $this->view->SenderEmailSysId = $SenderEmailSysId;
            $this->view->getActiveStaff = $getActiveStaff = $agencyModel->getActiveStaff($this->intLoggedinUserAgencySysId);
            $getleadSource = $this->_crmcustomerObj->getLeadSourceByAgency($this->intLoggedinUserAgencySysId);
            $this->view->getleadSource = $getleadSource;
        }
    }
    public function booknowAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);
            if ($post['hotelData'] && $post['searchID'] && $post['RoomInfo']) {
                $searchIDSearch = $post['searchID'];
                $objTempFlight = new Travel_Model_TblFlight();
                $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
                $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
                $TPSysId = $FlightTempData['TPSysId'];
                $SearchParams = $arrUrlData['SearchParams'];
                $SearchHotelTraceId = $post['hotelData']['SearchHotelTraceId'];
                $arrUrlData['hotelData'] = $post['hotelData'];
                $arrUrlData['RoomInfo'] = $post['RoomInfo'];

                $arrUrlData['searchids'] = $SearchHotelTraceId;
                $tempData = array(
                    'TraceId' => $SearchHotelTraceId,
                    'TPSysId' => ($TPSysId),
                    'APIBookingData' => json_encode($arrUrlData),
                );
                $objTempFlight->deleteFlightTempData($SearchHotelTraceId);
                $objTempFlight->insertFlightTempData($tempData);

                echo json_encode(['status' => true, 'message' => 'SUCESS', 'SearchTraceId' => $SearchHotelTraceId]);
                exit;
            } else {
                echo json_encode(['status' => false, 'message' => 'Oops somethings went wrong.', 'SearchTraceId' => '']);
                exit;
            }
        }
    }

    public function travellersAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        $objTempFlight = new Travel_Model_TblFlight();
        $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
        if ($FlightTempData) {
            $TPSysId = $FlightTempData['TPSysId'];
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $hotelData = $arrUrlData['hotelData'];
            $RoomInfo = $arrUrlData['RoomInfo'];
            $SearchParams = $arrUrlData['SearchParams'];
            $B2BSearch = isset($arrUrlData['B2BSearch']) ? $arrUrlData['B2BSearch'] : [];
            $tboCountryCode = $SearchParams['tboCountryCode'];

            if ($this->_request->isXmlHttpRequest()) {

                if ($hotelData && $RoomInfo && $searchIDSearch) {
                    $HotelID = $hotelData['HotelId'];
                    $ICSourceSysId = $hotelData['ICSourceSysId'];
                    $RoomId = $RoomInfo['RoomId'];
                    $CityName = $SearchParams['CityName'];
                    $hotelTotalRooms = $SearchParams['hotelTotalRooms'];
                    $tboCountryCode = $SearchParams['tboCountryCode'];
                    $memberDetailsRoom = $SearchParams['memberDetails'];
                    $hotelTotalNights = $SearchParams['hotelTotalNights'];
                    $AdultPax = (int) $SearchParams['totalMemberCount']['AdultPax'];
                    $ChildPax = (int) $SearchParams['totalMemberCount']['ChildPax'];
                    $MemberCount = ($AdultPax + $ChildPax);
                    if ($tboCountryCode != 'IN') {
                        $interNationalSearch = true;
                    } else {
                        $interNationalSearch = false;
                    }
                    if ($ICSourceSysId == 7) {
                        $request = [
                            "hotelId" => $HotelID,
                            "optionId" => $RoomId,
                        ];
                    } else {
                        $request = [
                            "BookingCode" => $RoomId,
                            "PaymentMode" => 'Limit',
                        ];
                    }

                    $DataS = array(
                        "request" => $request,
                        "searchID" => $searchIDSearch,
                        "MemberCount" => $MemberCount,
                        "destination" => $CityName,
                        "nights" => $hotelTotalNights,
                        "rooms" => $hotelTotalRooms,
                        "PlanType" => 2,
                        "ICSourceSysId" => $ICSourceSysId,
                        "B2B" => $B2BSearch,
                        "MPType" => 1,
                        "interNationalSearch" => $interNationalSearch,
                        'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,

                    );

                    // echo '<pre>';
                    // print_r($DataS);
                    // die('dddd');
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $URL = GTX_API_URL . '/hotel/v2/hotelreview';
                    $apiResponse = [];
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->apiHttpRequest($DataS, $getData, $URL);
                    // echo '<pre>';
                    // print_r($DataS);
                    // echo '<pre>';
                    // print_r(json_encode($apiResponse));
                    // die('dddd');
                    $status = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                    $ErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                    if ($apiResponse && $status) {
                        $arrUrlData['searchids'] = $SearchHotelTraceId;
                        $arrUrlData['hoteldetails'] = $apiResponse;
                        $HotelDetails = $apiResponse['HotelDetails'];
                        $RoomInfo = $apiResponse['RoomInfo'];

                        $IsPANMandatory = ($HotelDetails['IsPANMandatory']);
                        $IsPassportMandatory = ($HotelDetails['IsPassportMandatory']);

                        $TotalBaseFare = 0;
                        $OtherCharges = 0;
                        $TotalTaxesandFee = 0;
                        $TotalDiscount = 0;
                        $GrandTotal = 0;
                        $Currncy = '';
                        $TotalCommissionEarned = 0;
                        $TotalFixedMarkUp = 0;
                        $TotalGSTOnMarkUp = 0;
                        $TotalTDSEarn = 0;
                        $travellers = [];
                        $BaseFareArray = [];
                        if ($memberDetailsRoom) {
                            foreach ($memberDetailsRoom as $key => $values) {
                                $RoomInfoData = $RoomInfo[0]['Rooms'][$key];

                                $Currncy = $RoomInfoData['Currency'];
                                $ConvertionRate = $RoomInfoData['ConvertionRate'];
                                $BaseFare = ($RoomInfoData['TotalBaseFare'] * $ConvertionRate);
                                $TotalBaseFare += ($RoomInfoData['TotalBaseFare'] * $ConvertionRate);
                                $OtherCharges = isset($RoomInfoData['OtherCharges']) ? $RoomInfoData['OtherCharges'] : 0;
                                $TotalFixedMarkUp += ($RoomInfoData['FixedMarkUp'] * $ConvertionRate);
                                $TotalGSTOnMarkUp += ($RoomInfoData['GSTOnMarkUp'] * $ConvertionRate);
                                $TotalTaxesandFee += (($RoomInfoData['TotalTaxFare'] + $OtherCharges) * $ConvertionRate);
                                $adultCount = isset($values['AdultPax']) ? $values['AdultPax'] : 1;
                                $childCount = isset($values['ChildPax']) ? $values['ChildPax'] : 0;
                                $childAge = (isset($values['ChildsAge']) && !empty($values['ChildsAge'])) ? explode(',', $values['ChildsAge']) : [];
                                $memberDetails = [];
                                if ($adultCount > 0) {
                                    $intPaxCount = 1;
                                    for ($i = 0; $i < $adultCount; $i++) {
                                        $memberDetails[$i]['index'] = $i;
                                        $memberDetails[$i]['room'] = ($key + 1);
                                        $memberDetails[$i]['PaxCount'] = $intPaxCount;
                                        $memberDetails[$i]['PaxType'] = 1;
                                        $memberDetails[$i]['pax'] = 'ADULT';
                                        $memberDetails[$i]['AgeR'] = '12 yrs+';
                                        $memberDetails[$i]['cid'] = 0;
                                        $memberDetails[$i]['fname'] = '';
                                        $memberDetails[$i]['lname'] = '';
                                        $memberDetails[$i]['name'] = '';
                                        $memberDetails[$i]['title'] = '';
                                        $memberDetails[$i]['dob'] = '';
                                        $memberDetails[$i]['passno'] = '';
                                        $memberDetails[$i]['passisse'] = '';
                                        $memberDetails[$i]['passexp'] = '';
                                        $memberDetails[$i]['panno'] = '';
                                        $memberDetails[$i]['passnational'] = 'IN';
                                        $memberDetails[$i]['isdobr'] = false;
                                        $memberDetails[$i]['IsPassM'] = $IsPassportMandatory;
                                        $memberDetails[$i]['addonns'] = true;
                                        $memberDetails[$i]['checked'] = ($i == 1) ? true : false;
                                        $memberDetails[$i]['IsPAN'] = $IsPANMandatory;
                                        $intPaxCount++;
                                    }
                                }
                                if ($childCount > 0) {
                                    $intPaxCount = 1;
                                    $CH = 0;
                                    for ($kk = $i; $kk < ($childCount + $adultCount); $kk++) {
                                        $AGE = isset($childAge[$CH]) ? $childAge[$CH] : '';
                                        $memberDetails[$kk]['index'] = $kk;
                                        $memberDetails[$kk]['room'] = ($key + 1);
                                        $memberDetails[$kk]['PaxCount'] = $intPaxCount;
                                        $memberDetails[$kk]['PaxType'] = 2;
                                        $memberDetails[$kk]['pax'] = 'CHILD';
                                        $memberDetails[$kk]['AgeR'] = '2-12 Yrs';
                                        $memberDetails[$kk]['Age'] = $AGE;
                                        $memberDetails[$kk]['cid'] = 0;
                                        $memberDetails[$kk]['fname'] = '';
                                        $memberDetails[$kk]['lname'] = '';
                                        $memberDetails[$kk]['name'] = '';
                                        $memberDetails[$kk]['title'] = '';
                                        $memberDetails[$kk]['dob'] = '';
                                        $memberDetails[$kk]['passno'] = '';
                                        $memberDetails[$kk]['passisse'] = '';
                                        $memberDetails[$kk]['passexp'] = '';
                                        $memberDetails[$kk]['panno'] = '';
                                        $memberDetails[$kk]['passnational'] = 'IN';
                                        $memberDetails[$kk]['isdobr'] = false;
                                        $memberDetails[$kk]['IsPassM'] = $IsPassportMandatory;
                                        $memberDetails[$kk]['addonns'] = true;
                                        $memberDetails[$kk]['checked'] = false;
                                        $memberDetails[$kk]['IsPAN'] = false;
                                        $intPaxCount++;
                                        $CH++;
                                    }
                                }
                                $travellers[$key]['RoomType'] = ['name' => $RoomInfoData['RoomType'], 'MealBase' => $RoomInfoData['MealBase']];
                                $travellers[$key]['memberDetails'] = $memberDetails;
                                $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $RoomInfoData['RoomType'], 'MealBase' => $RoomInfoData['MealBase']];
                            }
                        }

                        $fare = array(
                            'Currncy' => $Currncy,
                            'BaseFare' => round($TotalBaseFare, 2),
                            'TaxesandFee' => round($TotalTaxesandFee, 2),
                            'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp, 2),
                            'CommissionEarned' => round($TotalCommissionEarned, 2),
                            'TDSEarn' => round($TotalTDSEarn, 2),
                            'Discount' => round($TotalDiscount, 2),
                            'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                            'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                            'roomCoun' => $hotelTotalRooms,
                            'nightCoun' => ($hotelTotalNights),
                            'BaseFareArray' => ($BaseFareArray),
                        );
                        $TotalPay = ceil($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp);
                        // echo "<pre>";
                        // print_r(($TotalPay));
                        // print_r(($fare));
                        // echo "</pre>";
                        $tempData = array(
                            'TraceId' => $SearchHotelTraceId,
                            'TPSysId' => ($TPSysId),
                            'APIBookingData' => json_encode($arrUrlData),
                        );
                        $objTempFlight->deleteFlightTempData($SearchHotelTraceId);
                        $objTempFlight->insertFlightTempData($tempData);
                        echo json_encode(['status' => true, 'message' => 'SUCESS', 'fare' => $fare, 'travellers' => $travellers, 'hoteldetails' => $HotelDetails, 'RoomInfo' => $RoomInfo, 'SearchParams' => $SearchParams]);
                        exit;
                    } else {
                        echo json_encode(['status' => false, 'message' => $ErrorMessage, 'SearchTraceId' => '']);
                        exit;
                    }

                    // echo "<pre>";
                    // print_r($getData);
                    // echo "</pre>";
                    // exit;
                } else {
                    echo json_encode(['status' => false, 'message' => 'Oops somethings went wrong.', 'SearchTraceId' => '']);
                    exit;
                }
            }
            // echo "<pre>";
            // print_r(($SearchParams));
            // die;
            $objMarkup = new Markup_Model_Markup();
            if (!empty(trim($tboCountryCode)) && trim($tboCountryCode) != "IN") {
                $intAirType = 2;
            } else {
                $intAirType = 1;
            }
            $arrAgencyUserDetail = $objMarkup->getAgencyUserDetail(array("AgencySysId" => $this->intLoggedinUserAgencySysId, "ItemSourceType" => (int) $intAirType, "PlanType" => 2));
            $this->view->arrAgencyUserDetail = $arrAgencyUserDetail;
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = isset($SearchParams['customerId']) ? $crmcustomerObj->GetAgencyCustomerById(trim($SearchParams['customerId'])) : '';
            $this->view->arrTrevllerDetails = $customerDetails;
            $this->view->searchID = $searchIDSearch;
            $this->view->hotelData = $hotelData;
            $this->view->RoomInfo = $RoomInfo;
            $this->view->SearchParams = $SearchParams;
            $this->view->arrTrevllerDetails = $customerDetails;
            $this->view->AgencySysId = $this->intLoggedinUserAgencySysId;
            // echo "<pre>";
            // print_r(($arrAgencyUserDetail));
            // die;
        } else {

            echo json_encode(['status' => false, 'message' => 'Invalid request', 'SearchTraceId' => '']);
            exit;
        }
    }
    public function reviewAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        $objTempFlight = new Travel_Model_TblFlight();
        $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
        if ($FlightTempData) {
            $TPSysId = $FlightTempData['TPSysId'];
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            if ($this->_request->isXmlHttpRequest()) {

                if ($TPSysId && $searchIDSearch) {
                    $TotalBaseFare = 0;
                    $TotalTaxesandFee = 0;
                    $TotalDiscount = 0;
                    $Currncy = '';
                    $TotalCommissionEarned = 0;
                    $TotalFixedMarkUp = 0;
                    $TotalGSTOnMarkUp = 0;
                    $TotalTDSEarn = 0;
                    $BaseFareArray = [];

                    $PostData = ['TPSysId' => $TPSysId];
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';

                    $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                    $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
                    $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
                    $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
                    $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                    if (empty($HotelData) || ($CurrentStatus == 24)) {
                        $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => 'This Trace id already expired', 'urlData' => $strUrlData, 'formAction' => "/flight-new/booking-confirmation/data/" . $TPSysId . "");
                        echo json_encode($response);
                        exit;
                    }
                    // echo "<pre>";
                    // print_r(($HotelData));
                    // die;
                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $Currncy = $values['Currency'];
                            $BaseFare = ($values['RoomPrice']);
                            $TotalBaseFare += ($values['RoomPrice']);
                            $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                            $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                            $TotalTaxesandFee += (($values['Taxes']));
                            $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                        }
                    }

                    $fare = array(
                        'Currncy' => $Currncy,
                        'BaseFare' => round($TotalBaseFare, 2),
                        'TaxesandFee' => round($TotalTaxesandFee, 2),
                        'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp, 2),
                        'CommissionEarned' => round($TotalCommissionEarned, 2),
                        'TDSEarn' => round($TotalTDSEarn, 2),
                        'Discount' => round($TotalDiscount, 2),
                        'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                        'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                        'roomCoun' => count($accom_room),
                        'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                        'BaseFareArray' => ($BaseFareArray),
                    );
                    // echo "<pre>post";
                    // print_r(($accom_room));
                    // die;

                    echo json_encode([
                        'status' => true,
                        'message' => 'SUCESS',
                        'fare' => $fare,
                        'HotelData' => $HotelData,
                    ]);
                    exit;
                }
            }
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinUserAgencySysId);
            $getAgentDetailById = $crmcustomerObj->getAgentDetailById($this->intLoggedinUserId);
            $this->view->IsAllowFlightBooking = isset($getAgentDetailById[0]['IsAllowFlightBooking']) ? $getAgentDetailById[0]['IsAllowFlightBooking'] : 0;
            $this->view->IsCheckWallet = isset($getAgencyDetail['IsCheckWallet']) ? $getAgencyDetail['IsCheckWallet'] : 0;
            $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
            $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
            $AgencySysId = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
            $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;
            $this->view->IsB2BCustomer = $IsB2BCustomer;
            $this->view->IsEnabledWallet = $IsEnabledWallet;
            $this->view->walletBalanceAmount = '0.00';

            $model = new Gtxwebservices_Model_Webservices();
            if ($IsB2BCustomer == 1) {
                $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId);
                $B2BAgencySysIdKey = $getAgencyDetail['SecurityKey'];
                $B2CAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
                $apiDataIV = array(
                    "B2BAgencySysIdKey" => $B2BAgencySysIdKey,
                    "B2CAgencySysIdKey" => $B2CAgencySysIdKey,
                );

                $result = json_decode($model->GetB2Bbalance($apiDataIV), true);
                $this->view->walletBalanceAmount = $result['creditBalance'];
            } elseif ($IsEnabledWallet == 1) {
                $apiDataIV = array(
                    "CustomerSysId" => $CustomerSysId,
                );

                $result = json_decode($model->GetB2Cbalance($apiDataIV, $this->agencyDetails['SecurityKey']), true);
                $this->view->walletBalanceAmount = (isset($result['WalletBalance'][0]['BalanceAmount']) && !empty($result['WalletBalance'][0]['BalanceAmount'])) ? $result['WalletBalance'][0]['BalanceAmount'] : 0;
            }
            // echo "<pre>post";
            // print_r(($customerDetails));
            // die;
            $this->view->intLoggedinUserId = $this->intLoggedinUserId;
            $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupSysId;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $searchIDSearch;
            $this->view->TPSysId = $TPSysId;
            $this->view->ActionName = 'review';

            $fullBaseUrl = $this->view->baseUrl();
            $this->view->strPayWithWalletUrl = $fullBaseUrl . "/payment/wallet-pay";
            $this->view->strRechargeNowUrl = $fullBaseUrl . "/payment/payment-options";
            $this->view->strSearchPageUrl = $fullBaseUrl . "/buyhotel/search-result";
            $this->view->strReturnURL = $fullBaseUrl . "/buyhotel/book-hotel/data/" . $searchIDSearch;
            $this->view->strErrorURL = $fullBaseUrl . "/buyhotel/review/data/" . $searchIDSearch;
            $this->view->strPayWithPaymentGatewayUrl = Catabatic_Helper::getSiteUrl() . "payment/payment-options/customer-pay";
            $this->view->strReturnURLCustomerPayment = $fullBaseUrl . "/buyhotel/check-flight-payment/data/" . $searchIDSearch;
            $this->view->intPlanType = "1";
            $this->view->strTrxType = "A";

            $Customer = new Zend_Session_Namespace('Customer');
            $this->view->intTpSysId = $intTpSysId = $Customer->intTPSysId;
            $this->view->intCustomerSysId = $intCustomerSysId = $Customer->intCustomerSysId;
        }
    }

    public function verifyingBookingAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $post = $this->getRequest()->getPost();
        $post = json_decode(file_get_contents('php://input'), true);
        $IsOffline = isset($post['IsOffline']) ? $post['IsOffline'] : 0;
        $MasterTPSysId = isset($post['MasterTPSysId']) ? base64_decode($post['MasterTPSysId']) : 0;


        $searchIDSearch = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        $objTempFlight = $objFlight = new Travel_Model_TblFlight();
        if ($IsOffline == 1) {
            $searchIDSearch = $this->view->searchIDSearch = base64_decode($post['searchID']);
            $FlightTempData = $objTempFlight->GetFlightTempDataByTPSysId(($searchIDSearch));
            $TPSysId = ($searchIDSearch);
            $intTPSysId = ($searchIDSearch);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        } else {
            $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
            $TPSysId = $FlightTempData['TPSysId'];
            $intTPSysId = $FlightTempData['TPSysId'];
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        }


        if ($FlightTempData) {

            $SearchParams = $arrUrlData['SearchParams'];
            if ($this->_request->isXmlHttpRequest()) {

                $this->_helper->layout->disableLayout();
                $this->_helper->viewRenderer->setNoRender(true);

                $customHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom');
                $crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
                $crmcustomerObj = new Travel_Model_CRM_Customer();
                $getAgentDetailById = $crmcustomerObj->getAgentDetailById($this->intLoggedinUserId);
                $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinUserAgencySysId);
                $IsAllowFlightBooking = isset($getAgentDetailById[0]['IsAllowFlightBooking']) ? $getAgentDetailById[0]['IsAllowFlightBooking'] : 0;
                $IsCheckWallet = isset($this->agencyDetails['IsCheckWallet']) ? $this->agencyDetails['IsCheckWallet'] : 0;
                $PrimaryContactNo = isset($this->agencyDetails['PrimaryContactNo']) ? trim($this->agencyDetails['PrimaryContactNo']) : 0;
                $countrycode = isset($this->agencyDetails['countrycode']) ? trim($this->agencyDetails['countrycode']) : '+91';
                $MobileNumber = $countrycode . $PrimaryContactNo;
                $LoggedinUserMobileNumber = $countrycode . $this->intLoggedinUserContactNo;


                $withprice = (isset($post['withprice']) && !empty($post['withprice'])) ? 1 : 0;
                $paymentModebyUser = (isset($post['paymentModebyUser']) && !empty($post['paymentModebyUser'])) ? $post['paymentModebyUser'] : 1;
                $travelPlanDetais = $crmcusttravelplan->CheckCustomerWithLeadId($intTPSysId);

                $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;

                $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
                $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
                $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
                $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
                $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;

                $TempOTPDATA = new Zend_Session_Namespace('TempOTPDATA');


                if ($TPSysId && $searchIDSearch) {
                    $TotalBaseFare = 0;
                    $TotalTaxesandFee = 0;
                    $TotalDiscount = 0;
                    $Currncy = '';
                    $TotalCommissionEarned = 0;
                    $TotalFixedMarkUp = 0;
                    $TotalGSTOnMarkUp = 0;
                    $TotalTDSEarn = 0;
                    $BaseFareArray = [];

                    $PostData = ['TPSysId' => $TPSysId];
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    if ($IsOffline == 1) {
                        $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher-offline';
                    } else {
                        $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';
                    }


                    $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                    $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
                    $AdjustmentsAmount = isset($HotelData['HotelData']['AdjustmentsAmount']) ? $HotelData['HotelData']['AdjustmentsAmount'] : 0;
                    $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
                    $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
                    $ICSourceSysId = isset($HotelData['HotelData']['ICSourceSysId']) ? $HotelData['HotelData']['ICSourceSysId'] : 0;
                    $XrefBookingId = isset($HotelData['HotelData']['XrefBookingId']) ? $HotelData['HotelData']['XrefBookingId'] : 0;

                    if ($IsOffline == 1) {
                        $searchIDSearch = $XrefBookingId;
                    }

                    // echo "<pre>post";
                    // print_r(($post));
                    // die;
                    $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $Currncy = $values['Currency'];
                            $BaseFare = ($values['RoomPrice']);
                            $TotalBaseFare += ($values['RoomPrice']);
                            $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                            $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                            $TotalTaxesandFee += (($values['Taxes']));
                            $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                        }
                    }

                    $fare = array(
                        'Currncy' => $Currncy,
                        'BaseFare' => round($TotalBaseFare, 2),
                        'TaxesandFee' => round($TotalTaxesandFee, 2),
                        'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp, 2),
                        'CommissionEarned' => round($TotalCommissionEarned, 2),
                        'TDSEarn' => round($TotalTDSEarn, 2),
                        'Discount' => round($TotalDiscount, 2),
                        'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                        'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                        'roomCoun' => count($accom_room),
                        'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                        'BaseFareArray' => ($BaseFareArray),
                    );
                    $TotalExtraMarkupAgency = 0;
                    $TotalPublishedFare = $fare['GrandTotal'];
                    $intChargeFromWallet = $fare['GrandTotal'];

                    $model = new Gtxwebservices_Model_Webservices();
                    if ($IsB2BCustomer == 1 && $paymentModebyUser == 1) {
                        $intChargeSelling = ($TotalPublishedFare + $TotalExtraMarkupAgency);
                        $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId__);
                        $B2BAgencySysIdKey = $getAgencyDetail['SecurityKey'];
                        $B2CAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
                        $apiDataIV = array(
                            "B2BAgencySysIdKey" => $B2BAgencySysIdKey,
                            "B2CAgencySysIdKey" => $B2CAgencySysIdKey,
                        );

                        $result = json_decode($model->GetB2Bbalance($apiDataIV), true);
                        $B2BwalletBalanceAmount = isset($result['creditBalance']) ? $result['creditBalance'] : 0;

                        if ((float) $B2BwalletBalanceAmount < (float) $intChargeSelling) {
                            $response = array('success' => false, 'message' => 'Agent does not have sufficient Credit Balance. Use Pay Later or Ask agent to top up balance.');
                            echo json_encode($response);
                            exit;
                        }
                    } elseif ($IsEnabledWallet == 1 && $paymentModebyUser == 1) {
                        $apiDataIV = array(
                            "CustomerSysId" => $CustomerSysId,
                        );

                        $result = json_decode($model->GetB2Cbalance($apiDataIV, $this->agencyDetails['SecurityKey']), true);
                        $walletBalanceAmount = (isset($result['WalletBalance'][0]['BalanceAmount']) && !empty($result['WalletBalance'][0]['BalanceAmount'])) ? $result['WalletBalance'][0]['BalanceAmount'] : 0;

                        if ((float) $walletBalanceAmount < (float) $TotalPublishedFare) {
                            $response = array('success' => false, 'message' => 'Agent does not have sufficient Credit Balance. Use Pay Later or Ask customer to top up balance.');
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if (isset($post['verifying']) && $post['verifying'] == 'true' && !empty($post['verifying'])) {
                        $getBooingOTP = $objFlight->getBooingOTP($intTPSysId);
                        if ($this->intLoggedinUserAgencySysId == 1) {
                            $OTPNumber = $TempOTPDATA->params;
                        } else {
                            $OTPNumber = trim($post['OTPNumber']);
                        }
                        $IsProposal = isset($post['IsProposal']) ? $post['IsProposal'] : 0;
                        if ($ICSourceSysId == 9) {
                            $response = array('success' => true, 'checkOTP' => false, 'walletPay' => false, 'trxstatus' => 'success', 'checkpr' => 0, 'PhoneNumberDigit' => '');
                            echo json_encode($response);
                            exit;
                        }

                        ####### In case of quick proposal flight booking start #############
                        if ($IsProposal == 1) {
                            if ($getBooingOTP == $OTPNumber) {
                                $objFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => ''), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);
                                $response = array('success' => true, 'checkOTP' => false, 'walletPay' => false, 'trxstatus' => 'success', 'checkpr' => 0, 'PhoneNumberDigit' => '');
                                echo json_encode($response);
                                exit;
                            } else {
                                $response = array('success' => false, 'message' => 'Invalid otp');
                                echo json_encode($response);
                                exit;
                            }
                        }
                        ####### In case of quick proposal flight booking end #############
                        if ($IsCheckWallet == 1 && $IsAllowFlightBooking == 1) {
                            if ($getBooingOTP == $OTPNumber) {
                                $objFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => ''), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);
                                $response = array('success' => true, 'checkOTP' => false, 'walletPay' => false, 'checkpr' => 0, 'PhoneNumberDigit' => '');
                                echo json_encode($response);
                                exit;
                            } else {
                                $response = array('success' => false, 'message' => 'Invalid otp');
                                echo json_encode($response);
                                exit;
                            }
                        } elseif ($IsCheckWallet == 0 && $IsAllowFlightBooking == 1) {
                            if ($getBooingOTP == $OTPNumber) {
                                $objFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => ''), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);
                                $response = array('success' => true, 'checkOTP' => false, 'walletPay' => true, 'checkpr' => $intChargeFromWallet, 'PhoneNumberDigit' => '');
                                echo json_encode($response);
                                exit;
                            } else {
                                $response = array('success' => false, 'message' => 'Invalid otp');
                                echo json_encode($response);
                                exit;
                            }
                        } elseif ($IsCheckWallet == 0 && $IsAllowFlightBooking == 0) {
                            if ($getBooingOTP == $OTPNumber) {
                                $objFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => ''), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);
                                $response = array('success' => true, 'checkOTP' => false, 'walletPay' => true, 'checkpr' => $intChargeFromWallet, 'PhoneNumberDigit' => '');
                                echo json_encode($response);
                                exit;
                            } else {
                                $response = array('success' => false, 'message' => 'Invalid otp');
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'checkpr' => 0, 'message' => 'Booking not allowed.');
                            echo json_encode($response);
                            exit;
                        }
                    }
                    $request = array(
                        "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                        'TokenAgencyId' => '',
                        'TokenMemberId' => '',
                    );
                    $DataS = array(
                        'apidata' => $request,
                        'memberCount' => 0,
                        'JourneyType' => 0,
                        'interNationalSearch' => false,
                        'searchID' => $searchIDSearch,
                        'ICSourceSysId' => $ICSourceSysId,
                        'APIMode' => ($this->intLoggedinUserAgencySysId == 1) ? 1 : 0
                    );
                    $url = GTX_API_URL . '/flight/v3/getbalnace';
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $CashBalance = (isset($apiResponse['results']) && !empty($apiResponse['results'])) ? (float)$apiResponse['results'] : 0;

                    if ($CashBalance >= (float) ceil($intChargeFromWallet)) {
                    } else {
                        $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'message' => 'Sorry we could not process your booking. Please contact our customer support. (API Insufficient Balance)');
                        echo json_encode($response);
                        exit;
                    }

                    $arrUrlData['withprice'] = $withprice;
                    $arrUrlData['paymentModebyUser'] = $paymentModebyUser;
                    $tempData = array(
                        'TPSysId' => $intTPSysId,
                        'TraceId' => $searchIDSearch,
                        'APIBookingData' => json_encode($arrUrlData),
                    );

                    $objTempFlight->deleteFlightTempData($searchIDSearch);
                    $objTempFlight->insertFlightTempData($tempData);
                    /* OTP setting */
                    $data = new Payment_Model_Checkotp();
                    $generateNumericOTP = $this->generateNumericOTP(6);
                    $TempOTPDATA->params = $generateNumericOTP;
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight/');
                    $html->assign(array('getBooingOTP' => $generateNumericOTP, 'agencyDetails' => $this->agencyDetails));
                    $bodyText = $html->render('OTPEmail.phtml');
                    $fromName = (isset($this->agencyDetails['DisplayName']) && !empty($this->agencyDetails['DisplayName'])) ? trim($this->agencyDetails['DisplayName']) : trim(trim($this->agencyDetails['Title']));
                    $emailData = array(
                        'fromEmail' => $this->intLoggedinUserEmailId,
                        'fromName' => $fromName,
                        'subject' => 'OTP for booking ' . date('Y-m-d H:i:s'),
                        'to' => array($this->intLoggedinUserEmailId),
                        'bodyHtml' => $bodyText,
                        'bodyText' => ''
                    );

                    $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                    $arrEmailStatistics = array(
                        "TPSysId" => 0,
                        "TypeSysId" => 1, // 1 For Email 2 For SMS
                        "AgencySysId" => $this->intLoggedinUserAgencySysId,
                        "AgentSysId" => $this->intLoggedinUserId,
                        "Title" => $bodyText,
                        "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                        "Status" => 0,
                        "RefSysId" => "",
                        "RefSysStatus" => "",
                        "CreateDate" => date('Y-m-d H:i:s')
                    );

                    $objTempFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => $generateNumericOTP), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);

                    $currentDate = date('Y-m-d H:i:s');
                    $dateTime = new DateTime($currentDate);
                    $dateTime->modify('+2 minutes');
                    $RandomCodeValidTo = $dateTime->format('Y-m-d H:i:s');

                    $col = array('RandomCode' => $generateNumericOTP, 'RandomCodeValidFrom' => $currentDate, 'RandomCodeValidTo' => $RandomCodeValidTo);
                    $message = "OTP for CRM access is $generateNumericOTP do not share it with anyone.\nTRVCRM";
                    $postFields = "";
                    $postFields .= "&method=$this->SMSMETHOD";
                    $postFields .= "&api_key=$this->SMSAPIKEY";
                    $postFields .= "&sender=$this->SMSSENDER";
                    $postFields .= "&message=$message";
                    $postFields .= "&format=$this->SMSFORMAT";
                    $postURL = $this->SMSURL;


                    if ($IsCheckWallet == 1 && $IsAllowFlightBooking == 1) {
                        $postFields .= "&to=" . substr($LoggedinUserMobileNumber, -10);
                        $hidePhoneNumberDigit = $customHelper->hidePhoneNumberDigit($LoggedinUserMobileNumber, 1);
                        $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
                        $resultVal = $data->sendSmsDetails($postURL, $postFields, array('AgencySysId' => $this->intLoggedinAgencyId), $this->IsSMSApi);
                        $guid = isset($resultVal['data']['data']['group_id']) ? $resultVal['data']['data']['group_id'] : 'NA';
                        $response = array('success' => true, 'checkOTP' => true, 'walletPay' => false, 'PhoneNumberDigit' => $hidePhoneNumberDigit, 'guid' => $guid, 'trxstatus' => 'success');
                        echo json_encode($response);
                        exit;
                    } elseif ($IsCheckWallet == 0 && $IsAllowFlightBooking == 1) {
                        $postFields .= "&to=" . substr($LoggedinUserMobileNumber, -10);
                        $hidePhoneNumberDigit = $customHelper->hidePhoneNumberDigit($LoggedinUserMobileNumber, 1);
                        $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
                        $resultVal = $data->sendSmsDetails($postURL, $postFields, array('AgencySysId' => $this->intLoggedinAgencyId), $this->IsSMSApi);
                        // echo "<pre>0";print_r($resultVal);exit;
                        $guid = isset($resultVal['data']['data']['group_id']) ? $resultVal['data']['data']['group_id'] : 'NA';
                        $wallet = Zend_Controller_Action_HelperBroker::getStaticHelper('Dashboard')->getWalletPrice($this->intLoggedinAgencyId);
                        $walletBalanceAmount = $wallet[0]['BalanceAmount'];
                        if ($walletBalanceAmount >= $intChargeFromWallet) {
                            $response = array('success' => true, 'checkOTP' => true, 'walletPay' => true, 'PhoneNumberDigit' => $hidePhoneNumberDigit, 'guid' => $guid, 'trxstatus' => 'success');
                            echo json_encode($response);
                            exit;
                        } else {
                            $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'message' => 'You do not have sufficient balance to make this booking. Please recharge before proceed.');
                            echo json_encode($response);
                            exit;
                        }
                    } elseif ($IsCheckWallet == 0 && $IsAllowFlightBooking == 0) {
                        $postFields .= "&to=" . substr($MobileNumber, -10);
                        $hidePhoneNumberDigit = $customHelper->hidePhoneNumberDigit($MobileNumber, 1);
                        $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
                        $resultVal = $data->sendSmsDetails($postURL, $postFields, array('AgencySysId' => $this->intLoggedinAgencyId), $this->IsSMSApi);
                        //echo "<pre>4";print_r($resultVal);exit;
                        $guid = isset($resultVal['data']['data']['group_id']) ? $resultVal['data']['data']['group_id'] : 'NA';
                        $wallet = Zend_Controller_Action_HelperBroker::getStaticHelper('Dashboard')->getWalletPrice($this->intLoggedinAgencyId);
                        $walletBalanceAmount = $wallet[0]['BalanceAmount'];
                        if ($walletBalanceAmount >= $intChargeFromWallet) {
                            $response = array('success' => true, 'checkOTP' => true, 'walletPay' => true, 'PhoneNumberDigit' => $hidePhoneNumberDigit, 'guid' => $guid, 'trxstatus' => 'success');
                            echo json_encode($response);
                            exit;
                        } else {
                            $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'message' => 'You do not have sufficient balance to make this booking. Please recharge before proceed.');
                            echo json_encode($response);
                            exit;
                        }
                    } elseif ($IsCheckWallet == 1 && $IsAllowFlightBooking == 0) {
                        $postFields .= "&to=" . substr($MobileNumber, -10);
                        $hidePhoneNumberDigit = $customHelper->hidePhoneNumberDigit($MobileNumber, 1);
                        $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
                        $resultVal = $data->sendSmsDetails($postURL, $postFields, array('AgencySysId' => $this->intLoggedinAgencyId), $this->IsSMSApi);
                        //echo "<pre>7";print_r($resultVal);exit;
                        $guid = isset($resultVal['data']['data']['group_id']) ? $resultVal['data']['data']['group_id'] : 'NA';
                        $response = array('success' => true, 'checkOTP' => true, 'walletPay' => false, 'PhoneNumberDigit' => $hidePhoneNumberDigit, 'guid' => $guid, 'trxstatus' => 'success');
                        echo json_encode($response);
                        exit;
                    } else {
                        $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'message' => 'Booking not allowed. somethings went wrong!!');
                        echo json_encode($response);
                        exit;
                    }
                    // echo "<pre>post";
                    // print_r(($fare));
                    // die;
                }
            }
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinUserAgencySysId);
            $getAgentDetailById = $crmcustomerObj->getAgentDetailById($this->intLoggedinUserId);
            $this->view->IsAllowFlightBooking = isset($getAgentDetailById[0]['IsAllowFlightBooking']) ? $getAgentDetailById[0]['IsAllowFlightBooking'] : 0;
            $this->view->IsCheckWallet = isset($getAgencyDetail['IsCheckWallet']) ? $getAgencyDetail['IsCheckWallet'] : 0;
            $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
            $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
            $AgencySysId = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
            $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;
            $this->view->IsB2BCustomer = $IsB2BCustomer;
            $this->view->IsEnabledWallet = $IsEnabledWallet;
            $this->view->walletBalanceAmount = '0.00';

            $model = new Gtxwebservices_Model_Webservices();
            if ($IsB2BCustomer == 1) {
                $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId);
                $B2BAgencySysIdKey = $getAgencyDetail['SecurityKey'];
                $B2CAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
                $apiDataIV = array(
                    "B2BAgencySysIdKey" => $B2BAgencySysIdKey,
                    "B2CAgencySysIdKey" => $B2CAgencySysIdKey,
                );

                $result = json_decode($model->GetB2Bbalance($apiDataIV), true);
                $this->view->walletBalanceAmount = $result['creditBalance'];
            } elseif ($IsEnabledWallet == 1) {
                $apiDataIV = array(
                    "CustomerSysId" => $CustomerSysId,
                );

                $result = json_decode($model->GetB2Cbalance($apiDataIV, $this->agencyDetails['SecurityKey']), true);
                $this->view->walletBalanceAmount = (isset($result['WalletBalance'][0]['BalanceAmount']) && !empty($result['WalletBalance'][0]['BalanceAmount'])) ? $result['WalletBalance'][0]['BalanceAmount'] : 0;
            }
            // echo "<pre>post";
            // print_r(($customerDetails));
            // die;
            $this->view->intLoggedinUserId = $this->intLoggedinUserId;
            $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupSysId;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $searchIDSearch;
            $this->view->ActionName = 'review';
        }
    }

    public function bookHotelAction()
    {
        $post = $this->getRequest()->getParams();
        $objFlight = new Travel_Model_TblFlight();
        $IsOffline = $this->view->IsOffline = isset($post['IsOffline']) ? $post['IsOffline'] : 0;
        // 

        if ($IsOffline == 1) {
            $MasterTPSysId = isset($post['MasterTPSysId']) ? base64_decode($post['MasterTPSysId']) : 0;
            $strUrlData = $searchId = $bookingId = $this->view->strUrlData = !empty($this->getRequest()->getParam('strUrlData')) ? base64_decode($this->getRequest()->getParam('strUrlData')) : base64_decode($this->getRequest()->getParam('data'));
            $FlightTempData = $objFlight->GetFlightTempDataByTPSysId(($searchId));
            $this->view->TPSysId = $intTPSysId = $TPSysId = ($strUrlData);
            $intTPSysId = ($strUrlData);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        } else {
            $strUrlData = $searchId = $bookingId = $this->view->strUrlData = !empty($this->getRequest()->getParam('strUrlData')) ? $this->getRequest()->getParam('strUrlData') : $this->getRequest()->getParam('data');
            $FlightTempData = $objFlight->GetFlightTempData($strUrlData);
            $this->view->TPSysId = $intTPSysId = $TPSysId = ($FlightTempData['TPSysId'] > 0) ? $FlightTempData['TPSysId'] : 0;
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        }

        $SearchParams = $arrUrlData['SearchParams'];
        $paymentModebyUser = (isset($arrUrlData['paymentModebyUser']) && !empty($arrUrlData['paymentModebyUser'])) ? $arrUrlData['paymentModebyUser'] : 1;
        $withprice = (isset($arrUrlData['withprice']) && !empty($arrUrlData['withprice'])) ? $arrUrlData['withprice'] : 0;
        $B2BSearch = (isset($arrUrlData['B2BSearch']) && !empty($arrUrlData['B2BSearch'])) ? $arrUrlData['B2BSearch'] : [];
        $IsB2Bproposal = (isset($arrUrlData['IsB2Bproposal']) && !empty($arrUrlData['IsB2Bproposal'])) ? $arrUrlData['IsB2Bproposal'] : 0;

        if ($this->getRequest()->isPost() && $this->_request->isXmlHttpRequest()) {
            /* Disable Layout */
            $paymentMdl = new Payment_Model_Payment();
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $strTrxStatus = !empty($this->getRequest()->getParam('trxstatus')) ? $this->getRequest()->getParam('trxstatus') : $post['status'];
            if ($strTrxStatus == "success") {
                $this->_helper->layout->disableLayout();
                $post = $this->getRequest()->getPost();
                $PostData = ['TPSysId' => $TPSysId];
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';

                $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
                $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
                $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
                $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                $ICSourceSysId = isset($HotelData['HotelData']['ICSourceSysId']) ? $HotelData['HotelData']['ICSourceSysId'] : 0;
                $APIBookingid = isset($HotelData['HotelData']['APIBookingid']) ? $HotelData['HotelData']['APIBookingid'] : 0;
                $BookingRefNo = isset($HotelData['HotelData']['BookingRefNo']) ? $HotelData['HotelData']['BookingRefNo'] : 0;
                $AdjustmentsAmount = isset($HotelData['HotelData']['AdjustmentsAmount']) ? $HotelData['HotelData']['AdjustmentsAmount'] : 0;

                // if (empty($arrUrlData) || ($CurrentStatus == 24)) {
                //     $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => 'This Trace id already expired', 'urlData' => $strUrlData, 'formAction' => "/flight-new/booking-confirmation/data/" . $TPSysId . "");
                //     echo json_encode($response);
                //     exit;
                // }
                // echo "<pre>post";
                // print_r(($HotelData));
                // die;
                $TotalBaseFare = 0;
                $TotalTaxesandFee = 0;
                $TotalDiscount = 0;
                $Currncy = '';
                $TotalCommissionEarned = 0;
                $TotalFixedMarkUp = 0;
                $TotalGSTOnMarkUp = 0;
                $TotalTDSEarn = 0;
                $BaseFareArray = [];
                if ($accom_room) {
                    foreach ($accom_room as $key => $values) {
                        $Currncy = $values['Currency'];
                        $BaseFare = ($values['RoomPrice']);
                        $TotalBaseFare += ($values['RoomPrice']);
                        $TotalDiscount += ($values['Discounts']);
                        $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                        $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                        $TotalTaxesandFee += (($values['Taxes']));
                        $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                    }
                }

                $fare = array(
                    'Currncy' => $Currncy,
                    'BaseFare' => round($TotalBaseFare, 2),
                    'TaxesandFee' => round($TotalTaxesandFee, 2),
                    'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp + $AdjustmentsAmount - $TotalDiscount, 2),
                    'CommissionEarned' => round($TotalCommissionEarned, 2),
                    'TDSEarn' => round($TotalTDSEarn, 2),
                    'Adjustments' => round($AdjustmentsAmount, 2),
                    'Discount' => round($TotalDiscount, 2),
                    'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                    'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                    'roomCoun' => count($accom_room),
                    'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                    'BaseFareArray' => ($BaseFareArray),
                );


                $checkPaymentStatus = $paymentMdl->checkPaymentStatus($this->intLoggedinAgencyId, $intTPSysId);
                $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);

                $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
                $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
                $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
                $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
                $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
                $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;
                $PublishedFare = ($fare['GrandTotal']);
                $B2BWalletbalance = $PublishedFare;

                $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId__);
                $AgentUserDetail = $crmcustomerObj->getAgentDetailById($AgencySysId__);
                $UserSysId = isset($AgentUserDetail[0]['UserSysId']) ? $AgentUserDetail[0]['UserSysId'] : 0;
                $B2BAgencySysIdKey = $getAgencyDetail['SecurityKey'];
                $B2CAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];

                $HotelQueryids = $arrUrlData['HotelQueryids'];
                $TPSysId = $HotelQueryids['arrIds']['TPSysId'];
                $intCustSysId = $HotelQueryids['arrIds']['CustomerSysId'];
                $MasterTPSysId = $HotelQueryids['arrIds']['MasterTPSysId'];
                $VersionId = $HotelQueryids['arrIds']['VersionId'];
                $TrxId = $HotelQueryids['arrIds']['TrxId'];


                $model = new Gtxwebservices_Model_Webservices();
                if ($IsB2BCustomer == 1) {

                    $URL_ = $this->baseUrl . '/webservice/credit-balance/update-credit-balance-for-offline-request/';
                    $updateCreditBalance = array(
                        'B2BAgencySysIdKey' => $B2BAgencySysIdKey,
                        'B2CAgencySysIdKey' => $B2CAgencySysIdKey,
                        'Remark' => 'Hotel Booking ',
                        'Amount' => $B2BWalletbalance,
                        'PlanType' => 2, // for hote
                        'UserSysId' => $UserSysId,
                        'PaymentMode' => 'Online Wallet',
                        'RefrenceNo' => $bookingId,
                        'CurrencyType' => $this->CurrencyId,
                        'FlightTraceId' => $strUrlData,
                        'IsPayLater' => true
                    );

                    $updateBalance = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->DebitFromWallet($updateCreditBalance, $URL_, $AgencySysId__);
                    ///$updateBalance = json_decode('{"status":true,"TransactionId":"A8203FDFD54448B393549481D2B2EDB4","message":""}', 1);
                    $TransactionId = isset($updateBalance['TransactionId']) ? $updateBalance['TransactionId'] : 0;
                    $Paystatus = isset($updateBalance['status']) ? $updateBalance['status'] : 0;
                    $message = isset($updateBalance['message']) ? $updateBalance['message'] : '';
                    if ($Paystatus) {
                        $postFieldArray = array(
                            'MasterTPSysId' => $MasterTPSysId,
                            'TPSysId' => $TPSysId,
                            'TrxId' => $TrxId,
                            'VersionId' => $VersionId,
                            'ErrorCode' => 6,
                            'field' => 'PaymentStatus',
                            'StatusCode' => 22,
                            'XRefBookingId' => '',
                            'APIBookingRes' => '',
                        );
                        $URL = $this->baseUrl . "/gtxwebservices/flight/update-api-payment-failed";
                        $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getHttpRequestArray($postFieldArray, $URL);
                    } else {
                        $response = array('success' => false, 'TrackId' => $strUrlData, 'IsTJFlightAPI' => 0, 'msg' => "Oop's unable to debit from agent wallet. " . $message, 'urlData' => $strUrlData, 'formAction' => "/flight/booking-confirmation/data/" . $strUrlData . "");
                        echo json_encode($response);
                        exit;
                    }
                } elseif ($IsEnabledWallet == 1 && $paymentModebyUser == 1) {
                    $apiDataIV = array(
                        "CustomerSysId" => $CustomerSysId,
                    );

                    $result = json_decode($model->GetB2Cbalance($apiDataIV, $this->agencyDetails['SecurityKey']), true);
                    $walletstatus = (isset($result['status']) && !empty($result['status'])) ? $result['status'] : 0;
                    $walletBalanceAmount = (isset($result['WalletBalance'][0]['BalanceAmount']) && !empty($result['WalletBalance'][0]['BalanceAmount'])) ? $result['WalletBalance'][0]['BalanceAmount'] : 0;
                    if ($walletstatus == 1) {
                        if ($walletBalanceAmount >= $PublishedFare) {
                            $DebitFromWallet = array(
                                'Remark' => 'Hotel Booking ',
                                'Amount' => $PublishedFare,
                                'CustomerSysId' => $CustomerSysId,
                                'PlanType' => 2,
                                'PaymentMode' => 'Online Wallet',
                                'ReferenceNo' => $bookingId,
                                'CurrencyType' => $this->CurrencyId,
                                'FlightTraceId' => $strUrlData,
                            );
                            $URL_ = $this->baseUrl . '/gtxwebservices/customer-wallet/update-b2c-wallet-balance/';
                            $updateBalance = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->B2CDebitFromWallet($DebitFromWallet, $URL_, $this->intLoggedinAgencyId, $this->agencyDetails['SecurityKey']);
                            $TransactionId = isset($updateBalance['TransactionId']) ? $updateBalance['TransactionId'] : 0;
                        } else {
                            $response = array('success' => false, 'TrackId' => $TrackId, 'IsTJFlightAPI' => 0, 'msg' => 'Agent does not have sufficient Credit Balance. Use Pay Later or Ask customer to top up balance.', 'urlData' => $strUrlData, 'formAction' => "/flight/booking-confirmation/data/" . $TrackId . "");
                            echo json_encode($response);
                            exit;
                        }
                    }
                }

                // echo "<pre>post";
                // print_r(($fare));
                // die;

                $bookingrequest = isset($arrUrlData['bookingrequest']) ? $arrUrlData['bookingrequest'] : [];
                $Invoicedata = isset($arrUrlData['Invoicedata']) ? $arrUrlData['Invoicedata'] : [];

                $nights = (int) $SearchParams['hotelTotalNights'];
                $rooms = (int) $SearchParams['hotelTotalRooms'];
                $AdultPax = (int) $SearchParams['totalMemberCount']['AdultPax'];
                $ChildPax = (int) $SearchParams['totalMemberCount']['ChildPax'];
                $MemberCount = ($AdultPax + $ChildPax);
                $CityName = $SearchParams['CityName'];
                $tboCountryCode = $SearchParams['tboCountryCode'];
                if ($tboCountryCode != 'IN') {
                    $interNationalSearch = true;
                } else {
                    $interNationalSearch = false;
                }

                $request = array(
                    "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                    'TokenAgencyId' => '',
                    'TokenMemberId' => '',
                );
                $DataS = array(
                    'apidata' => $request,
                    'memberCount' => 0,
                    'JourneyType' => 0,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $strUrlData,
                    'ICSourceSysId' => $ICSourceSysId,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                );
                if ($IsOffline == 1) {
                    $CashBalance = 999999999;
                } else {
                    $url = GTX_API_URL . '/flight/v3/getbalnace';
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $CashBalance = (isset($apiResponse['results']) && !empty($apiResponse['results'])) ? (float)$apiResponse['results'] : 0;
                }

                if ($CashBalance >= (float) ceil($PublishedFare)) {
                } else {
                    $response = array('success' => false, 'TrackId' => base64_encode($TPSysId), 'msg' => 'Sorry we could not process your booking. Please contact our customer support. (API Insufficient Balance)');
                    echo json_encode($response);
                    exit;
                }
                $APIBookingresponse = [];
                $GTXUpdateresponse = [];
                $DataS = array(
                    "request" => $bookingrequest,
                    "searchID" => $searchId,
                    "MemberCount" => $MemberCount,
                    "destination" => $CityName,
                    "nights" => $nights,
                    "rooms" => $rooms,
                    "PlanType" => 2,
                    "MPType" => 1,
                    "ICSourceSysId" => $ICSourceSysId,
                    "interNationalSearch" => $interNationalSearch,
                    "APIMode" => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                );

                $url = GTX_API_URL . '/hotel/v2/hotelbook';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                if ($IsOffline == 1) {
                    $hotelbook = [];
                    $ResponseStatus = true;
                    $ErrorMessage = 'SUCESS';
                } else {
                    $hotelbook = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $ResponseStatus = isset($hotelbook['status']) ? $hotelbook['status'] : false;
                    $ErrorMessage = isset($hotelbook['message']) ? $hotelbook['message'] : '';
                }
                // echo "hotelbook";
                // print_r(json_encode($hotelbook));
                // echo "DataS";
                // print_r(json_encode($DataS));
                // die;


                if ($ResponseStatus == 1) {
                    if ($IsOffline == 1) {
                        $VoucherStatus = true;
                        $OrderStatus = 'SUCCESS';
                        $ErrorMessage = 'SUCCESS';
                        $status = true;

                        $searchId = $APIBookingid;
                        $BookingId = $APIBookingid;
                        $BookingRefNo = $BookingRefNo;
                        $ConfirmationNo = $BookingRefNo;
                    } else {
                        if ($ICSourceSysId == 3) {
                            $BookingId = $hotelbook['data']['BookResult']['BookingId'];
                            $TraceId = $hotelbook['data']['BookResult']['TraceId'];
                            $BookingRefNo = $hotelbook['data']['BookResult']['BookingRefNo'];
                            $ConfirmationNo = $hotelbook['data']['BookResult']['ConfirmationNo'];
                            $request__['BookingId'] = $BookingId;
                        } else {
                            $BookingId = $hotelbook['data']['bookingId'];
                            $BookingRefNo = $hotelbook['data']['bookingId'];
                            $ConfirmationNo = $hotelbook['data']['bookingId'];
                            $request__['bookingId'] = $BookingId;
                        }

                        $DataSD = array(
                            "request" => $request__,
                            "searchID" => $searchId,
                            "MemberCount" => $MemberCount,
                            "destination" => $CityName,
                            "nights" => $nights,
                            "rooms" => $rooms,
                            "PlanType" => 2,
                            "MPType" => 1,
                            "ICSourceSysId" => $ICSourceSysId,
                            "interNationalSearch" => $interNationalSearch,
                            "APIMode" => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        );

                        $url = GTX_API_URL . '/hotel/v2/hotelbookdetails';
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataSD, $getData, $url);
                        $status = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                        $message = isset($apiResponse['message']) ? $apiResponse['message'] : '';

                        if ($ICSourceSysId == 3) {
                            $VoucherStatus = isset($apiResponse['data']['GetBookingDetailResult']['VoucherStatus']) ? $apiResponse['data']['GetBookingDetailResult']['VoucherStatus'] : false;
                            $OrderStatus = isset($apiResponse['data']['GetBookingDetailResult']['HotelBookingStatus']) ? $apiResponse['data']['GetBookingDetailResult']['HotelBookingStatus'] : '';
                            $ErrorMessage = isset($apiResponse['GetBookingDetailResult']['Error']['ErrorMessage']) ? $apiResponse['GetBookingDetailResult']['Error']['ErrorMessage'] : '';
                        } else {
                            $VoucherStatus = false;
                            $OrderStatus = isset($apiResponse['data']['order']['status']) ? $apiResponse['data']['order']['status'] : 0;
                            $ErrorMessage = isset($apiResponse['errors'][0]['message']) ? $apiResponse['errors'][0]['message'] : '';
                        }
                    }


                    $postFieldArray = [
                        "MasterTPSysId" => $MasterTPSysId,
                        "TPSysId" => $TPSysId,
                        "VersionId" => $VersionId,
                        "XRefBookingId" => $searchId,
                        "APIBookingid" => $BookingId,
                        "TrxId" => $TrxId,
                        "ErrorCode" => 1,
                        "BookingRefNo" => $BookingRefNo,
                        "ConfirmationNo" => $ConfirmationNo,
                        "TrxOrdDocId" => ($paymentModebyUser == 1) ? 19 : 0,
                        "hotelsource" => "API",
                        "AgencySysId" => $this->intLoggedinAgencyId,
                        "APIMode" => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                    ];


                    $InvoiceValue = isset($Invoicedata['InvoiceValue']) ? $Invoicedata['InvoiceValue'] : 0;
                    $Invoicedata['AgentSysId'] = $this->intLoggedinAgencyId;
                    $Invoicedata['InvoiceStatus'] = ($checkPaymentStatus == 1) ? 1 : 5;
                    $Invoicedata['TotalAdvance'] = ($checkPaymentStatus == 1) ? round(($InvoiceValue), 2) : 0;
                    $Invoicedata['TotalDueAmount'] = ($checkPaymentStatus == 1) ? 0 : round(($InvoiceValue), 2);
                    //$OrderStatus = 'PAYMENT_SUCCESS';

                    if ($status == 1 && ($OrderStatus != 'ABORTED' || $OrderStatus != 'Cancelled' || $OrderStatus != 'BookFailed' || $OrderStatus != 'VerifyPrice')) {

                        $InvoiceCreate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->InvoiceCreate($Invoicedata, [], $this->agencyDetails['SecurityKey'], $this->intLoggedinAgencyId);
                        if ($OrderStatus == 'PENDING' || $OrderStatus == 'PAYMENT_SUCCESS') {
                            $postFieldArray['ErrorCode'] = 0;
                        } elseif ($VoucherStatus != 1 && $ICSourceSysId == 3) {
                            $postFieldArray['ErrorCode'] = 0;
                        }

                        $URL = $this->baseUrl . "/gtxwebservices/hotel-api/updatebooking";
                        $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($postFieldArray, $getData, $URL);
                        $GTXUpdateresponse = $result;
                        // echo "<pre>DataS";
                        // print_r(($result));
                        // echo "<pre>DataS";
                        // print_r(($postFieldArray));
                        // die;
                    } else {
                        if ($IsB2BCustomer == 1) {
                            $dataArray = array(
                                'B2BAgencySysIdKey' => $B2CAgencySysIdKey,
                                'B2CAgencySysIdKey' => $B2BAgencySysIdKey,
                                'PaymentMode' => 'Wallet Refund',
                                'Amount' => $B2BWalletbalance,
                                'RefrenceNo' => $bookingId,
                                'CreditDate' => date('Y-m-d'),
                                'Remark' => 'Refund',
                                'PlanType' => 2,
                                'CurrencyType' => $this->CurrencyId,
                                'UserSysId' => $UserSysId,
                                'FlightTraceId' => $strUrlData,
                            );
                            $URL_CREDIT = $this->baseUrl . '/webservice/credit-balance/save-online-request/';
                            $CreditIntoWallet = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->CreditIntoWallet($dataArray, $URL_CREDIT, $AgencySysId__);
                        } elseif ($IsEnabledWallet == 1 && $paymentModebyUser == 1) {
                            $DebitFromWallet = array(
                                'Remark' => 'Refund',
                                'Amount' => $PublishedFare,
                                'CustomerSysId' => $CustomerSysId,
                                'PlanType' => 1,
                                'PaymentMode' => 'Wallet Refund',
                                'ReferenceNo' => $bookingId,
                                'CurrencyType' => $this->CurrencyId,
                                'FlightTraceId' => $strUrlData,
                            );

                            $URL_ = $this->baseUrl . '/gtxwebservices/customer-wallet/add-b2c-wallet-balance/';
                            $CreditIntoWallet = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->B2CDebitFromWallet($DebitFromWallet, $URL_, $this->intLoggedinAgencyId, $this->agencyDetails['SecurityKey']);
                        }

                        $response = array(
                            'MasterTPSysId' => $MasterTPSysId,
                            'TPSysId' => $TPSysId,
                            'TrxId' => $TrxId,
                            'field' => 'BookingStatus',
                            'XRefBookingId' => '',
                            'ErrorCode' => 6,
                            'StatusCode' => 144,
                            'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
                        );
                        $URL = $this->baseUrl . "/gtxwebservices/flight/update-api-payment-failed";
                        $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getHttpRequestArray($response, $URL);
                        $GTXUpdateresponse = $result;
                    }
                } else {
                    if ($IsB2BCustomer == 1) {
                        $dataArray = array(
                            'B2BAgencySysIdKey' => $B2CAgencySysIdKey,
                            'B2CAgencySysIdKey' => $B2BAgencySysIdKey,
                            'PaymentMode' => 'Wallet Refund',
                            'Amount' => $B2BWalletbalance,
                            'RefrenceNo' => $bookingId,
                            'CreditDate' => date('Y-m-d'),
                            'Remark' => 'Refund',
                            'PlanType' => 2,
                            'CurrencyType' => $this->CurrencyId,
                            'UserSysId' => $UserSysId,
                            'FlightTraceId' => $strUrlData,
                        );
                        $URL_CREDIT = $this->baseUrl . '/webservice/credit-balance/save-online-request/';
                        $CreditIntoWallet = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->CreditIntoWallet($dataArray, $URL_CREDIT, $AgencySysId__);
                    } elseif ($IsEnabledWallet == 1 && $paymentModebyUser == 1) {
                        $DebitFromWallet = array(
                            'Remark' => 'Refund',
                            'Amount' => $PublishedFare,
                            'CustomerSysId' => $CustomerSysId,
                            'PlanType' => 1,
                            'PaymentMode' => 'Wallet Refund',
                            'ReferenceNo' => $bookingId,
                            'CurrencyType' => $this->CurrencyId,
                            'FlightTraceId' => $strUrlData,
                        );

                        $URL_ = $this->baseUrl . '/gtxwebservices/customer-wallet/add-b2c-wallet-balance/';
                        $CreditIntoWallet = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->B2CDebitFromWallet($DebitFromWallet, $URL_, $this->intLoggedinAgencyId, $this->agencyDetails['SecurityKey']);
                    }

                    $response = array(
                        'MasterTPSysId' => $MasterTPSysId,
                        'TPSysId' => $TPSysId,
                        'TrxId' => $TrxId,
                        'VersionId' => $VersionId,
                        'ErrorCode' => $ErrorMessage,
                        'StatusType' => 70, /// Query Confirmed
                        'BookingStatus' => 144, // Ticket Failed
                        'PaymentStatus' => ($checkPaymentStatus == 1) ? 22 : 147, // 147 - Pending Payment, 22 - Full Payment
                    );
                    $URL = $this->baseUrl . "/gtxwebservices/hotel-api/update-api-payment-failed";
                    $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getHttpRequestArray($response, $URL);
                    $GTXUpdateresponse = $result;
                }

                $arrUrlData['Bookres'] = $hotelbook;
                $arrUrlData['InvoiceCreate'] = $InvoiceCreate;
                $arrUrlData['GTXUpdateresponse'] = $GTXUpdateresponse;
                $arrUrlData['APIBookingresponse'] = $APIBookingresponse;
                $arrUrlData['walletTransactionId'] = $TransactionId;
                $arrUrlData['CreditIntoWallet'] = $CreditIntoWallet;
                $arrUrlData['message'] = $message;
                $tempData = array(
                    'TPSysId' => $intTPSysId,
                    'TraceId' => $searchId,
                    'APIBookingData' => json_encode($arrUrlData),
                );

                // $objFlight->deleteFlightTempData($searchId);
                $objFlight->insertFlightTempData($tempData);
                $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => $ErrorMessage, 'urlData' => $strUrlData, 'formAction' => "/buyhotel/booking-confirmation/data/" . $searchId . "?status=true");
                echo json_encode($response);
                exit;
                // echo "<pre>DataS"; //
                // print_r(($hotelbook));
                // echo "<pre>DataS";
                // print_r(($DataS));
                // die;
            } else {
                $response = array('success' => false, 'TrackId' => base64_encode($TPSysId), 'msg' => 'Session is already expired', 'urlData' => $strUrlData, 'formAction' => "/buyhotel/booking-confirmation/data/" . $searchId . "?status=true");
                echo json_encode($response);
                exit;
            }
        } else {
            $this->view->status = !empty($this->getRequest()->getParam('status')) ? $this->getRequest()->getParam('status') : '';
            $this->view->strUrlData = $this->view->strUrlData = $this->getRequest()->getParam('data');
            $this->view->TrxSysId = $this->getRequest()->getParam('TrxSysId');
            $this->view->TPSysId = $this->getRequest()->getParam('TPSysId');
            $this->view->guid = $this->getRequest()->getParam('guid');
        }
    }


    public function bookingConfirmationNewAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $param = $this->getRequest()->getParams();
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        if ($searchIDSearch) {

            $PostData = ['TPSysId' => base64_decode($param['data'])];
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';

            // $objTempFlight = new Travel_Model_TblFlight();
            // $FlightTempData = $objTempFlight->GetFlightTempDataByTPSysId(base64_decode($param['data']));

            $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
            $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
            $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
            $BookingStatus = isset($HotelData['HotelData']['BookingStatus']) ? $HotelData['HotelData']['BookingStatus'] : '';
            $XrefBookingId = isset($HotelData['HotelData']['XrefBookingId']) ? $HotelData['HotelData']['XrefBookingId'] : '';
            $AdjustmentsAmount = isset($HotelData['HotelData']['AdjustmentsAmount']) ? $HotelData['HotelData']['AdjustmentsAmount'] : 0;
            $TPSysId = isset($HotelData['HotelData']['TPSysId']) ? $HotelData['HotelData']['TPSysId'] : '';
            $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
            $ICSourceSysId = isset($HotelData['HotelData']['ICSourceSysId']) ? $HotelData['HotelData']['ICSourceSysId'] : 0;
            // echo "<pre>post";
            // print_r(($FlightTempData));
            // echo "<pre>HOTEL_VOUCHER";
            // print_r(($HOTEL_VOUCHER));
            // die;
            if ($this->_request->isXmlHttpRequest()) {

                if ($TPSysId && $searchIDSearch) {
                    $TotalBaseFare = 0;
                    $TotalTaxesandFee = 0;
                    $TotalDiscount = 0;
                    $Currncy = '';
                    $TotalCommissionEarned = 0;
                    $TotalFixedMarkUp = 0;
                    $TotalGSTOnMarkUp = 0;
                    $TotalTDSEarn = 0;
                    $BaseFareArray = [];
                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $Currncy = $values['Currency'];
                            $BaseFare = ($values['RoomPrice']);
                            $TotalBaseFare += ($values['RoomPrice']);
                            $TotalDiscount += ($values['Discounts']);
                            $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                            $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                            $TotalTaxesandFee += (($values['Taxes']));
                            $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                        }
                    }

                    $fare = array(
                        'Currncy' => $Currncy,
                        'BaseFare' => round($TotalBaseFare, 2),
                        'TaxesandFee' => round($TotalTaxesandFee, 2),
                        'GrandTotal' => round(($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp + $AdjustmentsAmount) - $TotalDiscount, 2),
                        'CommissionEarned' => round($TotalCommissionEarned, 2),
                        'TDSEarn' => round($TotalTDSEarn, 2),
                        'Adjustments' => round($AdjustmentsAmount, 2),
                        'Discount' => round($TotalDiscount, 2),
                        'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                        'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                        'roomCoun' => count($accom_room),
                        'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                        'BaseFareArray' => ($BaseFareArray),
                    );
                    echo json_encode([
                        'status' => true,
                        'message' => 'SUCESS',
                        'fare' => $fare,
                        'HotelData' => $HotelData,
                    ]);
                    exit;
                }
            }

            // echo "<pre>post";
            // print_r(($HotelData));
            // die;
            $this->view->intLoggedinUserId = $this->intLoggedinUserId;
            $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupSysId;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $searchIDSearch;
            $this->view->TPSysId = $TPSysId;
            $this->view->PaymentStatus = $PaymentStatus;
            $this->view->CurrentStatus = $CurrentStatus;
            $this->view->BookingStatus = $BookingStatus;
            $this->view->XrefBookingId = $XrefBookingId;
            $this->view->ActionName = 'confirm';
        }
    }
    public function confirmationAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $param = $this->getRequest()->getParams();
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        if ($searchIDSearch) {

            $PostData = ['TPSysId' => base64_decode($param['data'])];
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';

            $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
            $ICSourceSysId = isset($HotelData['HotelData']['ICSourceSysId']) ? $HotelData['HotelData']['ICSourceSysId'] : 0;
            $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
            $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
            $BookingStatus = isset($HotelData['HotelData']['BookingStatus']) ? $HotelData['HotelData']['BookingStatus'] : '';
            $XrefBookingId = isset($HotelData['HotelData']['XrefBookingId']) ? $HotelData['HotelData']['XrefBookingId'] : '';
            $BookingRefNo = isset($HotelData['HotelData']['BookingRefNo']) ? $HotelData['HotelData']['BookingRefNo'] : '';
            $ConfirmationNo = isset($HotelData['HotelData']['ConfirmationNo']) ? $HotelData['HotelData']['ConfirmationNo'] : '';
            $APIBookingid = isset($HotelData['HotelData']['APIBookingid']) ? $HotelData['HotelData']['APIBookingid'] : '';
            $MasterTPSysId = isset($HotelData['HotelData']['MasterTPSysId']) ? $HotelData['HotelData']['MasterTPSysId'] : '';
            $TPSysId = isset($HotelData['HotelData']['TPSysId']) ? $HotelData['HotelData']['TPSysId'] : '';
            $VersionId = isset($HotelData['HotelData']['VersionId']) ? $HotelData['HotelData']['VersionId'] : '';
            $TrxSysId = isset($HotelData['HotelData']['TrxSysId']) ? $HotelData['HotelData']['TrxSysId'] : '';
            $AdjustmentsAmount = isset($HotelData['HotelData']['AdjustmentsAmount']) ? $HotelData['HotelData']['AdjustmentsAmount'] : 0;
            $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
            $ICSourceSysId = isset($HotelData['HotelData']['ICSourceSysId']) ? $HotelData['HotelData']['ICSourceSysId'] : 0;

            if ($this->_request->isXmlHttpRequest()) {

                if ($TPSysId && $searchIDSearch) {
                    if ($CurrentStatus == 21) {
                        if ($ICSourceSysId == 3) {
                            $request__['BookingId'] = $APIBookingid;
                        } else {
                            $request__['bookingId'] = $APIBookingid;
                        }
                        $DataSD = array(
                            "request" => $request__,
                            "searchID" => $XrefBookingId,
                            "MemberCount" => 0,
                            "destination" => '',
                            "nights" => 0,
                            "rooms" => 0,
                            "PlanType" => 2,
                            "MPType" => 1,
                            "ICSourceSysId" => $ICSourceSysId,
                            "interNationalSearch" => false,
                            "APIMode" => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        );

                        $url = GTX_API_URL . '/hotel/v2/hotelbookdetails';
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataSD, $getData, $url);

                        if ($ICSourceSysId == 3) {
                            $VoucherStatus = isset($apiResponse['data']['GetBookingDetailResult']['VoucherStatus']) ? $apiResponse['data']['GetBookingDetailResult']['VoucherStatus'] : false;
                            $OrderStatus = isset($apiResponse['data']['GetBookingDetailResult']['HotelBookingStatus']) ? $apiResponse['data']['GetBookingDetailResult']['HotelBookingStatus'] : '';
                            $OrderStatus = ($OrderStatus == 'Confirmed') ? 'SUCCESS' : '';
                            $ErrorMessage = isset($apiResponse['GetBookingDetailResult']['Error']['ErrorMessage']) ? $apiResponse['GetBookingDetailResult']['Error']['ErrorMessage'] : '';
                        } else {
                            $VoucherStatus = true;
                            $OrderStatus = isset($apiResponse['data']['order']['status']) ? $apiResponse['data']['order']['status'] : 0;
                            $ErrorMessage = isset($apiResponse['errors'][0]['message']) ? $apiResponse['errors'][0]['message'] : '';
                        }

                        // echo "<pre>post";
                        // print_r(($apiResponse));
                        // die('ddd');
                        // $status = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                        // $message = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                        // $OrderStatus = isset($apiResponse['data']['order']['status']) ? $apiResponse['data']['order']['status'] : 0;
                        // $ErrorMessage = isset($apiResponse['errors'][0]['message']) ? $apiResponse['errors'][0]['message'] : '';

                        if ($OrderStatus == 'SUCCESS' && $VoucherStatus == 1) {
                            $postFieldArray = [
                                "MasterTPSysId" => $MasterTPSysId,
                                "TPSysId" => $TPSysId,
                                "VersionId" => $VersionId,
                                "XRefBookingId" => $XrefBookingId,
                                "APIBookingid" => $APIBookingid,
                                "TrxId" => $TrxSysId,
                                "ErrorCode" => 1,
                                "BookingRefNo" => $BookingRefNo,
                                "ConfirmationNo" => $ConfirmationNo,
                                "hotelsource" => "API",
                                "AgencySysId" => $this->intLoggedinAgencyId,
                                "APIMode" => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                            ];
                            $URL = $this->baseUrl . "/gtxwebservices/hotel-api/updatebooking";
                            $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($postFieldArray, $getData, $URL);
                            if (isset($result['status']) && $result['status'] != 1) {
                                echo json_encode([
                                    'status' => false,
                                    'message' => isset($result['message']) ? $result['message'] : '',
                                    'fare' => [],
                                    'vouchered' => true,
                                    'HotelData' => $HotelData,
                                ]);
                                exit;
                            }
                        }

                        $PostData = ['TPSysId' => base64_decode($param['data'])];
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';

                        $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                        $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
                        $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                    }
                    $TotalBaseFare = 0;
                    $TotalTaxesandFee = 0;
                    $TotalDiscount = 0;
                    $Currncy = '';
                    $TotalCommissionEarned = 0;
                    $TotalFixedMarkUp = 0;
                    $TotalGSTOnMarkUp = 0;
                    $TotalTDSEarn = 0;
                    $BaseFareArray = [];
                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $Currncy = $values['Currency'];
                            $BaseFare = ($values['RoomPrice']);
                            $TotalBaseFare += ($values['RoomPrice']);
                            $TotalDiscount += ($values['Discounts']);
                            $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                            $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                            $TotalTaxesandFee += (($values['Taxes']));
                            $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                        }
                    }

                    $fare = array(
                        'Currncy' => $Currncy,
                        'BaseFare' => round($TotalBaseFare, 2),
                        'TaxesandFee' => round($TotalTaxesandFee, 2),
                        'GrandTotal' => round(($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp + $AdjustmentsAmount) - $TotalDiscount, 2),
                        'CommissionEarned' => round($TotalCommissionEarned, 2),
                        'TDSEarn' => round($TotalTDSEarn, 2),
                        'Discount' => round($TotalDiscount, 2),
                        'Adjustments' => round($AdjustmentsAmount, 2),
                        'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                        'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                        'roomCoun' => count($accom_room),
                        'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                        'BaseFareArray' => ($BaseFareArray),
                    );

                    echo json_encode([
                        'status' => true,
                        'message' => 'SUCESS',
                        'fare' => $fare,
                        'vouchered' => false,
                        'HotelData' => $HotelData,
                    ]);
                    exit;
                }
            }

            // echo "<pre>post";
            // print_r(($HotelData['HotelData']));
            // die;
            $this->view->intLoggedinUserId = $this->intLoggedinUserId;
            $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupSysId;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $searchIDSearch;
            $this->view->TPSysId = $TPSysId;
            $this->view->PaymentStatus = $PaymentStatus;
            $this->view->CurrentStatus = $CurrentStatus;
            $this->view->BookingStatus = $BookingStatus;
            $this->view->XrefBookingId = $XrefBookingId;
            $this->view->ActionName = 'confirm';
        }
    }
    public function printvoucherAction()
    {
        $this->_helper->layout->disableLayout();
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $param = $this->getRequest()->getParams();
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');

        if ($searchIDSearch) {

            $PostData = ['TPSysId' => base64_decode($param['data'])];
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';
            $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);

            $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
            $XrefBookingId = isset($HotelData['HotelData']['XrefBookingId']) ? $HotelData['HotelData']['XrefBookingId'] : '';
            $HotelCountry = isset($HotelData['HotelData']['HotelCountry']) ? $HotelData['HotelData']['HotelCountry'] : '';
            $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];


            $url = GTX_API_URL . '/flight/v3/get-agency-term-and-condtions';
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $DataTC = ['AgencySysId' => $this->intLoggedinUserAgencySysId];
            $TermsAndCondition = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataTC, $getData, $url);
            $TCHotelVoucher = isset($TermsAndCondition['results']['TCHotelVoucher']) ? $TermsAndCondition['results']['TCHotelVoucher'] : '';


            $TotalBaseFare = 0;
            $TotalTaxesandFee = 0;
            $TotalDiscount = 0;
            $Currncy = '';
            $TotalCommissionEarned = 0;
            $TotalFixedMarkUp = 0;
            $TotalGSTOnMarkUp = 0;
            $TotalTDSEarn = 0;
            $BaseFareArray = [];
            if ($accom_room) {
                foreach ($accom_room as $key => $values) {
                    $Currncy = $values['Currency'];
                    $BaseFare = ($values['RoomPrice']);
                    $TotalBaseFare += ($values['RoomPrice']);
                    $TotalDiscount += ($values['Discounts']);
                    $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                    $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                    $TotalTaxesandFee += (($values['Taxes']));
                    $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                }
            }

            $fare = array(
                'Currncy' => $Currncy,
                'BaseFare' => round($TotalBaseFare, 2),
                'TaxesandFee' => round($TotalTaxesandFee, 2),
                'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp - $TotalDiscount, 2),
                'CommissionEarned' => round($TotalCommissionEarned, 2),
                'TDSEarn' => round($TotalTDSEarn, 2),
                'Discount' => round($TotalDiscount, 2),
                'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                'roomCoun' => count($accom_room),
                'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                'BaseFareArray' => ($BaseFareArray),
            );

            if (isset($param['email']) && $param['email'] == true) {
                $withprice = $param['withprice'];
                $withcancellation = $param['withcancellation'];
                $EticketEmail = $param['EticketEmail'];
                $objMarkup = new Markup_Model_Markup();
                $_crmcustomerObj = new Travel_Model_CRM_Customer();
                if (!empty(trim($HotelCountry)) && trim($HotelCountry) != "India") {
                    $intAirType = 2;
                } else {
                    $intAirType = 1;
                }
                $arrAgencyUserDetail = $objMarkup->getAgencyUserDetail(array("AgencySysId" => $this->intLoggedinAgencyId, "ItemSourceType" => (int) $intAirType, "PlanType" => 2, 'MarketType' => 1));
                $this->view->arrAgencyUserDetail = $arrAgencyUserDetail;
                $getAgencyDetail = $_crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);
                $fromName = (isset($getAgencyDetail['DisplayName']) && !empty($getAgencyDetail['DisplayName'])) ? trim($getAgencyDetail['DisplayName']) : trim(trim($getAgencyDetail['Title']));
                $emailSendId = trim($getAgencyDetail['PrimaryEmail']);
                $IsBookingEmail = (isset($arrAgencyUserDetail) && !empty($arrAgencyUserDetail['IsBookingEmail'])) ? $arrAgencyUserDetail['IsBookingEmail'] : 0;
                if (isset($arrAgencyUserDetail) && !empty($arrAgencyUserDetail['EmailId']) && $IsBookingEmail == 1) {
                    $ToemailSendId = trim($arrAgencyUserDetail['EmailId']);
                } else {
                    $ToemailSendId = $emailSendId; //$this->intLoggedinUserEmailId; Email Delivered SuccessFully
                }

                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
                $html->assign(array('apiResponse' => $HOTEL_VOUCHER, 'fare' => $fare, 'TCHotelVoucher' => $TCHotelVoucher, 'withcancellation' => $withcancellation, 'withprice' => $withprice));

                $bodyText = $html->render('printvoucher.phtml');

                $emailData = array(
                    'fromEmail' => $ToemailSendId,
                    'fromName' => $fromName,
                    'subject' => 'Hotel Booking Confirmation',
                    'to' => array($EticketEmail),
                    'bodyHtml' => $bodyText,
                    'bodyText' => ''
                );

                $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
                $arrEmailStatistics = array(
                    "TPSysId" => 0,
                    "TypeSysId" => 1, // 1 For Email 2 For SMS
                    "AgencySysId" => $this->intLoggedinAgencyId,
                    "AgentSysId" => $this->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => date('Y-m-d H:i:s')
                );
                $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
                if ($emailResponse['success']) {
                    $response = array('success' => true);
                    echo json_encode($response);
                    exit;
                } else {
                    $response = array('success' => false);
                    echo json_encode($response);
                    exit;
                }
                // echo "<pre>post";
                // print_r(($emailResponse));
                // echo "<pre>post";
                // print_r(($fare));
                // die;
            }


            $this->view->XrefBookingId = $XrefBookingId;
            $this->view->apiResponse = $HOTEL_VOUCHER;
            $this->view->fare = $fare;
            $this->view->TCHotelVoucher = $TCHotelVoucher;
            $this->view->ActionName = 'confirm';
        }
    }
    public function printinvoiceAction()
    {
        $this->_helper->layout->disableLayout();
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $param = $this->getRequest()->getParams();
        $searchIDSearch = $SearchHotelTraceId = $this->view->searchIDSearch = $this->getRequest()->getParam('data');

        if ($searchIDSearch) {

            $PostData = ['TPSysId' => base64_decode($param['data'])];
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher';
            $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);

            $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
            $XrefBookingId = isset($HotelData['HotelData']['XrefBookingId']) ? $HotelData['HotelData']['XrefBookingId'] : '';
            $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];


            $url = GTX_API_URL . '/flight/v3/get-agency-term-and-condtions';
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $DataTC = ['AgencySysId' => $this->intLoggedinUserAgencySysId];
            $TermsAndCondition = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataTC, $getData, $url);
            $FlightInvoice = isset($TermsAndCondition['results']['FlightInvoice']) ? $TermsAndCondition['results']['FlightInvoice'] : '';

            $TotalBaseFare = 0;
            $TotalTaxesandFee = 0;
            $TotalDiscount = 0;
            $Currncy = '';
            $TotalCommissionEarned = 0;
            $TotalFixedMarkUp = 0;
            $TotalGSTOnMarkUp = 0;
            $TotalTDSEarn = 0;
            $BaseFareArray = [];
            if ($accom_room) {
                foreach ($accom_room as $key => $values) {
                    $Currncy = $values['Currency'];
                    $BaseFare = ($values['RoomPrice']);
                    $TotalBaseFare += ($values['RoomPrice']);
                    $TotalDiscount += ($values['Discounts']);
                    $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                    $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                    $TotalTaxesandFee += (($values['Taxes']));
                    $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                }
            }

            $fare = array(
                'Currncy' => $Currncy,
                'BaseFare' => round($TotalBaseFare, 2),
                'TaxesandFee' => round($TotalTaxesandFee, 2),
                'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp - $TotalDiscount, 2),
                'CommissionEarned' => round($TotalCommissionEarned, 2),
                'TDSEarn' => round($TotalTDSEarn, 2),
                'Discount' => round($TotalDiscount, 2),
                'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                'roomCoun' => count($accom_room),
                'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                'BaseFareArray' => ($BaseFareArray),
            );
            // echo "<pre>post";
            // print_r(($TermsAndCondition));
            // die;

            $this->view->XrefBookingId = $XrefBookingId;
            $this->view->apiResponse = $HOTEL_VOUCHER;
            $this->view->fare = $fare;
            $this->view->FlightInvoice = $FlightInvoice;
            $this->view->ActionName = 'confirm';
        }
    }
    public function generateNumericOTP($n)
    {
        $generator = "1357902468";
        $result = "";

        for ($i = 1; $i <= $n; $i++) {
            $result .= substr($generator, (rand() % (strlen($generator))), 1);
        }
        // Return result
        return $result;
    }
    public function getApiHotelInfoAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        //$this->_helper->layout->disableLayout();


        if ($this->_request->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);
            $searchID = $post['hotelData']['SearchHotelTraceId'];
            $searchIDSearch = $post['searchID'];
            $objTempFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            $B2BSearch = $arrUrlData['B2BSearch'];
            $hotelCityTitle = $SearchParams['hotelCityTitle'];
            $nights = (int) $SearchParams['hotelTotalNights'];
            $rooms = (int) $SearchParams['hotelTotalRooms'];
            $tboCountryCode = $SearchParams['tboCountryCode'];
            $AdultPax = (int) $SearchParams['totalMemberCount']['AdultPax'];
            $ChildPax = (int) $SearchParams['totalMemberCount']['ChildPax'];
            $MemberCount = ($AdultPax + $ChildPax);
            $hotelCityTitle = $SearchParams['hotelCityTitle'];
            $HotelId = $post['hotelData']['HotelId'];
            $ICSourceSysId = $post['hotelData']['ICSourceSysId'];
            if ($tboCountryCode != 'IN') {
                $interNationalSearch = true;
            } else {
                $interNationalSearch = false;
            }

            $request = [
                'request' => ['id' => $HotelId],
                'searchID' => $searchID,
                'MemberCount' => $MemberCount,
                'destination' => $hotelCityTitle,
                'nights' => $nights,
                'rooms' => $rooms,
                'ICSourceSysId' => $ICSourceSysId,
                'PlanType' => 2,
                'MPType' => 1,
                'B2B' => $B2BSearch,
                'interNationalSearch' => $interNationalSearch,
                'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
            ];

            $SecurityKey = $this->agencyDetails['SecurityKey'];
            //$SecurityKey = 'F38C55F4-5771-4EED-AAB2-D1CE094AEB4E';
            Zend_Session::namespaceUnset('HotelDetails_' . $HotelId . ' ');
            if ($ICSourceSysId == 7) {
                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getHotelDetails($request, $SecurityKey);
                $HotelDetails = new Zend_Session_Namespace('HotelDetails_' . $HotelId . ' ');
                $HotelDetails->params = $apiResponse;
            } else {
                $apiResponse['status'] = true;
                $apiResponse['message'] = 'SUCCESS';
                $apiResponse['RoomInfo'] = $post['hotelData']['HotelRoomFaciality'];
                $apiResponse['RoomCombinations'] = [];
                $apiResponse['roomGroupby'] = [];
                $apiResponse['HotelDetails'] = $post['hotelData']['HotelDetails'];
                $HotelDetails = new Zend_Session_Namespace('HotelDetails_' . $HotelId . ' ');
                $HotelDetails->params = $apiResponse;
            }

            // echo "<pre>";
            // print_r(($HotelId));
            // echo "<pre>";
            // print_r(($HotelDetails->params));
            // die;
            $ResponseStatus = $apiResponse['status'];
            if ($ResponseStatus == 1) {
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
                $html->assign(array('apiResponse' => $apiResponse, 'post' => $post));
                $bodyText = $html->render('getapihotelinfo.phtml');
                echo json_encode(['status' => true, 'message' => 'SUCESS', 'bodyText' => $bodyText, 'apiResponse' => $apiResponse, 'post' => $post]);
                exit;
            } else {
                echo json_encode(['status' => false, 'message' => 'Not found']);
                exit;
            }
        }

        // $objHotel = new Travel_Model_TblBuyHotel();
        // // For Hotel Basic Details From DB...
        // $arrHotelAminity = $objHotel->getHotelMappedAmenities($HotelCode);
        // $this->view->arrhotelAminity = $arrHotelAminity;
        // $this->render('api-room-detail-info');
        // exit;
    }
    public function selecthotelsAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        //$this->_helper->layout->disableLayout();
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        if ($this->_request->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);
            $dataArr = isset($post['dataArr']) ? $post['dataArr'] : [];
            $searchID = $post['searchID'];
            $addMarkup = $post['addMarkup'];
            $discount = $post['discount'];

            $finModel = new Finance_Model_Finance();
            $getTaxSettingDetail = $finModel->getAllDefaultTaxSetting($this->intLoggedinUserAgencySysId, 0, 2);
            $TaxPercentage = (isset($getTaxSettingDetail[0]['TaxPercentage']) && $getTaxSettingDetail[0]['TaxPercentage']) ? (int) $getTaxSettingDetail[0]['TaxPercentage'] : 0;
            $objTempFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objTempFlight->GetFlightTempData($searchID);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            // echo "<pre>";
            // print_r(($dataArr));
            // die;
            $sss = 0;
            if (!empty($dataArr)) {
                $selectedRoom = [];
                foreach ($dataArr as $key => $value) {
                    $explode = explode('____', $value);
                    $HotelId = $explode[0];
                    $RoomID = $explode[1];
                    $HotelDetails = new Zend_Session_Namespace('HotelDetails_' . $HotelId . ' ');
                    $RoomInfo = $HotelDetails->params['RoomInfo'];
                    $HotelDetailsData = $HotelDetails->params['HotelDetails'];
                    // echo "<pre>";
                    // print_r(('HotelDetails_' . $HotelId . ' '));
                    // echo "<pre>";
                    // print_r(($dataArr));
                    // echo "<pre>";
                    // print_r(($HotelDetails->params));
                    // die;
                    if ($RoomInfo) {
                        foreach ($RoomInfo as $RoomVal) {

                            if ($RoomVal['Index'] == $RoomID) {
                                $RoomValArray = [];

                                if ($RoomVal['Rooms']) {
                                    foreach ($RoomVal['Rooms'] as $rooKey => $rooms) {
                                        $ExtraMarkup = (isset($addMarkup[$sss]) && !empty($addMarkup[$sss])) ? $addMarkup[$sss] : 0;
                                        $discountVal = (isset($discount[$sss]) && !empty($discount[$sss])) ? $discount[$sss] : 0;
                                        $intAmount = (float) $ExtraMarkup;
                                        $ExtraMarkupOnGST = (($intAmount * $TaxPercentage) / 100);

                                        $RoomValArray['Rooms'][$rooKey] = $rooms;
                                        $RoomValArray['Rooms'][$rooKey]['ExtraMarkup'] = $ExtraMarkup;
                                        $RoomValArray['Rooms'][$rooKey]['ExtraMarkupOnGST'] = $ExtraMarkupOnGST;
                                        $RoomValArray['Rooms'][$rooKey]['discountVal'] = $discountVal;
                                        $sss++;
                                    }
                                }

                                $selectedRoom[$HotelId]['room'][] = $RoomValArray;
                            }
                        }
                    }
                    $selectedRoom[$HotelId]['HotelDetailsData'] = $HotelDetailsData;
                }
                // echo "<pre>";
                // echo json_encode($selectedRoom);
                // die;
            }

            // echo "<pre>";
            // print_r($selectedRoom);
            // die;

            $finModel = new Finance_Model_Finance();
            $getTaxSettingDetail = $finModel->getAllTaxSetting($this->intLoggedinUserAgencySysId, 2);
            // echo "<pre>";
            // print_r($getTaxSettingDetail);
            // die;

            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
            $html->assign(array('selectedRoom' => $selectedRoom, 'dataArr' => $dataArr, 'getTaxSettingDetail' => $getTaxSettingDetail));
            $bodyText = $html->render('selecthotels.phtml');
            echo json_encode(['status' => true, 'message' => 'SUCESS', 'bodyText' => $bodyText]);
            exit;
        }
    }

    public function json_validate(string $json): bool
    {
        if (empty($json)) {
            return false; // Empty strings are not valid JSON
        }
        json_decode($json);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    public function savePassengerAction()
    {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        if ($this->getRequest()->isXmlHttpRequest()) {
            $param = $this->getRequest()->getPost();

            try {

                $objFlight = new Travel_Model_TblFlight();
                $objBuyHotel = new Travel_Model_TblBuyHotel();
                $accom_room = isset($param['accom_room']) ? json_decode($param['accom_room'], 1) : [];
                $email_id = isset($param['email_id']) ? $param['email_id'] : '';
                $mobile_number = isset($param['mobile_number']) ? $param['mobile_number'] : 0;
                $currencytype = isset($param['currencytype']) ? $param['currencytype'] : 0;
                $supplier_id = isset($param['supplier_id']) ? $param['supplier_id'] : 0;
                $VersionId = isset($param['TPIntSysId']) ? $param['TPIntSysId'] : 0;
                $FixedMarkUp = isset($param['FixedMarkUp']) ? $param['FixedMarkUp'] : 0;
                $GSTOnMarkUp = isset($param['GSTOnMarkUp']) ? $param['GSTOnMarkUp'] : 0;
                $AdjustmentsAmount = isset($param['Adjustments']) ? $param['Adjustments'] : 0;
                $paynow = isset($param['paynow']) ? $param['paynow'] : 0;
                $currency = isset($param['currency']) ? $param['currency'] : 'INR';
                $ConfirmationNo = isset($param['ConfirmationNo']) ? $param['ConfirmationNo'] : '';
                $TPSysId = isset($param['searchID']) ? base64_decode($param['searchID']) : 0;
                $MasterTPSysId = isset($param['MasterTPSysId']) ? base64_decode($param['MasterTPSysId']) : 0;
                $ARR_SALUTIONTBO = unserialize(ARR_SALUTIONTBO);

                $PostData = ['TPSysId' => ($TPSysId), 'MasterTPSysId' => ($MasterTPSysId)];
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher-offline';
                $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];

                if (empty($supplier_id) && $paynow == 1) {
                    $response = array('success' => false, 'message' => 'Please enter supplier.', 'index' => 'supplier_id');
                    echo json_encode($response);
                    exit;
                }
                if (empty($ConfirmationNo) && $paynow == 1) {
                    $response = array('success' => false, 'message' => 'Please enter Confirmation No.', 'index' => 'ConfirmationNo');
                    echo json_encode($response);
                    exit;
                }

                //$arrUrlData['gstData'] = $gstData;
                // echo "<pre>TPSysId";
                // print_r(($TPSysId));

                $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
                $ARR_SALUTION_CHILD = array_flip($ARR_SALUTIONTBO);
                $TaxesTotal = 0;
                $NetCost = 0;
                if ($accom_room) {
                    $email_id = isset($HotelData['HotelData']['EmailId']) ? $HotelData['HotelData']['EmailId'] : '';
                    $mobile_number = isset($HotelData['HotelData']['Contacts']) ? $HotelData['HotelData']['Contacts'] : 0;
                    $VersionId = isset($HotelData['HotelData']['VersionId']) ? $HotelData['HotelData']['VersionId'] : 0;
                    $TrxSysId = isset($HotelData['HotelData']['TrxSysId']) ? $HotelData['HotelData']['TrxSysId'] : 0;

                    if ($paynow == 1) {
                        $dataRoomDel['IsMarkForDel'] = 1;
                        $objBuyHotel->updateAccomRoomByTPSysId($dataRoomDel, $TPSysId);
                    }
                    $roomCount = count($accom_room);

                    foreach ($accom_room as $k => $val) {
                        $Discounts = isset($val['Discounts']) ? $val['Discounts'] : 0;
                        $RoomVersionId = $val['VersionId'];
                        $RoomPrice = isset($param['RoomPrice-' . $k]) ? trim($param['RoomPrice-' . $k]) : 0;
                        $RoomTaxes = isset($param['RoomTaxes-' . $k]) ? trim($param['RoomTaxes-' . $k]) : 0;
                        $AgencyMarkUp = ($FixedMarkUp / $roomCount);
                        $GSTOnAgencyMarkUp = ($GSTOnMarkUp / $roomCount);
                        $TaxesTotal += ($RoomTaxes);
                        $NetCost += (($RoomPrice + $AgencyMarkUp + $GSTOnAgencyMarkUp) - $Discounts);
                        $dataRoom = array(
                            "CurrencyType" => $currencytype,
                            "Currency" => $currency,
                            "TotalPrice" => (($RoomPrice + $RoomTaxes + $AgencyMarkUp + $GSTOnAgencyMarkUp) - $Discounts),
                            "RoomPrice" => $RoomPrice,
                            "AgencyMarkUp" => $AgencyMarkUp,
                            "GSTOnAgencyMarkUp" => $GSTOnAgencyMarkUp,
                            "Taxes" => $RoomTaxes,
                            "IsMarkForDel" => 0,
                        );

                        $objBuyHotel->updateAccomRoomDetail($dataRoom, $RoomVersionId);

                        foreach ($val['customer'] as $i => $value) {
                            $CustomerSysId = $value['CustomerSysId'];
                            $paxType = $value['paxType'];
                            $firstName = $fname = trim($param['fname-' . $k . '-' . $i]);
                            $lastName = trim($param['lname-' . $k . '-' . $i]);
                            $relation = 9; //$data['relation-' . $i];
                            $salutation = trim($param['title-' . $k . '-' . $i]);
                            $panno = trim($param['panno-' . $k . '-' . $i]);
                            $TPPaxSysId = $param['TPPaxSysId-' . $k . '-' . $i];
                            // $memberData['relation'] = $relation;

                            if ($paynow == 1) {
                                if (empty($salutation)) {
                                    $response = array('success' => false, 'message' => 'Please select title.', 'index' => 'title-' . $k . '-'  . $i);
                                    echo json_encode($response);
                                    exit;
                                }
                                if (empty($firstName)) {
                                    $response = array('success' => false, 'message' => 'Please enter first name.', 'index' => 'fname-' . $k . '-'  . $i);
                                    echo json_encode($response);
                                    exit;
                                }

                                if (empty($lastName)) {
                                    $response = array('success' => false, 'message' => 'Please enter last name.', 'index' => 'lname-' . $k . '-'  . $i);
                                    echo json_encode($response);
                                    exit;
                                }
                                if (!empty($panno)) {
                                    $pattern = "/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/";
                                    if (!preg_match($pattern, $panno) && $value['paxType'] == 1) {
                                        $response = array('success' => false, 'message' => 'Enter valid PAN number.', 'index' => 'panno-' . $k . '-'  . $i);
                                        echo json_encode($response);
                                        exit;
                                    }
                                }
                            }

                            if ($paxType == 1) {
                                $memberData['Title'] = isset($ARR_SALUTION[$salutation]) ? $ARR_SALUTION[$salutation] : 0;
                                $memberData['Salutation'] = isset($ARR_SALUTION[$salutation]) ? $ARR_SALUTION[$salutation] : 0;
                            } else {
                                $memberData['Title'] = isset($ARR_SALUTION[$salutation]) ? $ARR_SALUTION_CHILD[$salutation] : 0;
                                $memberData['Salutation'] = isset($ARR_SALUTION[$salutation]) ? $ARR_SALUTION_CHILD[$salutation] : 0;
                            }


                            $memberData['panno'] = $panno;
                            $memberData['FirstName'] = $firstName;
                            $memberData['LastName'] = $lastName;
                            // $memberData['name'] = $firstName . ' ' . $lastName;
                            if (!empty($firstName) && !empty($lastName)) {
                                $memberUpdate = [
                                    'EmailId' => $email_id,
                                    'Contacts' => $mobile_number,
                                    'Title' => $salutation,
                                    'Relation' => $relation,
                                    'FirstName' => $firstName,
                                    'LastName' => $lastName,
                                    'PanCard' => $panno,
                                    'CustomerSysId' => $CustomerSysId,
                                    'paxType' => $paxType,
                                    'AgencySysId' => $this->intLoggedinUserAgencySysId,
                                    'UpdateDate' => date('Y-m-d H:i:s'),
                                    'RegisterDate' => date('Y-m-d H:i:s'),
                                    'IsApproved' => 0,
                                    'IsActive' => 1,
                                    'IsMarkForDelete' => '0',
                                ];

                                $member = [
                                    'FirstName' => $firstName,
                                    'LastName' => $lastName,
                                    'CustomerSysId' => $CustomerSysId,
                                    'AgencySysId' => $this->intLoggedinUserAgencySysId,
                                ];
                                // echo "<pre>";
                                // print_r(($TPPaxSysId));
                                // echo "<pre>memberUpdate";
                                // print_r(($memberUpdate));
                                $MemberSysId = $objFlight->checkMemberWithName($member);
                                if (!empty($MemberSysId) && $MemberSysId > 0) {
                                    $objFlight->updateCustomerMember($memberUpdate, $MemberSysId);
                                    $memberData['MemberSysId'] = $MemberSysId;
                                    $objFlight->updateTravelPlanPax($memberData, $TPPaxSysId);
                                } else {
                                    $MemberSysIds = $objFlight->addCustomerMember($memberUpdate);
                                    $memberData['MemberSysId'] = $MemberSysIds;
                                    $objFlight->updateTravelPlanPax($memberData, $TPPaxSysId);
                                }
                            }
                        }
                    }


                    if ($VersionId > 0 && $currencytype > 0) {
                        $dataAccom = array(
                            "CurrencyType" => $currencytype,
                            "TotalCost" => ($NetCost - ($FixedMarkUp + $GSTOnMarkUp)),
                            "NetCost" => $NetCost,
                            "Taxes" => $TaxesTotal,
                            "AgencyMarkUp" => $FixedMarkUp,
                            "AgentServiceTaxAmount" => $GSTOnMarkUp,
                            "AdjustmentsAmount" => $AdjustmentsAmount,
                            "BookingRefNo" => $ConfirmationNo,
                            "ConfirmationNo" => $ConfirmationNo,
                        );
                        $objBuyHotel->updateB2CBookingDetails($dataAccom, $VersionId);
                        $dataTB_Trx['CurrencyType'] = $currencytype;
                        $objFlight->updatetbtrx($dataTB_Trx, $TrxSysId);
                    }

                    if ($supplier_id > 0) {
                        $updateTP['SupplierSysId'] = $supplier_id;
                        $updateTP['CurrencyType'] = $currencytype;
                        $updateTP['Price'] = (($NetCost + $TaxesTotal) - ($FixedMarkUp + $GSTOnMarkUp));
                        $updateTP['NetPrice'] = $NetCost + $TaxesTotal;
                        $updateTP['TotalCost'] = $NetCost + $TaxesTotal;
                        $updateTP['AgencyMarkUp'] = $FixedMarkUp;
                        $updateTP['AgentServiceTaxAmount'] = $GSTOnMarkUp;

                        $objFlight->updateBookingStatusTravelPlan($updateTP, $TPSysId, $MasterTPSysId);
                    }
                }
                if ($paynow == 1) {
                    $MasterTPSysId = $this->view->MasterTPSysId = $this->getRequest()->getParam('MasterTPSysId');
                    $FlightTempData = $objFlight->GetFlightTempDataByTPSysId(base64_decode($MasterTPSysId));
                    //$TPSysId = $FlightTempData['TPSysId'];
                    $TraceId = $FlightTempData['TraceId'];
                    $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
                    $HotelQueryid = isset($arrUrlData['HotelQueryid'][$TPSysId]) ? $arrUrlData['HotelQueryid'][$TPSysId] : [];
                    $Invoicedata = isset($arrUrlData['Invoicedata'][$TPSysId]) ? $arrUrlData['Invoicedata'][$TPSysId] : [];
                    $arrUrlData['HotelQueryids'] = $HotelQueryid;
                    $arrUrlData['Invoicedata'] = $Invoicedata;


                    //$TPSysId = $FlightTempData['TPSysId'];
                    $tempData = array(
                        'TraceId' => $TraceId,
                        'TPSysId' => ($TPSysId),
                        'APIBookingData' => json_encode($arrUrlData),
                    );
                    $objFlight->insertFlightTempData($tempData);
                }
                $response = array('success' => true, 'message' => 'SUCCESS');
                echo json_encode($response);
                exit;
            } catch (Exception $e) {
                $response = array('success' => false, 'message' => $e->getMessage());
                echo json_encode($response);
                exit;
            }
        }
    }
    public function savePassengerDetailsAction()
    {
        if ($this->getRequest()->isXmlHttpRequest()) {
            // ini_set('display_errors', 1);
            // ini_set('display_startup_errors', 1);
            // error_reporting(E_ALL);
            $objFlight = new Travel_Model_TblFlight();
            $this->_helper->layout->disableLayout();
            $post = json_decode(file_get_contents('php://input'), true);
            parse_str($post['data'], $data);

            $memberDetails = isset($post['travellers']) ? $post['travellers'] : [];
            $countryCodeISO = strtoupper($data['countryCodeISO']);
            $countrycode = $countryCode = $data['countrycode'];
            $mobileNumber = $leadMobile = $data['mobile_number'];
            $email_id = $leadEmail = $data['email_id'];
            $airline_number = $data['airline_number'];
            $airline_email = $data['airline_email'];
            $specialrequest = $data['specialrequest'];
            $isgstapply = $data['isgstapply'];
            $gstnnumber = $data['gstnnumber'];
            $companyname = $data['companyname'];
            $gstemail = $data['gstemail'];
            $gstphone = $data['gstphone'];
            $gstaddress = $data['gstaddress'];
            $gststate = $data['gststate'];
            $searchIDSearch = $BookingID = $post['searchids'];
            // echo "<pre>post";
            // print_r(($data));
            // die;
            $objTempFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objTempFlight->GetFlightTempData($searchIDSearch);
            $TPSysId = $FlightTempData['TPSysId'];
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $hoteldetails = $arrUrlData['hoteldetails'];
            if (empty($airline_number)) {
                $response = array('success' => false, 'message' => 'Please enter hotel number.', 'index' => 'airline_number');
                echo json_encode($response);
                exit;
            }
            if (strlen($airline_number) != 10 && strlen($airline_number) != 11) {
                $response = array('success' => false, 'message' => 'Please enter a hotel hotel number.', 'index' => 'airline_number');
                echo json_encode($response);
                exit;
            }
            if (empty($mobileNumber)) {
                $response = array('success' => false, 'message' => 'Please enter mobile number.', 'index' => 'airline_number');
                echo json_encode($response);
                exit;
            }

            if (empty($airline_email)) {
                $response = array('success' => false, 'message' => 'Please enter hotel Email ID.', 'index' => 'airline_email');
                echo json_encode($response);
                exit;
            }
            if (!filter_var($airline_email, FILTER_VALIDATE_EMAIL)) {
                $msg = "Hotel Email address is not valid.";
                $response = array('success' => false, 'message' => $msg, 'index' => 'airline_email');
                echo json_encode($response);
                exit;
            }

            if (strlen($mobileNumber) != 10 && strlen($mobileNumber) != 11) {
                $response = array('success' => false, 'message' => 'Please enter a valid mobile number.', 'index' => 'mobile_number');
                echo json_encode($response);
                exit;
            }
            if (empty($email_id)) {
                $response = array('success' => false, 'message' => 'Please enter Email ID.', 'index' => 'email_id');
                echo json_encode($response);
                exit;
            }

            if (!filter_var($email_id, FILTER_VALIDATE_EMAIL)) {
                $msg = "Email address is not valid.";
                $response = array('success' => false, 'message' => $msg, 'index' => 'email_id');
                echo json_encode($response);
                exit;
            }

            $memberData = [];
            if ($memberDetails) {
                foreach ($memberDetails as $k => $val) {
                    foreach ($val['memberDetails'] as $i => $value) {
                        $firstName = $fname = $data['fname-' . $k . '-' . $i];
                        $lastName = $data['lname-' . $k . '-' . $i];
                        $relation = 9; //$data['relation-' . $i];
                        $salutation = $data['title-' . $k . '-' . $i];
                        $panno = $data['panno-' . $k . '-' . $i];

                        // echo "<pre>";
                        // print_r(($k . '-' . $i));
                        // echo "</pre>";
                        // die;
                        //$passengerDob = isset($data['dob-' . $k . '-' . $i]) ? $data['dob-' . $k . '-' . $i] : '';
                        $nationality = ''; //isset($data['passenger-nationality-' . $k . '-' . $i]) ? $data['passenger-nationality-' . $k . '-' . $i] : '';
                        $passengerPassportNo = isset($data['passno-' . $k . '-' . $i]) ? $data['passno-' . $k . '-' . $i] : '';
                        $PassportExpiry = isset($data['passexp-' . $k . '-' . $i]) ? $data['passexp-' . $k . '-' . $i] : '';
                        $passporIssue = isset($data['passisse-' . $k . '-' . $i]) ? $data['passisse-' . $k . '-' . $i] : '';
                        //$passengerDob = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($passengerDob, 'd/m/y');
                        $passporIssue = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($passporIssue, 'd/m/y');
                        $PassportExpiry = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($PassportExpiry, 'd/m/y');

                        $memberData[$k][$i] = $value;
                        $memberData[$k][$i]['relation'] = $relation;
                        $memberData[$k][$i]['title'] = $salutation;
                        $memberData[$k][$i]['panno'] = $panno;
                        $memberData[$k][$i]['passno'] = $passengerPassportNo;
                        $memberData[$k][$i]['passisse'] = $passporIssue;
                        $memberData[$k][$i]['passexp'] = $PassportExpiry;
                        $memberData[$k][$i]['passnational'] = $nationality;
                        $memberData[$k][$i]['fname'] = $firstName;
                        $memberData[$k][$i]['lname'] = $lastName;
                        $memberData[$k][$i]['name'] = $firstName . ' ' . $lastName;
                        //$memberData[$k][$i]['dob'] = $passengerDob;
                        $memberData[$k][$i]['countrycode'] = $countrycode;
                        $memberData[$k][$i]['countryCodeISO'] = $countryCodeISO;

                        if (empty($salutation)) {
                            $response = array('success' => false, 'message' => 'Please select title.', 'index' => 'title-' . $k . '-'  . $i);
                            echo json_encode($response);
                            exit;
                        }
                        if (empty($firstName)) {
                            $response = array('success' => false, 'message' => 'Please enter first name.', 'index' => 'fname-' . $k . '-'  . $i);
                            echo json_encode($response);
                            exit;
                        }

                        if (empty($lastName)) {
                            $response = array('success' => false, 'message' => 'Please enter last name.', 'index' => 'lname-' . $k . '-'  . $i);
                            echo json_encode($response);
                            exit;
                        }
                        $pattern = "/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/";
                        if ($value['PaxType'] == 1 && $value['IsPAN'] == 1 && empty($panno)) {
                            $response = array('success' => false, 'message' => 'Please enter PAN number.', 'index' => 'panno-' . $k . '-'  . $i);
                            echo json_encode($response);
                            exit;
                        }
                        if (!preg_match($pattern, $panno) && $value['PaxType'] == 1 && $value['IsPAN'] == 1) {
                            $response = array('success' => false, 'message' => 'Enter valid PAN number.', 'index' => 'panno-' . $k . '-'  . $i);
                            echo json_encode($response);
                            exit;
                        }

                        if ($value['IsPassM'] == 1) {
                            if (empty($passengerPassportNo)) {
                                $response = array('success' => false, 'message' => 'Please enter Passpost number.', 'index' => 'passno-' . $k . '-'  . $i);
                                echo json_encode($response);
                                exit;
                            }
                            if (empty($passporIssue)) {
                                $response = array('success' => false, 'message' => 'Please enter Passpost Issue Date.', 'index' => 'passisse-' . $k . '-'  . $i);
                                echo json_encode($response);
                                exit;
                            }
                            if (empty($PassportExpiry)) {
                                $response = array('success' => false, 'message' => 'Please enter Passpost Expiry Date.', 'index' => 'passexp-' . $k . '-'  . $i);
                                echo json_encode($response);
                                exit;
                            }
                        }
                    }
                }
            }

            $ForCustomerSession = [];
            if ($memberData) {
                foreach ($memberData as $keyss => $value) {
                    foreach ($value as $key => $val) {
                        $ForCustomerSession[] = $val;
                    }
                }
            }

            $ICSourceSysId = $hoteldetails['HotelDetails']['ICSourceSysId'];
            $currencySysId = isset($hoteldetails['HotelDetails']['currencySysId']) ? $hoteldetails['HotelDetails']['currencySysId'] : 1;
            $Currency = isset($hoteldetails['HotelDetails']['Currency']) ? $hoteldetails['HotelDetails']['Currency'] : '';

            $SearchParams = $arrUrlData['SearchParams'];
            $tboCountryCode = $SearchParams['tboCountryCode'];
            $memberDetailsSearch = $SearchParams['memberDetails'];
            $hotelTotalNights = $SearchParams['hotelTotalNights'];
            $cityId = $SearchParams['tboCityId'];
            $hotelXrefCityId = $SearchParams['hotelXrefCityId'];
            $CityName = $SearchParams['CityName'];
            $countrySysId = $SearchParams['countrySysId'];
            $checkin = $SearchParams['hotelFromDateSession'];
            // echo "<pre>";
            // print_r(($SearchParams));
            // die;
            $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
            $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
            $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;

            $AgentUserDetail = $crmcustomerObj->getAgentDetailById($AgencySysId__);
            $UserSysId = isset($AgentUserDetail[0]['UserSysId']) ? $AgentUserDetail[0]['UserSysId'] : 0;

            $checkin = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($checkin, 'd/m/y');
            $checkout = $SearchParams['hotelToDateSession'];
            $checkout = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($checkout, 'd/m/y');
            $CancelArr = isset($hoteldetails['RoomInfo'][0]['CancelArr']) ? $hoteldetails['RoomInfo'][0]['CancelArr'] : [];
            $HotelFaciality = (isset($hoteldetails['HotelDetails']['HotelFaciality']) && !empty($hoteldetails['HotelDetails']['HotelFaciality'])) ? $hoteldetails['HotelDetails']['HotelFaciality'] : [];
            $Instruction = isset($hoteldetails['HotelDetails']['Instruction']) ? $hoteldetails['HotelDetails']['Instruction'] : [];
            $insts = isset($hoteldetails['HotelDetails']['inst'][0]) ? $hoteldetails['HotelDetails']['inst'][0] : [];
            $HotelDescription = isset($hoteldetails['HotelDetails']['HotelDescription']) ? $hoteldetails['HotelDetails']['HotelDescription'] : '';
            $HotelImages = isset($hoteldetails['HotelDetails']['HotelImages']) ? $hoteldetails['HotelDetails']['HotelImages'] : '';
            $IsPANMandatory = ($hoteldetails['HotelDetails']['IsPANMandatory']);
            $IsPassportMandatory = ($hoteldetails['HotelDetails']['IsPassportMandatory']);

            $f = 1;
            $roomjson = [];
            $bookingrequest = [];
            $adultcount = 0;
            $childcount = 0;
            $rooms = 0;
            if ($memberDetailsSearch) {
                foreach ($memberDetailsSearch as $key => $pax) {
                    $adultcount += $pax['AdultPax'];
                    $childcount += $pax['ChildPax'];
                    $TotAdultCount = isset($pax['AdultPax']) ? trim($pax['AdultPax']) : 0;
                    $TotChildCount = isset($pax['ChildPax']) ? $pax['ChildPax'] : 0;


                    $roomjson[$f]['Adult']  = $TotAdultCount;
                    $roomjson[$f]['Child']  = $TotChildCount;
                    $roomjson[$f]['Infant']  = 0;
                    $roomjson[$f]['bedtype'] = '';
                    $roomjson[$f]['departuredate'] = date('d/m/Y',  strtotime($checkin));
                    $roomjson[$f]['returndate'] = '';
                    $roomjson[$f]['fromaircode'] = '';
                    $roomjson[$f]['toaircode'] = '';
                    $roomjson[$f]['airclass'] = '';
                    $f++;
                }
            }

            $Instructionarray = [];
            if (!empty($insts)) {
                $Instruction = array_merge($insts, $Instruction);
            } else {
                $Instruction = $Instruction;
            }

            if ($Instruction) {
                foreach ($Instruction as $inst) {
                    if ($this->json_validate($inst['msg'])) {
                        $msg = (isset($inst['msg']) && !empty($inst['msg'])) ? json_decode($inst['msg'], 1) : [];
                    } else {
                        $msg = ['' => $inst['msg']];
                    }
                    foreach ($msg as $key => $value) {
                        $Instructionarray[] = array(
                            'types' => $inst['type'],
                            'name' => $key,
                            'description' => $value,
                        );
                    }
                }
            }
            $HotelFacialityArray = [];
            if ($HotelFaciality) {
                foreach ($HotelFaciality as $value) {
                    $HotelFacialityArray[] = array(
                        'name' => $value,
                    );
                }
            }
            if ($CancelArr) {
                foreach ($CancelArr as $value) {
                    $CancelArray[] = array(
                        'fromdate' => (isset($value['fromddate']) && !empty($value['fromddate'])) ? date('Y-m-d H:i:s', strtotime($value['fromddate'])) : '',
                        'todate' => (isset($value['todate'])  && !empty($value['todate'])) ? date('Y-m-d H:i:s', strtotime($value['todate'])) : '',
                        'amount' => $value['am'],
                        'servicefee' => isset($value['servicefee']) ? $value['servicefee'] : 0,
                        'Currency' => $value['Currency'],
                        'LastCancellationDate' => (isset($value['LastCancellationDate']) && !empty($value['LastCancellationDate'])) ? date('Y-m-d H:i:s', strtotime($value['LastCancellationDate'])) : '',
                        'Isfullrefundallowed' => isset($value['Isfullrefundallowed']) ? $value['Isfullrefundallowed'] : false,
                    );
                }
            }
            $ImageArray = [];
            if ($HotelImages) {
                foreach ($HotelImages as $img) {
                    $ImageArray[] = array(
                        'ImageURL' => isset($img['url']) ? $img['url'] : '',
                        'sizes' => isset($img['sz']) ? $img['sz'] : '',
                    );
                }
            }
            $AgencySysId = $this->intLoggedinUserAgencySysId;
            $arrayCancellation = '';
            $HotelAddress = $hoteldetails['HotelDetails']['HotelAddress'];
            // $HotelAddress = $hoteldetails['HotelDetails']['HotelAddress'] . ', ' . $hoteldetails['HotelDetails']['HotelCity'] . ', ' . $hoteldetails['HotelDetails']['HotelCountry'] . ' - ' . $hoteldetails['HotelDetails']['postalCode'];
            $HotelDetails = array(
                'cancellationPolicy' => $arrayCancellation,
                'AgencySysId' => $this->intLoggedinUserAgencySysId,
                'TraceId' => $BookingID,
                'ConfirmationNo' => '',
                'CheckInDate' => $checkin,
                'CheckOutDate' => $checkout,
                'BookingRefNo' => '',
                'BookingId' => $BookingID,
                'APIBookingId' => $hoteldetails['HotelDetails']['bookingId'],
                'HotelBookingStatus' => '',
                'ResultIndex' => $hoteldetails['HotelDetails']['HotelId'],
                'HotelName' => $hoteldetails['HotelDetails']['HotelName'],
                'HotelCode' => $hoteldetails['HotelDetails']['HotelId'],
                'HotelDescription' => $HotelDescription,
                'StarRating' => $hoteldetails['HotelDetails']['HotelStars'],
                'Currency' => $Currency,
                // 'HotelPicture' => isset($hoteldetails['HotelDetails']['HotelImages'][0]['tns']) ? $hoteldetails['HotelDetails']['HotelImages'][0]['tns'] : $hoteldetails['HotelDetails']['HotelImages'][0]['url'],
                'HotelPicture' => isset($hoteldetails['HotelDetails']['HotelImages'][0]['tns']) ? $hoteldetails['HotelDetails']['HotelImages'][0]['tns'] : ($hoteldetails['HotelDetails']['HotelImages'][0]['url'] ?? ''),
                'HotelAddress' => $HotelAddress,
                'HotelContactNo' => isset($hoteldetails['HotelDetails']['HotelContact']['ph']) ? $hoteldetails['HotelDetails']['HotelContact']['ph'] : '',
                'HotelMap' => $hoteldetails['HotelDetails']['HotelAddress'],
                'Latitude' => $hoteldetails['HotelDetails']['HotelGeioLocation']['ln'],
                'Longitude' => $hoteldetails['HotelDetails']['HotelGeioLocation']['lt'],
                'HotelLocation' => isset($hoteldetails['HotelDetails']['location']) ? $hoteldetails['HotelDetails']['location'] : '',
                'PinCode' => isset($hoteldetails['HotelDetails']['postalCode']) ? $hoteldetails['HotelDetails']['postalCode'] : '',
                'Remarks' => $specialrequest,
                'NoOfNights' => $hotelTotalNights,
                'NoOfRooms' => $rooms,
                'totaladult' => $adultcount,
                'totalchild' => $childcount,
                'memberdata' => json_encode($roomjson),
                'facility' => ($HotelFacialityArray),
                'cancellation' => ($CancelArray),
                'instruction' => ($Instructionarray),
                'images' => ($ImageArray),
                'TBBCityId' => $cityId,
                'cityid' => $cityId,
                'ContSysId' => $countrySysId,
                'cityName' => !empty($hoteldetails['HotelDetails']['HotelCity']) ? $hoteldetails['HotelDetails']['HotelCity'] : $CityName,
                'HotelCountry' => !empty($hoteldetails['HotelDetails']['HotelCountry']) ? $hoteldetails['HotelDetails']['HotelCountry'] : '',
                'gtxcity' => !empty($hotelXrefCityId) ? $hotelXrefCityId : 0,
                'IsMarkForDel' => '0',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            );
            // echo "<pre>";
            // print_r(($HotelDetails));
            // echo "<pre>";
            // print_r(($hoteldetails['HotelDetails']));
            // die;

            $ARR_SALUTIONTBO = unserialize(ARR_SALUTIONTBO);

            $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
            $ARR_SALUTION_CHILD = array_flip($ARR_SALUTIONTBO);
            $ConvertionRate = 1;
            $index = 0;
            $booking_room_data = [];
            $TotalBaseFare = 0;
            $TotalTaxesandFee = 0;
            $OtherCharges = 0;
            $TotalDiscount = 0;
            $GrandTotal = 0;
            $Currncy = '';
            $TotalCommissionEarned = 0;
            $TotalFixedMarkUp = 0;
            $TotalGSTOnMarkUp = 0;
            $TotalTDSEarn = 0;
            $roomtravellerinfo = [];
            $hotelPassengerArr = [];
            $HotelRoomsDetails_TBO = [];
            if ($memberDetailsSearch) {
                foreach ($memberDetailsSearch as $key => $mem) {
                    $RoomInfo = $hoteldetails['RoomInfo'][0]['Rooms'][$key];
                    $OtherCharges = isset($RoomInfo['OtherCharges']) ? $RoomInfo['OtherCharges'] : 0;
                    $TotalPrice = ($RoomInfo['TotalBaseFare'] + $RoomInfo['FixedMarkUp'] + $RoomInfo['FixedMarkUp'] + $RoomInfo['GSTOnMarkUp'] + $RoomInfo['TotalTaxFare'] + $OtherCharges);
                    $RoomInfoData = [];

                    $RoomInfoData['numberOfAdults'] = $mem['AdultPax'];
                    $RoomInfoData['numberOfChild'] = $mem['ChildPax'];
                    $mem['numberOfAdults'] = $mem['AdultPax'];
                    $mem['numberOfChild'] = $mem['ChildPax'];

                    $IntmemberData = isset($memberData[$key]) ? $memberData[$key] : [];

                    $ConvertionRate = $RoomInfo['ConvertionRate'];
                    $HotelRoomsDetails = array(
                        'AgencySysId' => $AgencySysId,
                        'TraceId' => $BookingID,
                        'NoOfAdults' => $RoomInfoData['numberOfAdults'],
                        'NoOfChild' => $RoomInfoData['numberOfChild'],
                        'RoomIndex' => $key,
                        'RoomTypeCode' => $RoomInfo['id'],
                        'RoomTypeName' => $RoomInfo['RoomType'],
                        'RatePlanCode' => $RoomInfo['MealBase'],
                        'RatePlanName' => $RoomInfo['RoomCategory'],
                        'RatePlan' => isset($RoomInfo['RatePlan']) ? $RoomInfoData['RatePlan'] : '0',
                        'LastCancellationDate' => isset($RoomInfo['LastCancellationDate']) ? date('Y-m-d H:i:s', strtotime($RoomInfo['LastCancellationDate'])) : '',
                        'LastVoucherDate' => NULL,
                        'BedTypeCode' => null,
                        'SmokingPreference' => 0,
                        'CurrencyType' => $currencySysId,
                        'Currency' => $RoomInfo['Currency'],
                        'RoomPrice' => $RoomInfo['TotalBaseFare'] * $ConvertionRate,
                        'TotalPrice' => ($TotalPrice * $ConvertionRate),
                        'TaxesServiceFee' => (($RoomInfo['TotalTaxFare'] + $OtherCharges) * $ConvertionRate),
                        'intCostToCustomer' => ($TotalPrice * $ConvertionRate),
                        'AgencyMarkUp' => $RoomInfo['FixedMarkUp'] * $ConvertionRate,
                        'ServiceTaxOnAgencyMarkUp' => $RoomInfo['GSTOnMarkUp'] * $ConvertionRate,
                        'PublishedPrice' => $TotalPrice * $ConvertionRate,
                        'OfferedPrice' => $RoomInfo['TotalNetFare'] * $ConvertionRate,
                        // 'Discounts' => isset($RoomInfo['couponVal']) ? $RoomInfo['couponVal'] * $ConvertionRate : 0,
                        'Discounts' => isset($RoomInfo['couponVal']) ? $RoomInfo['couponVal']  : 0,
                        'IsMarkForDel' => '0',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    );

                    $TotalBaseFare += $RoomInfo['TotalBaseFare'] * $ConvertionRate;
                    $TotalFixedMarkUp += $RoomInfo['FixedMarkUp'] * $ConvertionRate;
                    $TotalGSTOnMarkUp += $RoomInfo['GSTOnMarkUp'] * $ConvertionRate;
                    $OtherCharges = isset($RoomInfo['OtherCharges']) ? $RoomInfo['OtherCharges'] : 0;
                    $TotalTaxesandFee += (($RoomInfo['TotalTaxFare'] + $OtherCharges) * $ConvertionRate);
                    // $TotalDiscount += isset($RoomInfo['couponVal']) ? $RoomInfo['couponVal'] * $ConvertionRate : 0;
                    $TotalDiscount += isset($RoomInfo['couponVal']) ? $RoomInfo['couponVal']  : 0;
                    ///$Currncy = 'INR';
                    $Currncy = $RoomInfo['Currency'];
                    $booking_room_data[$key] = $HotelRoomsDetails;
                    $HotelPassenger = [];
                    $travellerInfo = array();
                    if ($mem['numberOfAdults']) {
                        for ($a = 0; $a < $mem['numberOfAdults']; $a++) {
                            $index++;
                            $ind = ($index - 1);
                            if ($a == 0) {
                                $LeadPassenger = true;
                            } else {
                                $LeadPassenger = false;
                            }

                            $HotelPassenger[$a] = array(
                                'AgencySysId' => $AgencySysId,
                                'EmailId' => $leadEmail,
                                'Salutation' => $ARR_SALUTION[$IntmemberData[$a]['title']],
                                'Title' =>  isset($IntmemberData[$a]['title']) ? $IntmemberData[$a]['title'] : '',
                                'Contacts' => $leadMobile,
                                'Relation' => 9,
                                'FirstName' => $IntmemberData[$a]['fname'],
                                'LastName' => $IntmemberData[$a]['lname'],
                                'panno' => isset($IntmemberData[$a]['panno']) ? $IntmemberData[$a]['panno'] : '',
                                'Age' => 0,
                                'IsPswExpire' => 0,
                                'CreatedByUserSysId' => $AgencySysId,
                                'Address' => 'Not Required',
                                'CityTitle' => 'Not Required',
                                'CitySysId' => 0,
                                'paxType' => $IntmemberData[$a]['PaxType'],
                                'IsPassM' => $IntmemberData[$a]['IsPassM'],
                                'StateOrZoneSysId' => 0,
                                'CountrySysId' => 0,
                                'countryCode' => $countryCode,
                                'RegisterDate' => date('Y-m-d H:i:s'),
                                'IsApproved' => '0',
                                'IsActive' => '1',
                                'IsMarkForDel' => '0',
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            );
                            if (!empty($IntmemberData[$a]['passno']) && $IntmemberData[$a]['IsPassM'] == 1) {
                                $HotelPassenger[$a]['passportnoexpiry'] = $IntmemberData[$a]['passexp'];
                                $HotelPassenger[$a]['passporIssue'] = $IntmemberData[$a]['passisse'];
                                $HotelPassenger[$a]['passportno'] = $IntmemberData[$a]['passno'];
                            }
                            if ($ind == 0) {
                                $HotelPassenger[$a]['GTX_customerSysId'] = isset($apiCustomer['Message']) ? $apiCustomer['Message'] : 0;
                            } else {
                                $HotelPassenger[$a]['GTX_customerSysId'] = isset($apiCustomer['memberId'][($ind - 1)]) ? $apiCustomer['memberId'][($ind - 1)] : 0;
                            }

                            $traveller['fN'] = $IntmemberData[$a]['fname'];
                            $traveller['lN'] =  $IntmemberData[$a]['lname'];
                            $traveller['ti'] = trim($IntmemberData[$a]['title']);
                            $traveller['pt'] = 'ADULT';

                            // echo '<pre>';
                            // print_r($IntmemberData[$a]);
                            // echo '</pre>';
                            if ($IntmemberData[$a]['IsPAN'] == 1) {
                                $traveller['pan'] = $IntmemberData[$a]['panno'];
                            }
                            if ($IntmemberData[$a]['IsPassM'] == 1) {
                                if (!empty($IntmemberData[$a]['passno'])) {
                                    $traveller['pNum'] = $IntmemberData[$a]['passno'];
                                }
                            }
                            $travellerInfo[] = $traveller;
                            $HotelPassenger[$a]['apiTraceId'] = $BookingID;
                            if ($ICSourceSysId == 3) {
                                $expDate = isset($memberData[$a]['passexp']) ? date('Y-m-d', strtotime($memberData[$a]['passexp'])) : '';
                                $issueDate = isset($memberData[$a]['passisse']) ? date('Y-m-d', strtotime($memberData[$a]['passisse'])) : '';
                                if ($a == 0) {
                                    $LeadPassenger = true;
                                } else {
                                    $LeadPassenger = false;
                                }
                                $hotelPassengerArr[$key]["paxes"][$a] = array(
                                    'Title' => trim($IntmemberData[$a]['title']),
                                    'FirstName' => $IntmemberData[$a]['fname'],
                                    'Middlename' => null,
                                    'LastName' => $IntmemberData[$a]['lname'],
                                    'Phoneno' => $leadMobile,
                                    'Email' => $leadEmail,
                                    'PaxType' => 1,
                                    'LeadPassenger' => $LeadPassenger,
                                    'PAN' => ($IsPANMandatory == 1) ? $IntmemberData[$a]['panno'] : null,
                                    'Age' => 0,

                                    "PaxId" => $a,
                                    // "GSTCompanyAddress" => null,
                                    // "GSTCompanyContactNumber" => null,
                                    // "GSTCompanyName" => null,
                                    // "GSTNumber" => null,
                                    // "GSTCompanyEmail" => null,

                                );
                                if ($IsPassportMandatory == 1) {
                                    $hotelPassengerArr[$key]["paxes"][$a]['PassportNo'] = isset($IntmemberData[$a]['passno']) ? $IntmemberData[$a]['passno'] : '';
                                    $hotelPassengerArr[$key]["paxes"][$a]['PassportIssueDate'] = isset($IntmemberData[$a]['passisse']) ? date('Y-m-d', strtotime($IntmemberData[$a]['passisse'])) . 'T00: 00: 00' : '';
                                    $hotelPassengerArr[$key]["paxes"][$a]['PassportExpDate'] = isset($IntmemberData[$a]['passexp']) ? date('Y-m-d', strtotime($IntmemberData[$a]['passexp'])) . 'T00: 00: 00' : '';
                                }
                            }
                        }
                    }


                    if ($mem['numberOfChild'] > 0) {
                        $ch = 0;
                        if ($ICSourceSysId == 3 && $this->intLoggedinUserAgencySysId != 1) {
                            $ChildAge = explode(',', $mem['ChildsAge']);
                        } else {
                            $ChildAge = explode(',', $mem['ChildsAge']);
                        }

                        for ($c = $a; $c < ($mem['numberOfChild'] + $mem['numberOfAdults']); $c++) {

                            $index++;
                            $ind = ($index - 1);

                            $HotelPassenger[$c] = array(
                                'AgencySysId' => $AgencySysId,
                                'EmailId' => $leadEmail,
                                'Salutation' => isset($IntmemberData[$c]['title']) ? $ARR_SALUTION_CHILD[$IntmemberData[$c]['title']] : '',
                                'Title' => isset($IntmemberData[$c]['title']) ? $IntmemberData[$c]['title'] : '',
                                'Relation' => 9,
                                'Contacts' => $leadMobile,
                                'FirstName' => isset($IntmemberData[$c]['fname']) ? $IntmemberData[$c]['fname'] : '',
                                'LastName' => isset($IntmemberData[$c]['lname']) ? $IntmemberData[$c]['lname'] : '',
                                'panno' => '',
                                'Age' => isset($ChildAge[$ch]) ? $ChildAge[$ch] : 0,
                                'IsPswExpire' => 0,
                                'CreatedByUserSysId' => $AgencySysId,
                                'Address' => 'Not Required',
                                'CityTitle' => 'Not Required',
                                'CitySysId' => 0,
                                'paxType' => $IntmemberData[$c]['PaxType'],
                                'IsPassM' => $IntmemberData[$c]['IsPassM'],
                                'StateOrZoneSysId' => 0,
                                'CountrySysId' => 0,
                                'countryCode' => $countryCode,
                                'RegisterDate' => date('Y-m-d H:i:s'),
                                'IsApproved' => '0',
                                'IsActive' => '1',
                                'IsMarkForDel' => '0',
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            );
                            if (!empty($IntmemberData[$c]['passno']) && $IntmemberData[$c]['IsPassM'] == 1) {
                                $HotelPassenger[$c]['passportnoexpiry'] = $IntmemberData[$c]['passexp'];
                                $HotelPassenger[$c]['passporIssue'] = $IntmemberData[$c]['passisse'];
                                $HotelPassenger[$c]['passportno'] = $IntmemberData[$c]['passno'];
                            }
                            $HotelPassenger[$c]['GTX_customerSysId'] = isset($apiCustomer['memberId'][($ind - 1)]) ? $apiCustomer['memberId'][($ind - 1)] : 0;
                            $HotelPassenger[$c]['apiTraceId'] =  $BookingID;

                            if ($IntmemberData[$c]['title'] == 'Ms') {
                                $chtitle = 'Miss';
                            } elseif ($IntmemberData[$c]['title'] == 'Mstr') {
                                $chtitle = 'Master';
                            } else {
                                $chtitle = $IntmemberData[$c]['title'];
                            }
                            $traveller['fN'] = $IntmemberData[$c]['fname'];
                            $traveller['lN'] =  $IntmemberData[$c]['lname'];
                            $traveller['ti'] = $chtitle;
                            $traveller['pt'] = 'CHILD';
                            unset($traveller['pan']);

                            if ($IntmemberData[$c]['IsPassM'] == 1) {
                                if (!empty($IntmemberData[$c]['passno'])) {
                                    $traveller['pNum'] = $IntmemberData[$a]['passno'];
                                }
                            }
                            if ($ICSourceSysId == 3) {
                                $hotelPassengerArr[$key]["paxes"][$c] = array(
                                    'Title' => trim($IntmemberData[$c]['title']),
                                    'FirstName' => $IntmemberData[$c]['fname'],
                                    'Middlename' => null,
                                    'LastName' => $IntmemberData[$c]['lname'],
                                    'Phoneno' => $leadMobile,
                                    'Email' => $leadEmail,
                                    'PaxType' => 2,
                                    'LeadPassenger' => false,
                                    'Age' => isset($ChildAge[$ch]) ? $ChildAge[$ch] : 0,
                                    'PAN' => ($IsPANMandatory == 1) ? $IntmemberData[0]['panno'] : '',

                                    "PaxId" => $c,
                                    // "GSTCompanyAddress" => null,
                                    // "GSTCompanyContactNumber" => null,
                                    // "GSTCompanyName" => null,
                                    // "GSTNumber" => null,
                                    // "GSTCompanyEmail" => null,
                                );
                                if ($IsPassportMandatory == 1) {
                                    $hotelPassengerArr[$key]["paxes"][$c]['PassportNo'] = isset($IntmemberData[$c]['passno']) ? $IntmemberData[$c]['passno'] : '';

                                    $hotelPassengerArr[$key]["paxes"][$c]['PassportIssueDate'] = isset($IntmemberData[$c]['passisse']) ? date('Y-m-d', strtotime($IntmemberData[$c]['passisse'])) . 'T00: 00: 00' : '';
                                    $hotelPassengerArr[$key]["paxes"][$c]['PassportExpDate'] = isset($IntmemberData[$c]['passexp']) ? date('Y-m-d', strtotime($IntmemberData[$c]['passexp'])) . 'T00: 00: 00' : '';
                                }
                            }
                            $travellerInfo[] = $traveller;
                            $ch++;
                        }
                    }
                    $alltraveller['travellerInfo'] = $travellerInfo;
                    $roomtravellerinfo[] = $alltraveller;
                    $booking_room_data[$key]['customer'] = $HotelPassenger;
                    // pr($HotelPassenger);LastCancellationDate
                }
            }

            if ($ICSourceSysId == 3) {
                if ($memberDetailsSearch) {
                    foreach ($memberDetailsSearch as $key => $mem) {
                        $HotelPassenger__ = $hotelPassengerArr[$key]['paxes'];
                        $CancelDateskipped = false;
                        $RoomInfoData = isset($hoteldetails['RoomInfo'][0]['Rooms'][$key]) ? $hoteldetails['RoomInfo'][0]['Rooms'][$key] : [];

                        $HotelRoomsDetails_TBO[$key] = array(
                            'HotelPassenger' => $HotelPassenger__,
                        );
                    }
                }
                $bookingRequestTbo = array(
                    'BookingCode' => isset($hoteldetails['RoomInfo'][0]['Rooms'][0]['RoomIndex']) ? $hoteldetails['RoomInfo'][0]['Rooms'][0]['RoomIndex'] : false,
                    'IsVoucherBooking' => true, //isset($hoteldetails['RoomInfo'][0]['IsVoucherBooking']) ? $hoteldetails['RoomInfo'][0]['IsVoucherBooking'] : false,
                    'NetAmount' => isset($hoteldetails['RoomInfo'][0]['NetAmount']) ? $hoteldetails['RoomInfo'][0]['NetAmount'] : 0,
                    'RequestedBookingMode' => 5,
                    'GuestNationality' => 'IN',
                    'HotelRoomsDetails' => $HotelRoomsDetails_TBO,
                );
            }

            // echo "<pre>bookingRequestTbo";
            // print_r(($bookingRequestTbo));
            // die;
            $emails[] = $leadEmail;
            $contacts[] =  $leadMobile;
            $code[] =  '+' . $countryCode;
            $deliveri['emails'] =  $emails;
            $deliveri['contacts'] =  $contacts;
            $deliveri['code'] =   $code;
            $bookingId = $hoteldetails['HotelDetails']['bookingId'];
            $amount = isset($hoteldetails['RoomInfo'][0]['RoomTotalPrice']) ? $hoteldetails['RoomInfo'][0]['RoomTotalPrice'] : 0;
            $payments[] = array('amount' => (float)$amount);
            if ($ICSourceSysId == 3) {
                $bookingrequest = $bookingRequestTbo;
            } else {
                $bookingrequest['bookingId'] = $bookingId;
                $bookingrequest['roomTravellerInfo'] = $roomtravellerinfo;
                $bookingrequest['deliveryInfo'] = $deliveri;
                $bookingrequest['type'] = 'HOTEL';
                $bookingrequest['paymentInfos'] = $payments;
            }

            $Hotel_booking_data = array(
                'hotel_data' => $HotelDetails,
                'booking_room_data' => $booking_room_data,
            );
            $fare = array(
                'Currncy' => $Currncy,
                'BaseFare' => $TotalBaseFare,
                'TaxesandFee' => $TotalTaxesandFee,
                'GrandTotal' => (($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp) - $TotalDiscount),
                'CommissionEarned' => $TotalCommissionEarned,
                'TDSEarn' => $TotalTDSEarn,
                'Discount' => $TotalDiscount,
                'FixedMarkUp' => $TotalFixedMarkUp,
                'GSTOnMarkUp' => $TotalGSTOnMarkUp,
            );

            $BookingDetails = [
                'HotelBookingData' => $Hotel_booking_data,
                'Fare' => $fare,
            ];
            $TPSysId = $SearchParams['TPSysId'];
            $BookingDetails["AgencySysId"] = $AgencySysId;
            $BookingDetails["AgentSysId"] = $this->intLoggedinUserId;
            $BookingDetails["email"] = isset($leadEmail) ? $leadEmail : '';
            $BookingDetails["mobile"] = isset($leadMobile) ? $leadMobile : '';
            $BookingDetails["FirstName"] = isset($ForCustomerSession[0]['fname']) ? $ForCustomerSession[0]['fname'] : '';
            $BookingDetails["LastName"] = isset($ForCustomerSession[0]['lname']) ? $ForCustomerSession[0]['lname'] : '';
            $BookingDetails["editLeadId"] = $TPSysId;
            $BookingDetails["IsB2BQuery"] = $IsB2BCustomer;
            $BookingDetails["B2BAgentSysId"] = $UserSysId;
            $BookingDetails["B2BAgencySysId"] = $AgencySysId__;
            $BookingDetails["leadsource"] = 'Agency';
            $BookingDetails["IsB2BProposal"] = $IsB2BCustomer;
            $BookingDetails["ICSourceSysId"] = $ICSourceSysId;
            $BookingDetails["ExchangeCurrencyRate"] = $ConvertionRate;
            $BookingDetails["TraceId"] = $BookingID;
            $BookingDetails["APIMode"] = 0;
            $BookingDetails["IsNewMigration"] = 3;

            $gstData = array(
                'GstNumber' => $gstnnumber,
                'GstCompany' => $companyname,
                'GstEmail' => $gstemail,
                'GstPhone' => $gstphone,
                'GstAddress' => $gstaddress,
                'GstState' => $gststate,
            );

            $ServiceTaxNo = $this->agencyDetails['ServiceTaxNo'];
            $gstvalidate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->gstvalidate($gstnnumber, $ServiceTaxNo);

            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api';

            $HotelQueryids = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($BookingDetails, $getData, $URL);
            // echo "<pre>";
            // print_r(($HotelQueryids));
            // echo "<pre>";
            // print_r(($BookingDetails));
            // die;
            $misxItems_name = [];
            if ($BookingDetails['HotelBookingData']['booking_room_data']) {
                foreach ($BookingDetails['HotelBookingData']['booking_room_data'] as $key => $value) {

                    $TotalGST = $value['ServiceTaxOnAgencyMarkUp'];
                    $Discounts = isset($value['Discounts']) ? $value['Discounts'] : 0;
                    $misxItems_name[] = [
                        'AgencySysId' => $AgencySysId,
                        'AgentSysId' => 0,
                        'MisxItems_name' => 'Hotel',
                        'Description' => $value['RoomTypeName'],
                        'ItemQty' => 1,
                        'ItemRates' => ($value['RoomPrice'] + $value['TaxesServiceFee']),
                        'Total' => $value['RoomPrice'] + $value['TaxesServiceFee'],
                        'DiscountType' => 1,
                        'Discount' => $Discounts,
                        'TotalDiscount' => $Discounts,
                        'TotalAmount' => ($value['RoomPrice'] + $value['TaxesServiceFee'] + $value['AgencyMarkUp'] + $TotalGST - $Discounts),
                        'MarkupType' => '',
                        'Markup' =>  $value['AgencyMarkUp'],
                        'TotalMarkup' =>  $value['AgencyMarkUp'],
                        'SubTotal' => ($value['RoomPrice'] + $value['TaxesServiceFee'] + $value['AgencyMarkUp'] + $TotalGST - $Discounts),
                        'ServiceFeeTotal' => 0,
                        'GSTPercentage' => '18',
                        'TotalGST' => $TotalGST,
                        'SGST' => ($gstvalidate['SGST'] == 1) ? ($TotalGST / 2) : 0,
                        'CGST' => ($gstvalidate['CGST'] == 1) ? ($TotalGST / 2) : 0,
                        'IGST' => ($gstvalidate['IGST'] == 1) ? $TotalGST : 0,
                        'ItemsSACCode' => '',
                    ];
                }
            }

            $Invoicedata = [];
            if ($HotelQueryids['status'] == 1) {
                $arrIds = isset($HotelQueryids['arrIds']) ? $HotelQueryids['arrIds'] : [];
                $MasterTPSysId = isset($arrIds['MasterTPSysId']) ? $arrIds['MasterTPSysId'] : 0;
                $TPSysId = isset($arrIds['TPSysId']) ? $arrIds['TPSysId'] : 0;
                $VersionId = isset($arrIds['VersionId']) ? $arrIds['VersionId'] : 0;
                $CustomerSysIdGTX = isset($arrIds['CustomerSysId']) ? $arrIds['CustomerSysId'] : 0;
                $TrxId = isset($arrIds['TrxId']) ? $arrIds['TrxId'] : 0;

                $TotalInvoiceValue = $fare['GrandTotal'];
                $PublishedFare = $fare['GrandTotal'];
                $agencyMarkUpGST = $fare['GSTOnMarkUp'];
                $Discount = $fare['Discount'];
                $Invoicedata = [
                    'AgentSysId' => 0,
                    'CustomerSysId' => $CustomerSysIdGTX,
                    'TPSysId' => $TPSysId,
                    'MasterTPSysId' => $MasterTPSysId,
                    'ProposalID' => $TPSysId . '/V1',
                    'InvoiceDate' => date('Y-m-d'),
                    'isDisplayMarkup' => true,
                    'PaymentDueDate' => date('Y-m-d'),
                    'PaymentDate' => date('Y-m-d'),
                    'ClientGST' => 0,
                    'ClientGSTNumber' => '',
                    'Currency' => 1,
                    'TotalInvoiceValue' => $TotalInvoiceValue,
                    'InvoiceStatus' => true,
                    'TotalSGST' => ($gstvalidate['SGST'] == 1) ? ($agencyMarkUpGST / 2) : 0,
                    'TotalCGST' => ($gstvalidate['CGST'] == 1) ? ($agencyMarkUpGST / 2) : 0,
                    'TotalIGST' => ($gstvalidate['IGST'] == 1) ? $agencyMarkUpGST : 0,
                    'SumdiscountItem' => $Discount,
                    'OtherDiscount' => 0,
                    'otherDiscountVal' => 0,
                    'TotalAdvance' => $PublishedFare,
                    'TotalDueAmount' => 0,
                    'InvoiceValue' => $PublishedFare,
                    'notes' => 'Hotel Voucher',
                    'termsandcondition' => '',
                    'client_state' => '',
                    'Advance' => 0,
                    'PaymentType' => 4,
                    'paymentNote' => 'Online',
                    'misxItems_name' => $misxItems_name,

                ];
                $arrUrlData['Invoicedata'] = $Invoicedata;
                $arrUrlData['HotelQueryids'] = $HotelQueryids;
                $arrUrlData['BookingDetails'] = $BookingDetails;
                $arrUrlData['bookingrequest'] = $bookingrequest;
                $arrUrlData['gstData'] = $gstData;

                $tempData = array(
                    'TraceId' => $searchIDSearch,
                    'TPSysId' => ($TPSysId),
                    'APIBookingData' => json_encode($arrUrlData),
                );
                $objTempFlight->deleteFlightTempData($searchIDSearch);
                $objTempFlight->insertFlightTempData($tempData);
                echo json_encode(['success' => true, 'message' => 'SUCESS', 'fare' => $fare, 'SearchTraceId' => $searchIDSearch]);
                exit;
                // echo "<pre>Invoicedata";
                // print_r(($Invoicedata));
                // echo "<pre>SearchParams";
                // print_r(($SearchParams));
                // echo "<pre>BookingDetails";
                // print_r(($BookingDetails));

                // die;
            } else {
                $response = array('success' => false, 'message' => 'Unable to create query. please contact administrator.');
                echo json_encode($response);
                exit;
            }
        }
    }









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

        if ($this->_request->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);

            $dataArr = isset($post['dataArr']) ? $post['dataArr'] : [];
            $searchID = $post['searchID'];
            $addMarkup = $post['addMarkup'];
            $discount = $post['discount'];
            $TaxPercentage_ = $post['TaxPercentage'];
            $custemail = $post['custemail'];
            $custname = $post['custname'];
            $custphone = $post['custphone'];
            $countrycode = $post['countrycode'];
            $remarks = $post['remarks'];
            $ccemail = (isset($post['ccemail']) && !empty($post['ccemail'])) ? $post['ccemail'] : '';
            $mailToCC = explode(',', $ccemail);
            if (empty(trim($custemail))) {
                echo json_encode(['status' => false, 'message' => 'Please enter email ID', 'searchID' => $searchID]);
                exit;
            }
            if (empty(trim($custphone))) {
                echo json_encode(['status' => false, 'message' => 'Please enter mobile number', 'searchID' => $searchID]);
                exit;
            }
            $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
            $this->_crmcustomertravelItenary = new Travel_Model_CRM_CustomerTravelItenary();
            $this->_crmcusttravelplanHotel = new Travel_Model_CRM_CustomerTravelPlanHotel();

            $objTempFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objTempFlight->GetFlightTempData($searchID);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            $emailID = $custemail; //$SearchParams['emailID'];
            $hotelCityTitle = $SearchParams['hotelCityTitle'];
            $PrimaryEmail = $this->agencyDetails['PrimaryEmail'];
            $PrimaryContactNo = $this->agencyDetails['PrimaryContactNo'];
            $DisplayName = $this->agencyDetails['DisplayName'];
            $FirstName = trim($this->agencyDetails['FirstName']);
            $checkIn = $SearchParams['hotelFromDateSession'];
            $checkOut = $SearchParams['hotelToDateSession'];
            $night = $SearchParams['hotelTotalNights'];
            $room = count($SearchParams['memberDetails']);
            $AdultPax = (int)$SearchParams['totalMemberCount']['AdultPax'];
            $ChildPax = (int)$SearchParams['totalMemberCount']['ChildPax'];
            $intMemberCount = ($AdultPax + $ChildPax);

            $sss = 0;
            if (!empty($dataArr)) {
                $selectedRoom = [];
                foreach ($dataArr as $key => $value) {
                    $explode = explode('____', $value);
                    $HotelId = $explode[0];
                    $RoomID = $explode[1];
                    $HotelDetails = new Zend_Session_Namespace('HotelDetails_' . $HotelId . ' ');
                    $RoomInfo = $HotelDetails->params['RoomInfo'];
                    $HotelDetailsData = $HotelDetails->params['HotelDetails'];


                    if ($RoomInfo) {
                        foreach ($RoomInfo as $RoomVal) {

                            if ($RoomVal['Index'] == $RoomID) {
                                $RoomValArray = [];
                                if ($RoomVal['Rooms']) {
                                    foreach ($RoomVal['Rooms'] as $rooKey => $rooms) {
                                        $TaxPercentage = (isset($TaxPercentage_[$sss]) && !empty($TaxPercentage_[$sss])) ? $TaxPercentage_[$sss] : 18;
                                        $ExtraMarkup = (isset($addMarkup[$sss]) && !empty($addMarkup[$sss])) ? $addMarkup[$sss] : 0;
                                        $discountVal = (isset($discount[$sss]) && !empty($discount[$sss])) ? $discount[$sss] : 0;
                                        $intAmount = (float) $ExtraMarkup;
                                        $ExtraMarkupOnGST = (($intAmount * $TaxPercentage) / 100);

                                        $RoomValArray['Rooms'][$rooKey] = $rooms;
                                        $RoomValArray['Rooms'][$rooKey]['ExtraMarkup'] = $ExtraMarkup;
                                        $RoomValArray['Rooms'][$rooKey]['ExtraMarkupOnGST'] = $ExtraMarkupOnGST;
                                        $RoomValArray['Rooms'][$rooKey]['discountVal'] = $discountVal;
                                        $RoomValArray['Rooms'][$rooKey]['RoomId'] = $RoomVal['RoomId'];
                                        $sss++;
                                    }
                                }

                                $selectedRoom[$HotelId]['room'][] = $RoomValArray;
                            }
                        }
                    }
                    $selectedRoom[$HotelId]['HotelDetailsData'] = $HotelDetailsData;
                }
                // echo "<pre>";
                // echo json_encode($selectedRoom);
                // die;
            }

            // echo "<pre>";
            // print_r($night);
            // echo "<pre>";
            // print_r($selectedRoom);
            // die;
            $finalHtml = '';
            $indkeyy = 1;
            foreach ($selectedRoom as $values) {
                $HotelDetailsData = $values['HotelDetailsData'];

                $RoomsData = '';
                $roomPrice = 0;
                if ($values['room']) {
                    foreach ($values['room'] as $Rkey => $RoomVal) {
                        $option = ($Rkey + 1);
                        $RoomsData .= "*Option $option:*%0a";
                        if ($RoomVal['Rooms']) {
                            foreach ($RoomVal['Rooms'] as $keyroom => $value) {
                                $Currency = $value['Currency'];
                                $TotalRoomPrice = $value['TotalRoomPrice'];
                                $FixedMarkUp = $value['FixedMarkUp'];
                                $GSTOnMarkUp = $value['GSTOnMarkUp'];
                                $ExtraMarkup = $value['ExtraMarkup'];
                                $ExtraMarkupOnGST = $value['ExtraMarkupOnGST'];
                                $discountVal = !empty($value['discountVal']) ? $value['discountVal'] : 0;
                                $roomPrice += (($TotalRoomPrice + $FixedMarkUp + $GSTOnMarkUp + $ExtraMarkup + $ExtraMarkupOnGST) - $discountVal);
                                $roomPriceInt = (($TotalRoomPrice + $FixedMarkUp + $GSTOnMarkUp + $ExtraMarkup + $ExtraMarkupOnGST) - $discountVal);
                                $roomPriceInt = round((($roomPriceInt / $night) / $room), 2);
                                $RoomType = str_replace(array('\'', '"', ',', ';', '<', '>'), ' ', $value['RoomType']);
                                $MealBase = $value['MealBase'];
                                $RoomsData .= "*Room Type:* $RoomType - $MealBase %0a*Sale Price:* $Currency $roomPriceInt per room/night %0a%0a";
                                // $RoomsData .= '*Room Type:*' . "$RoomType - $MealBase %0a" . "Sale Price:" . "$Currency $roomPriceInt %0a%0a";
                            }
                        }
                    }
                }

                $finalHtml .= "*Hotel $indkeyy : " . trim($HotelDetailsData['HotelName']) . ' ( ' . $HotelDetailsData['HotelStars'] . ' Star )*%0a*Address* : ' .  str_replace('039', '', preg_replace('/[^a-zA-Z0-9_ -]/s', ' ', trim($HotelDetailsData['HotelAddress']))) . '%0a%0a' . $RoomsData . '%0a';
                $indkeyy++;
            }

            $bookingUrl = 'urlclick';

            // $whatsappmessage = "*Dear $custname*,%0a%0aThanks for your Hotel query for *$hotelCityTitle* Please find the below quotation for your travel dates.%0a%0a *Check In* :  $checkIn | *Check Out* :  $checkOut %0a%0a *Room(s)* : $room, *Night(s)* : $night, *Pax* : $intMemberCount %0a%0a$finalHtml %0a%0aTo view hotel details and *book online* click on the below link:%0a$bookingUrl %0a%0aYou can also call $FirstName at $PrimaryContactNo or email at $PrimaryEmail or whatsapp me here.%0a%0aRegards %0a%0a$FirstName, %0a$DisplayName";

            // echo json_encode(['status' => true, 'message' => 'Proposal sent successfully', 'searchID' => $searchID, 'whatsapp' => $whatsappmessage, 'contactno' => !empty(trim($custphone)) ? $countrycode . $custphone : '']);
            // exit;
            // $html = new Zend_View();
            // $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
            // $html->assign(array('selectedRoom' => $selectedRoom, 'bookingUrl' => $bookingUrl, 'SearchParams' => $SearchParams, 'remarks' => $remarks, 'custname' => $custname, 'dataArr' => $dataArr, 'baseUrl' => $this->baseUrl, 'getAgencyData' => $this->agencyDetails));
            // $bodyText = $html->render('selectmailhotels.phtml');
            // $emailData = array(
            //     'fromEmail' =>  $PrimaryEmail,
            //     'fromName' => $DisplayName,
            //     'subject' => 'Hotel Proposal for ' . $hotelCityTitle,
            //     'to' => array($emailID),
            //     'bodyHtml' => $bodyText,
            //     'bodyText' => ''
            // );
            // echo "<pre>";
            // print_r($emailData);
            // die;


            $strCheckInDate = $SearchParams['hotelFromDateSession'];
            $strCheckOutDate = $SearchParams['hotelToDateSession'];


            if (!empty($strCheckInDate)) {
                $arrCheckInDate = explode("/", $strCheckInDate);
                if (!empty($arrCheckInDate) > 0) {
                    $strCheckInDateNew = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
                }
            }

            if (!empty($strCheckOutDate)) {
                $arrCheckOutDate = explode("/", $strCheckOutDate);
                if (!empty($arrCheckOutDate)) {
                    $strCheckOutDateNew = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];
                }
            }
            $leadID = $TPSysId = $SearchParams['TPSysId'];
            $CustomerSysId = $SearchParams['customerId'];
            $TPIntSysId = $SearchParams['TPIntSysId'];
            $HotelCitySysId = $SearchParams['hotelXrefCityId'];
            $Hotel_name_city = $SearchParams['hotelCityTitle'];
            $hotelTotalNights = $SearchParams['hotelTotalNights'];
            $AdultPax = (int)$SearchParams['totalMemberCount']['AdultPax'];
            $ChildPax = (int)$SearchParams['totalMemberCount']['ChildPax'];
            $intTotalPaxCount = ($AdultPax + $ChildPax);
            $roominfojson = $SearchParams['RoomInfoJson'];
            $RoomMemInfoJson = $SearchParams['RoomMemInfoJson'];
            $selectNationality = $SearchParams['selectNationality'];
            $intNoOfRooms = count($SearchParams['memberDetails']);
            $memberDetailsSearch = $SearchParams['memberDetails'];
            $checkin = $SearchParams['hotelFromDateSession'];
            $checkin = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($checkin, 'd/m/y');
            $AgencySysId = $this->intLoggedinUserAgencySysId;
            $AgentSysId = $this->intLoggedinUserId;
            $planbookingID = 'QS/' . date('y');
            $chekInDate = date('Y-m-d', strtotime(str_replace("/", "-", $strCheckInDateNew)));
            $validTillDate = date('Y-m-d', strtotime(str_replace("/", "-", $strCheckOutDateNew)));
            $createDate = date('Y-m-d H:i:s');
            $proposalID = [];
            $lastairID = [];
            $TravelitenaryID = [];
            $HotelQueryid = [];
            $InvoicedataArray = [];
            // echo "<pre>";
            // print_r(json_encode($selectedRoom));
            // die;
            if ($selectedRoom) {
                foreach ($selectedRoom as $key => $values) {
                    $HotelDetailsData = $values['HotelDetailsData'];
                    $BookingDetails = $this->SetHotelBookingData($values, $SearchParams, $post);
                    // echo "<pre>";
                    // print_r($BookingDetails);
                    // die;
                    $offerFare = 0;
                    $finalprice = 0;
                    $agencyMarkUp = 0;
                    $AgentServiceTaxAmount = 0;
                    $extraMarkup_ = 0;
                    $GTXServiceTaxAmount = 0;
                    if ($values['room']) {
                        foreach ($values['room'] as $Rkey => $RoomVal) {
                            if ($RoomVal['Rooms']) {
                                foreach ($RoomVal['Rooms'] as $keyroom => $value) {
                                    $ExtraMarkup = isset($value['ExtraMarkup']) ? $value['ExtraMarkup'] : 0;
                                    $ExtraMarkupOnGST = isset($value['ExtraMarkupOnGST']) ? $value['ExtraMarkupOnGST'] : 0;
                                    $discountVal = isset($value['discountVal']) ? $value['discountVal'] : 0;

                                    $TotalRoomPrice = $value['TotalRoomPrice'];
                                    $CostToCustomer = $value['CostToCustomer'];
                                    $FixedMarkUp = $value['FixedMarkUp'];
                                    $GSTOnMarkUp = $value['GSTOnMarkUp'];
                                    $CostToCustomer = $value['CostToCustomer'];
                                    // $ExtraMarkup = $value['ExtraMarkup'];
                                    // $ExtraMarkupOnGST = $value['ExtraMarkupOnGST'];
                                    $offerFare += $TotalRoomPrice - $discountVal;
                                    $finalprice += (($CostToCustomer + $ExtraMarkup + $ExtraMarkupOnGST) - $discountVal);
                                    $agencyMarkUp += $FixedMarkUp + $ExtraMarkup;
                                    $AgentServiceTaxAmount += $GSTOnMarkUp + $ExtraMarkupOnGST;
                                    $extraMarkup_ += $ExtraMarkup;
                                    $GTXServiceTaxAmount += $ExtraMarkupOnGST;
                                }
                            }
                        }
                    }


                    $arrHotelDetails['TraceId'] = $HotelDetailsData['SearchHotelTraceId'];
                    $arrHotelDetails['ResultIndex'] = $HotelDetailsData['SearchHotelTraceId'];
                    $arrHotelDetails['source'] = 0;

                    $arrHotelDetails['totalpax'] = $intTotalPaxCount;
                    $arrHotelDetails['totalrooms'] = $intNoOfRooms;
                    $arrHotelDetails['nights'] = $hotelTotalNights;
                    $arrHotelDetails['nationality'] = $selectNationality;
                    $arrHotelDetails['checkin'] = $strCheckInDateNew;
                    $arrHotelDetails['checkout'] = $strCheckOutDateNew;
                    $arrHotelDetails['gtxcity'] = $HotelCitySysId;
                    $arrHotelDetails['countrycode'] = $selectNationality;
                    $arrHotelDetails['PublishedFare'] = $finalprice;

                    $arrHotelDetails['HotelName'] = isset($HotelDetailsData['HotelName']) ? $HotelDetailsData['HotelName'] : '';
                    $arrHotelDetails['HotelPicture'] = isset($HotelDetailsData['HotelImages'][0]['url']) ? $HotelDetailsData['HotelImages'][0]['url'] : '';
                    $arrHotelDetails['HotelCode'] = isset($HotelDetailsData['HotelId']) ? $HotelDetailsData['HotelId'] : '';
                    $arrHotelDetails['Longitude'] = isset($HotelDetailsData['HotelGeioLocation']['ln']) ? $HotelDetailsData['HotelGeioLocation']['ln'] : '';
                    $arrHotelDetails['Latitude'] = isset($HotelDetailsData['HotelGeioLocation']['lt']) ? $HotelDetailsData['HotelGeioLocation']['lt'] : '';
                    $arrHotelDetails['Description'] = isset($HotelDetailsData['HotelDescription']) ? $HotelDetailsData['HotelDescription'] : '';
                    $arrHotelDetails['StarRating'] = isset($HotelDetailsData['HotelStars']) ? $HotelDetailsData['HotelStars'] : '';
                    $arrHotelDetails['Address'] = isset($HotelDetailsData['HotelAddress']) ? $HotelDetailsData['HotelAddress'] : '';
                    $intAccomSysId = $this->insertHotelDetailsAction($arrHotelDetails);
                    // echo "<pre>";
                    // print_r($arrHotelDetails);
                    // die;
                    $data1 = array(
                        'MasterTPSysId' => $leadID,
                        'PlanBookingId' => ($planbookingID),
                        'AgencySysId' => ($AgencySysId),
                        'AgentSysId' => $AgentSysId,
                        'InventoryType' => 2,
                        'CreatorSysId' => $AgentSysId,
                        'StatusType' => 4,
                        'CustomerSysId' => ($CustomerSysId),
                        'AdditionalReq' => '',
                        'StartDate' => $chekInDate,
                        'validTill' => $validTillDate,
                        'PlanType' => 2,
                        'Cities' => $Hotel_name_city,
                        'SourcePlaces' => $Hotel_name_city,
                        'CityIds' => $HotelCitySysId,
                        'SourcePlaceSysId' => $HotelCitySysId,
                        'Countries' => '',
                        'CreateDate' => $createDate,
                        'IsActive' => 1,
                        'CreateDate' => $createDate,
                        'UpdateDate' => $createDate,
                        'RoomInfoJson' => $roominfojson,
                        'Price' => (isset($offerFare)) ? (int) $offerFare : 0,
                        'NetPrice' => (isset($finalprice)) ? (int) $finalprice : 0,
                        'AgencyMarkUp' => (int) $agencyMarkUp,
                        'AgentServiceTaxAmount' => (isset($AgentServiceTaxAmount)) ? (int) $AgentServiceTaxAmount : 0,
                        'MarkUp' => 0,
                        'AgentsCustomServiceTaxAmount' => 0,
                        'GTXMarkup' =>  0,
                        'GTXServiceTaxAmount' => 0,
                        'TotalCost' => (isset($finalprice)) ? (int) $finalprice : 0,
                        'IsAprooved' => 1,
                        'CustomerRemark' => '',
                    );

                    $proposalID[] = $isproposalid = $this->_crmcusttravelplan->addCustomerTravelPlan($data1);

                    // if ($leadID) {
                    //     $where = "TPSysId = " . $leadID;
                    //     $updatetravelplan = array(
                    //         'UpdateDate' => $createDate,
                    //         'StatusType' => '2'
                    //     );

                    //     $updatetravelPlan = $this->_crmcusttravelplan->UpdateCustomerTravelPlanQuery($updatetravelplan, $where);
                    //     $travelitenary = array(
                    //         'TPSysId' => $leadID,
                    //         'AgencySysId' => $AgencySysId,
                    //         'StartDate' => $createDate,
                    //         'IsActive' => 1,
                    //         'Sequence' => 1,
                    //         'CreateDate' => $createDate,
                    //         'UpdateDate' => $createDate,
                    //         'IsMarkForDel' => 0,
                    //     );

                    //     $lasttravelitenaryID = $this->_crmcustomertravelItenary->addCustomerTravelItenary($travelitenary);
                    //     $TravelitenaryID[] = $lasttravelitenaryID;
                    // }
                    // $travelplandata = $this->_crmcusttravelplan->GetTravelPlanHotel($intAccomSysId);

                    // $ICSourceSysId = ($travelplandata['ICSourceSysId']) ? $travelplandata['ICSourceSysId'] : 0;
                    // $SupplierSysId = ($travelplandata['SupplierSysId']) ? $travelplandata['SupplierSysId'] : 0;
                    // $CostCurrency = $travelplandata['TrxCurrency'];
                    // $hotelData = array(
                    //     'TPIntSysId' => $lasttravelitenaryID,
                    //     'SeqId' => 1,
                    //     'AccoBookingId' => 0,
                    //     'XRefBookingId' => 0,
                    //     'AccoSysId' => $intAccomSysId,
                    //     'SourceSysId' => (int) $ICSourceSysId,
                    //     'SupplierSysId' => (int) $SupplierSysId,
                    //     'IsfromAPI' => ($ICSourceSysId == 3 || $ICSourceSysId == 4) ? 1 : 0,
                    //     'Title' => $Hotel_name_city,
                    //     'AgencySysId' => $AgencySysId,
                    //     'RoomMemInfoJson' => $RoomMemInfoJson,
                    //     'CreateDate' => $createDate,
                    //     'UpdateDate' => $createDate,
                    //     'FromDate' => $chekInDate,
                    //     'ToDate' => $validTillDate,
                    //     'TotalNights' => $hotelTotalNights,
                    //     'StarRating' => isset($HotelDetailsData['HotelStars']) ? $HotelDetailsData['HotelStars'] : '',
                    //     'AdultPax' => $AdultPax,
                    //     'ChildPax' => $ChildPax,
                    //     'ChildsAge' => 0,
                    //     'InfantPax' => 0,
                    //     'CurrencyType' => trim($CostCurrency),
                    //     'TotalCost' => (isset($finalprice)) ? (int) $finalprice : 0,
                    //     'Discounts' => 0,
                    //     'Taxes' => 0,
                    //     'NetCost' => (isset($offerFare)) ? (int) $offerFare : 0,
                    //     'MarkUp' => 0,
                    //     'PetPax' => 0,
                    //     'TotalPax' => $AdultPax + $ChildPax,
                    //     'XrefCityId' => (int) $HotelCitySysId,
                    //     'IsMarkForDel' => 0,
                    //     'IsSelectedOnPkg' => 1,
                    //     'IsActive' => 1,
                    //     'CurrencyType' => '1'
                    //     //'InfentPax' => $infant,
                    // );
                    // $lastairID[] = $this->_crmcusttravelplanHotel->addCustomerTravelPlanHotel($hotelData);

                    $Invoicedata = isset($BookingDetails['Invoicedata']) ? $BookingDetails['Invoicedata'] : [];
                    $BookingDetails['isproposalid'] = $isproposalid;
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $URL = $this->baseUrl . '/gtxwebservices/hotel-api';
                    $HotelQueryids = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($BookingDetails, $getData, $URL);
                    $TPSysId = isset($HotelQueryids['arrIds']['TPSysId']) ? $HotelQueryids['arrIds']['TPSysId'] : 0;
                    $arrIds = isset($HotelQueryids['arrIds']) ? $HotelQueryids['arrIds'] : [];
                    $MasterTPSysId = isset($arrIds['MasterTPSysId']) ? $arrIds['MasterTPSysId'] : 0;
                    $TPSysId = isset($arrIds['TPSysId']) ? $arrIds['TPSysId'] : 0;
                    $VersionId = isset($arrIds['VersionId']) ? $arrIds['VersionId'] : 0;
                    $CustomerSysIdGTX = isset($arrIds['CustomerSysId']) ? $arrIds['CustomerSysId'] : 0;
                    $TrxId = isset($arrIds['TrxId']) ? $arrIds['TrxId'] : 0;

                    $Invoicedata['CustomerSysId'] = $CustomerSysIdGTX;
                    $Invoicedata['TPSysId'] = $TPSysId;
                    $Invoicedata['MasterTPSysId'] = $MasterTPSysId;
                    $Invoicedata['ProposalID'] = $TPSysId . '/V1';

                    $InvoicedataArray[$TPSysId] = $Invoicedata;
                    $HotelQueryid[$TPSysId] = $HotelQueryids;
                }
            }

            // echo "<pre>";
            // print_r(($HotelQueryid));
            // die;
            $bookingUrl = $originalurl = $this->view->baseUrl('hotel-proposal/view-hotel-proposal/searchID/' . ($searchID) . '/TPSys/' . $leadID . '/cust/1');

            if ($this->intLoggedinAgencyId == 1) {
                $bookingUrl = $originalurl;
            } else {
                $bitly_response = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom')->getSmallLinkFromBitlyAPI($bookingUrl, $this->BITLYLOGIN, $this->BITLYAPIKEY);
                if ($bitly_response['errorCode'] == 0) {
                    $bookingUrl = $bitly_response['results'][trim($bookingUrl)]['shortUrl'];
                }
            }
            //$bookingUrl = '#';
            $whatsappmessage = "*Dear $custname*,%0a%0aThanks for your Hotel query for *$hotelCityTitle* Please find the below quotation for your travel dates.%0a%0a *Check In* :  $checkIn | *Check Out* :  $checkOut %0a%0a *Room(s)* : $room, *Night(s)* : $night, *Pax* : $intMemberCount %0a%0a$finalHtml %0a%0aTo view hotel details and *book online* click on the below link:%0a$bookingUrl %0a%0aYou can also call $FirstName at $PrimaryContactNo or email at $PrimaryEmail or whatsapp me here.%0a%0aRegards %0a%0a$FirstName, %0a$DisplayName";

            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/buyhotel/');
            $html->assign(array('selectedRoom' => $selectedRoom, 'bookingUrl' => $bookingUrl, 'SearchParams' => $SearchParams, 'remarks' => $remarks, 'custname' => $custname, 'dataArr' => $dataArr, 'baseUrl' => $this->baseUrl, 'getAgencyData' => $this->agencyDetails));
            $bodyText = $html->render('selectmailhotels.phtml');
            $emailData = array(
                'fromEmail' =>  $PrimaryEmail,
                'fromName' => $DisplayName,
                'subject' => 'Hotel Proposal for ' . $hotelCityTitle,
                'to' => array($emailID),
                'bodyHtml' => $bodyText,
                'bodyText' => ''
            );
            // echo "<pre>";
            // print_r($searchID);
            // echo "<pre>";
            // print_r($HotelQueryid);
            // die;
            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $arrEmailStatistics = array(
                "TPSysId" => 0,
                "TypeSysId" => 1,  // 1 For Email 2 For SMS
                "AgencySysId" => $this->intLoggedinUserAgencySysId,
                "AgentSysId" => $this->intLoggedinUserId,
                "Title" => $bodyText,
                "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => date('Y-m-d H:i:s')
            );

            $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
            if (!empty($mailToCC)) {
                $emailDataCC = array(
                    'fromEmail' =>  $PrimaryEmail,
                    'fromName' => $DisplayName,
                    'subject' => 'Hotel Proposal for ' . $hotelCityTitle,
                    'to' => $mailToCC,
                    'bodyHtml' => $bodyText,
                    'bodyText' => ''
                );
                $ddddd = $this->mailSentByElastice($emailDataCC, $arrEmailStatistics);
            }

            $arrUrlData['selectedRoom'] = $selectedRoom;
            $arrUrlData['proposalID'] = $proposalID;
            $arrUrlData['lastairID'] = $lastairID;
            $arrUrlData['TravelitenaryID'] = $TravelitenaryID;
            $arrUrlData['HotelQueryid'] = $HotelQueryid;
            $arrUrlData['Invoicedata'] = $InvoicedataArray;
            $tempData = array(
                'TPSysId' => $leadID,
                'TraceId' => $searchID,
                'APIBookingData' => json_encode($arrUrlData),
            );
            $objTempFlight->deleteFlightTempData($searchID);
            $objTempFlight->insertFlightTempData($tempData);
            echo json_encode(['status' => true, 'message' => 'Proposal sent successfully', 'searchID' => $searchID, 'whatsapp' => $whatsappmessage, 'contactno' => !empty(trim($custphone)) ? $countrycode . $custphone : '']);
            exit;
        } else {
            die('Invalid request');
        }
    }

    public function SetHotelBookingData($hoteldetails, $SearchParams, $post)
    {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);

        $hoteldetails['HotelDetails'] = $hoteldetails['HotelDetailsData'];
        $CancelArr = isset($hoteldetails['room'][0]['Rooms'][0]['CancelArr']) ? $hoteldetails['room'][0]['Rooms'][0]['CancelArr'] : [];
        $hotelTotalNights = $SearchParams['hotelTotalNights'];

        $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
        $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
        $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
        $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
        $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;

        $AgentUserDetail = $crmcustomerObj->getAgentDetailById($AgencySysId__);
        $UserSysId = isset($AgentUserDetail[0]['UserSysId']) ? $AgentUserDetail[0]['UserSysId'] : 0;

        // echo "<pre>";
        // print_r(($customerDetails));
        // die;

        $cityId = $SearchParams['tboCityId'];
        $hotelXrefCityId = $SearchParams['hotelXrefCityId'];
        $CityName = $SearchParams['CityName'];
        $countrySysId = $SearchParams['countrySysId'];
        $memberDetailsSearch = $SearchParams['memberDetails'];
        $checkin = $SearchParams['hotelFromDateSession'];
        $checkin = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($checkin, 'd/m/y');
        $checkout = $SearchParams['hotelToDateSession'];
        $checkout = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($checkout, 'd/m/y');
        $AgencySysId = $this->intLoggedinUserAgencySysId;
        $AgentSysId = $this->intLoggedinUserId;
        $HotelFaciality = (isset($hoteldetails['HotelDetails']['HotelFaciality']) && !empty($hoteldetails['HotelDetails']['HotelFaciality'])) ? $hoteldetails['HotelDetails']['HotelFaciality'] : [];
        $HotelDescription = isset($hoteldetails['HotelDetails']['HotelDescription']) ? $hoteldetails['HotelDetails']['HotelDescription'] : '';
        $HotelImages = isset($hoteldetails['HotelDetails']['HotelImages']) ? $hoteldetails['HotelDetails']['HotelImages'] : '';
        $HotelFacialityArray = [];
        if ($HotelFaciality) {
            foreach ($HotelFaciality as $value) {
                $HotelFacialityArray[] = array(
                    'name' => $value,
                );
            }
        }
        $ImageArray = [];
        if ($HotelImages) {
            foreach ($HotelImages as $img) {
                $ImageArray[] = array(
                    'ImageURL' => isset($img['url']) ? $img['url'] : '',
                    'sizes' => isset($img['sz']) ? $img['sz'] : '',
                );
            }
        }

        $CancelArray = [];
        if ($CancelArr['cancel']) {
            foreach ($CancelArr['cancel'] as $value) {
                $CancelArray[] = array(
                    'fromdate' => (isset($value['FromDate']) && !empty($value['FromDate'])) ? date('Y-m-d H:i:s', strtotime($value['FromDate'])) : '',
                    'todate' => (isset($value['ToDate'])  && !empty($value['ToDate'])) ? date('Y-m-d H:i:s', strtotime($value['ToDate'])) : '',
                    'amount' => $value['am'],
                    'servicefee' => isset($value['servicefee']) ? $value['servicefee'] : 0,
                    'Currency' => $value['Currency'],
                    'LastCancellationDate' => (isset($CancelArr['LastCancellationDate']) && !empty($CancelArr['LastCancellationDate'])) ? date('Y-m-d H:i:s', strtotime($CancelArr['LastCancellationDate'])) : '',
                    'Isfullrefundallowed' => isset($CancelArr['getfullrefund']) ? $CancelArr['getfullrefund'] : false,
                );
            }
        }

        $f = 1;
        $roomjson = [];
        $bookingrequest = [];
        $adultcount = 0;
        $childcount = 0;
        $rooms = 0;
        if ($memberDetailsSearch) {
            foreach ($memberDetailsSearch as $key => $pax) {
                $rooms++;
                $adultcount += $pax['AdultPax'];
                $childcount += $pax['ChildPax'];
                $TotAdultCount = isset($pax['AdultPax']) ? trim($pax['AdultPax']) : 0;
                $TotChildCount = isset($pax['ChildPax']) ? $pax['ChildPax'] : 0;


                $roomjson[$f]['Adult']  = $TotAdultCount;
                $roomjson[$f]['Child']  = $TotChildCount;
                $roomjson[$f]['Infant']  = 0;
                $roomjson[$f]['bedtype'] = '';
                $roomjson[$f]['departuredate'] = date('d/m/Y',  strtotime($checkin));
                $roomjson[$f]['returndate'] = '';
                $roomjson[$f]['fromaircode'] = '';
                $roomjson[$f]['toaircode'] = '';
                $roomjson[$f]['airclass'] = '';
                $f++;
            }
        }

        $specialrequest = isset($post['remarks']) ? $post['remarks'] : '';
        $BookingID = $hoteldetails['HotelDetails']['SearchHotelTraceId'];
        $ICSourceSysId = $hoteldetails['HotelDetails']['ICSourceSysId'];
        $currencySysId = isset($hoteldetails['HotelDetails']['currencySysId']) ? $hoteldetails['HotelDetails']['currencySysId'] : 1;
        $Currency = isset($hoteldetails['HotelDetails']['Currency']) ? $hoteldetails['HotelDetails']['Currency'] : '';
        $arrayCancellation = '';
        $HotelAddress = $hoteldetails['HotelDetails']['HotelAddress'];
        $HotelDetails = array(
            'cancellationPolicy' => $arrayCancellation,
            'AgencySysId' => $this->intLoggedinUserAgencySysId,
            'TraceId' => $BookingID,
            'ConfirmationNo' => $BookingID,
            'CheckInDate' => $checkin,
            'CheckOutDate' => $checkout,
            'BookingRefNo' => $BookingID,
            'BookingId' => $BookingID,
            'APIBookingId' => isset($hoteldetails['HotelDetails']['bookingId']) ? $hoteldetails['HotelDetails']['bookingId'] : $BookingID,
            'HotelBookingStatus' => '',
            'ResultIndex' => $hoteldetails['HotelDetails']['HotelId'],
            'HotelName' => $hoteldetails['HotelDetails']['HotelName'],
            'HotelCode' => $hoteldetails['HotelDetails']['HotelId'],
            'HotelDescription' => $HotelDescription,
            'StarRating' => $hoteldetails['HotelDetails']['HotelStars'],
            'Currency' => $Currency,
            // 'HotelPicture' => isset($hoteldetails['HotelDetails']['HotelImages'][0]['tns']) ? $hoteldetails['HotelDetails']['HotelImages'][0]['tns'] : $hoteldetails['HotelDetails']['HotelImages'][0]['url'],
            'HotelPicture' => isset($hoteldetails['HotelDetails']['HotelImages'][0]['tns']) ? $hoteldetails['HotelDetails']['HotelImages'][0]['tns'] : ($hoteldetails['HotelDetails']['HotelImages'][0]['url'] ?? ''),
            'HotelAddress' => $HotelAddress,
            'HotelContactNo' => isset($hoteldetails['HotelDetails']['HotelContact']['ph']) ? $hoteldetails['HotelDetails']['HotelContact']['ph'] : '',
            'HotelMap' => $hoteldetails['HotelDetails']['HotelAddress'],
            'Latitude' => $hoteldetails['HotelDetails']['HotelGeioLocation']['ln'],
            'Longitude' => $hoteldetails['HotelDetails']['HotelGeioLocation']['lt'],
            'HotelLocation' => isset($hoteldetails['HotelDetails']['location']) ? $hoteldetails['HotelDetails']['location'] : '',
            'PinCode' => isset($hoteldetails['HotelDetails']['postalCode']) ? $hoteldetails['HotelDetails']['postalCode'] : '',
            'Remarks' => $specialrequest,
            'NoOfNights' => $hotelTotalNights,
            'NoOfRooms' => $rooms,
            'totaladult' => $adultcount,
            'totalchild' => $childcount,
            'memberdata' => json_encode($roomjson),
            'facility' => ($HotelFacialityArray),
            'cancellation' => ($CancelArray),
            'instruction' => [],
            'images' => ($ImageArray),
            'TBBCityId' => $cityId,
            'cityid' => $cityId,
            'ContSysId' => $countrySysId,
            'cityName' => !empty($hoteldetails['HotelDetails']['HotelCity']) ? $hoteldetails['HotelDetails']['HotelCity'] : $CityName,
            'HotelCountry' => !empty($hoteldetails['HotelDetails']['HotelCountry']) ? $hoteldetails['HotelDetails']['HotelCountry'] : '',
            'gtxcity' => !empty($hotelXrefCityId) ? $hotelXrefCityId : 0,
            'IsMarkForDel' => '0',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        );

        $ARR_SALUTIONTBO = unserialize(ARR_SALUTIONTBO);
        $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
        $ARR_SALUTION_CHILD = array_flip($ARR_SALUTIONTBO);
        $ConvertionRate = 1;
        $index = 0;
        $booking_room_data = [];
        $TotalBaseFare = 0;
        $TotalTaxesandFee = 0;
        $OtherCharges = 0;
        $TotalDiscount = 0;
        $GrandTotal = 0;
        $Currncy = '';
        $TotalCommissionEarned = 0;
        $TotalFixedMarkUp = 0;
        $TotalGSTOnMarkUp = 0;
        $TotalTDSEarn = 0;
        $indexKey = 0;
        if ($memberDetailsSearch) {
            foreach ($hoteldetails['room'] as $selectKey => $roomData) {
                foreach ($memberDetailsSearch as $key => $mem) {
                    $RoomInfo = $roomData['Rooms'][$key];

                    $ExtraMarkup = isset($RoomInfo['ExtraMarkup']) ? $RoomInfo['ExtraMarkup'] : 0;
                    $ExtraMarkupOnGST = isset($RoomInfo['ExtraMarkupOnGST']) ? $RoomInfo['ExtraMarkupOnGST'] : 0;
                    $discountVal = isset($RoomInfo['discountVal']) ? $RoomInfo['discountVal'] : 0;
                    $OtherCharges = isset($RoomInfo['OtherCharges']) ? $RoomInfo['OtherCharges'] : 0;
                    $TotalPrice = (($RoomInfo['TotalBaseFare'] + $ExtraMarkup + $ExtraMarkupOnGST + $RoomInfo['FixedMarkUp'] + $RoomInfo['GSTOnMarkUp'] + $RoomInfo['TotalTaxFare'] + $OtherCharges) - $discountVal);
                    $RoomInfoData = [];

                    $RoomInfoData['numberOfAdults'] = $mem['AdultPax'];
                    $RoomInfoData['numberOfChild'] = $mem['ChildPax'];
                    $mem['numberOfAdults'] = $mem['AdultPax'];
                    $mem['numberOfChild'] = $mem['ChildPax'];

                    $ConvertionRate = $RoomInfo['ConvertionRate'];
                    $HotelRoomsDetails = array(
                        'AgencySysId' => $AgencySysId,
                        'TraceId' => $BookingID,
                        'NoOfAdults' => $RoomInfoData['numberOfAdults'],
                        'NoOfChild' => $RoomInfoData['numberOfChild'],
                        'RoomIndex' => $selectKey,
                        'RoomTypeCode' => $RoomInfo['id'],
                        'RoomTypeName' => $RoomInfo['RoomType'],
                        'RatePlanCode' => $RoomInfo['MealBase'],
                        'RatePlanName' => $RoomInfo['RoomCategory'],
                        'RatePlan' => isset($RoomInfo['RatePlan']) ? $RoomInfoData['RatePlan'] : '0',
                        'LastCancellationDate' => isset($RoomInfo['CancelArr']['LastCancellationDate']) ? date('Y-m-d H:i:s', strtotime($RoomInfo['CancelArr']['LastCancellationDate'])) : '',
                        'LastVoucherDate' => NULL,
                        'BedTypeCode' => null,
                        'SmokingPreference' => 0,
                        'CurrencyType' => $currencySysId,
                        'Currency' => $RoomInfo['Currency'],
                        'RoomPrice' => $RoomInfo['TotalBaseFare'] * $ConvertionRate,
                        'TotalPrice' => ($TotalPrice * $ConvertionRate),
                        'TaxesServiceFee' => (($RoomInfo['TotalTaxFare'] + $OtherCharges) * $ConvertionRate),
                        'intCostToCustomer' => ($TotalPrice * $ConvertionRate),
                        'AgencyMarkUp' => ($RoomInfo['FixedMarkUp'] + $ExtraMarkup) * $ConvertionRate,
                        'ServiceTaxOnAgencyMarkUp' => ($RoomInfo['GSTOnMarkUp'] + $ExtraMarkupOnGST) * $ConvertionRate,
                        'PublishedPrice' => $TotalPrice * $ConvertionRate,
                        'OfferedPrice' => $RoomInfo['TotalNetFare'] * $ConvertionRate,
                        // 'Discounts' => isset($RoomInfo['couponVal']) ? $RoomInfo['couponVal'] * $ConvertionRate : 0,
                        'Discounts' => isset($RoomInfo['couponVal']) ? ($RoomInfo['couponVal'] + $discountVal)  : $discountVal,
                        'IsMarkForDel' => '0',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    );


                    // echo "<pre>";
                    // print_r($ExtraMarkup);
                    // echo "<pre>";
                    // print_r($HotelRoomsDetails);
                    // die;
                    $TotalBaseFare += $RoomInfo['TotalBaseFare'] * $ConvertionRate;
                    $TotalFixedMarkUp += ($RoomInfo['FixedMarkUp'] + $ExtraMarkup) * $ConvertionRate;
                    $TotalGSTOnMarkUp += ($RoomInfo['GSTOnMarkUp'] + $ExtraMarkupOnGST) * $ConvertionRate;
                    $OtherCharges = isset($RoomInfo['OtherCharges']) ? $RoomInfo['OtherCharges'] : 0;
                    $TotalTaxesandFee += (($RoomInfo['TotalTaxFare'] + $OtherCharges) * $ConvertionRate);
                    $TotalDiscount += isset($RoomInfo['couponVal']) ? ($RoomInfo['couponVal'] + $discountVal)  : $discountVal;

                    $HotelPassenger = [];
                    $travellerInfo = array();
                    if ($mem['numberOfAdults']) {
                        for ($a = 0; $a < $mem['numberOfAdults']; $a++) {
                            $index++;
                            $ind = ($index - 1);

                            $HotelPassenger[$a] = array(
                                'AgencySysId' => $AgencySysId,
                                'EmailId' => isset($post['custemail']) ? $post['custemail'] : '',
                                'Salutation' => '',
                                'Title' =>  '',
                                'Contacts' => isset($post['custphone']) ? $post['custphone'] : '',
                                'Relation' => 9,
                                'FirstName' => '',
                                'LastName' => '',
                                'panno' => '',
                                'Age' => 0,
                                'IsPswExpire' => 0,
                                'CreatedByUserSysId' => $AgencySysId,
                                'Address' => 'Not Required',
                                'CityTitle' => 'Not Required',
                                'CitySysId' => 0,
                                'paxType' => 1,
                                'IsPassM' => '',
                                'StateOrZoneSysId' => 0,
                                'CountrySysId' => 0,
                                'countryCode' => '',
                                'RegisterDate' => date('Y-m-d H:i:s'),
                                'IsApproved' => '1',
                                'IsActive' => '1',
                                'IsMarkForDel' => '0',
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            );
                            $HotelPassenger[$a]['apiTraceId'] = $BookingID;
                        }
                    }

                    if ($mem['numberOfChild'] > 0) {
                        $ch = 0;
                        if ($ICSourceSysId == 3 && $this->intLoggedinUserAgencySysId != 1) {
                            $ChildAge = explode(',', $mem['ChildsAge']);
                        } else {
                            $ChildAge = explode(',', $mem['ChildsAge']);
                        }

                        for ($c = $a; $c < ($mem['numberOfChild'] + $mem['numberOfAdults']); $c++) {

                            $index++;
                            $ind = ($index - 1);

                            $HotelPassenger[$c] = array(
                                'AgencySysId' => $AgencySysId,
                                'EmailId' => isset($post['custemail']) ? $post['custemail'] : '',
                                'Salutation' => '',
                                'Title' =>  '',
                                'Contacts' => isset($post['custphone']) ? $post['custphone'] : '',
                                'Relation' => 9,
                                'FirstName' => '',
                                'LastName' => '',
                                'panno' => '',
                                'Age' => isset($ChildAge[$ch]) ? $ChildAge[$ch] : 0,
                                'IsPswExpire' => 0,
                                'CreatedByUserSysId' => $AgencySysId,
                                'Address' => 'Not Required',
                                'CityTitle' => 'Not Required',
                                'CitySysId' => 0,
                                'paxType' => 2,
                                'IsPassM' => '',
                                'StateOrZoneSysId' => 0,
                                'CountrySysId' => 0,
                                'countryCode' => '',
                                'RegisterDate' => date('Y-m-d H:i:s'),
                                'IsApproved' => '1',
                                'IsActive' => '1',
                                'IsMarkForDel' => '0',
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            );

                            $HotelPassenger[$c]['apiTraceId'] =  $BookingID;

                            $ch++;
                        }
                    }
                    ///$Currncy = 'INR';
                    $Currncy = $RoomInfo['Currency'];
                    $booking_room_data[$indexKey] = $HotelRoomsDetails;
                    $booking_room_data[$indexKey]['customer'] = $HotelPassenger;
                    $indexKey++;
                }
            }
        }


        // echo "<pre>";
        // print_r(($booking_room_data));
        // die;

        $Hotel_booking_data = array(
            'hotel_data' => $HotelDetails,
            'booking_room_data' => $booking_room_data,
        );
        $fare = array(
            'Currncy' => $Currncy,
            'BaseFare' => $TotalBaseFare,
            'TaxesandFee' => $TotalTaxesandFee,
            'GrandTotal' => (($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp) - $TotalDiscount),
            'CommissionEarned' => $TotalCommissionEarned,
            'TDSEarn' => $TotalTDSEarn,
            'Discount' => $TotalDiscount,
            'FixedMarkUp' => $TotalFixedMarkUp,
            'GSTOnMarkUp' => $TotalGSTOnMarkUp,
        );

        $BookingDetails = [
            'HotelBookingData' => $Hotel_booking_data,
            'Fare' => $fare,
        ];



        $TPSysId = $SearchParams['TPSysId'];
        $BookingDetails["AgencySysId"] = $AgencySysId;
        $BookingDetails["AgentSysId"] = $this->intLoggedinUserId;
        $BookingDetails["email"] = isset($post['custemail']) ? $post['custemail'] : '';
        $BookingDetails["mobile"] = isset($post['custphone']) ? $post['custphone'] : '';
        $BookingDetails["FirstName"] = isset($post['custname']) ? $post['custname'] : '';
        $BookingDetails["LastName"] = '';
        $BookingDetails["editLeadId"] = $TPSysId;
        $BookingDetails["IsB2BQuery"] = $IsB2BCustomer;
        $BookingDetails["B2BAgentSysId"] = $UserSysId;
        $BookingDetails["B2BAgencySysId"] = $AgencySysId__;
        $BookingDetails["leadsource"] = 'Agency';
        $BookingDetails["IsB2BProposal"] = $IsB2BCustomer;
        $BookingDetails["ICSourceSysId"] = $ICSourceSysId;
        $BookingDetails["ExchangeCurrencyRate"] = $ConvertionRate;
        $BookingDetails["TraceId"] = $BookingID;
        $BookingDetails["APIMode"] = 0;
        $BookingDetails["IsNewMigration"] = 3;
        $BookingDetails["IsOffline"] = 1;

        $ServiceTaxNo = $this->agencyDetails['ServiceTaxNo'];
        $gstvalidate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->gstvalidate('', $ServiceTaxNo);

        $misxItems_name = [];
        if ($BookingDetails['HotelBookingData']['booking_room_data']) {
            foreach ($BookingDetails['HotelBookingData']['booking_room_data'] as $key => $value) {

                $TotalGST = $value['ServiceTaxOnAgencyMarkUp'];
                $Discounts = isset($value['Discounts']) ? $value['Discounts'] : 0;
                $misxItems_name[] = [
                    'AgencySysId' => $AgencySysId,
                    'AgentSysId' => 0,
                    'MisxItems_name' => 'Hotel',
                    'Description' => $value['RoomTypeName'],
                    'ItemQty' => 1,
                    'ItemRates' => ($value['RoomPrice'] + $value['TaxesServiceFee']),
                    'Total' => $value['RoomPrice'] + $value['TaxesServiceFee'],
                    'DiscountType' => 1,
                    'Discount' => $Discounts,
                    'TotalDiscount' => $Discounts,
                    'TotalAmount' => ($value['RoomPrice'] + $value['TaxesServiceFee'] + $value['AgencyMarkUp'] + $TotalGST - $Discounts),
                    'MarkupType' => '',
                    'Markup' =>  $value['AgencyMarkUp'],
                    'TotalMarkup' =>  $value['AgencyMarkUp'],
                    'SubTotal' => ($value['RoomPrice'] + $value['TaxesServiceFee'] + $value['AgencyMarkUp'] + $TotalGST - $Discounts),
                    'ServiceFeeTotal' => 0,
                    'GSTPercentage' => '18',
                    'TotalGST' => $TotalGST,
                    'SGST' => ($gstvalidate['SGST'] == 1) ? ($TotalGST / 2) : 0,
                    'CGST' => ($gstvalidate['CGST'] == 1) ? ($TotalGST / 2) : 0,
                    'IGST' => ($gstvalidate['IGST'] == 1) ? $TotalGST : 0,
                    'ItemsSACCode' => '',
                ];
            }
        }

        $TotalInvoiceValue = $fare['GrandTotal'];
        $PublishedFare = $fare['GrandTotal'];
        $agencyMarkUpGST = $fare['GSTOnMarkUp'];
        $Discount = $fare['Discount'];
        $Invoicedata = [
            'AgentSysId' => 0,
            // 'CustomerSysId' => $CustomerSysIdGTX,
            // 'TPSysId' => $TPSysId,
            // 'MasterTPSysId' => $MasterTPSysId,
            // 'ProposalID' => $TPSysId . '/V1',
            'InvoiceDate' => date('Y-m-d'),
            'isDisplayMarkup' => true,
            'PaymentDueDate' => date('Y-m-d'),
            'PaymentDate' => date('Y-m-d'),
            'ClientGST' => 0,
            'ClientGSTNumber' => '',
            'Currency' => 1,
            'TotalInvoiceValue' => $TotalInvoiceValue,
            'InvoiceStatus' => true,
            'TotalSGST' => ($gstvalidate['SGST'] == 1) ? ($agencyMarkUpGST / 2) : 0,
            'TotalCGST' => ($gstvalidate['CGST'] == 1) ? ($agencyMarkUpGST / 2) : 0,
            'TotalIGST' => ($gstvalidate['IGST'] == 1) ? $agencyMarkUpGST : 0,
            'SumdiscountItem' => $Discount,
            'OtherDiscount' => 0,
            'otherDiscountVal' => 0,
            'TotalAdvance' => $PublishedFare,
            'TotalDueAmount' => 0,
            'InvoiceValue' => $PublishedFare,
            'notes' => 'Hotel Voucher',
            'termsandcondition' => '',
            'client_state' => '',
            'Advance' => 0,
            'PaymentType' => 4,
            'paymentNote' => 'Online',
            'misxItems_name' => $misxItems_name,

        ];

        $BookingDetails["Invoicedata"] = $Invoicedata;
        return $BookingDetails;
        // $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        // $URL = $this->baseUrl . '/gtxwebservices/hotel-api';

        // $HotelQueryids = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($BookingDetails, $getData, $URL);

        // echo "<pre>";
        // print_r(($HotelQueryids));
        // die;
        echo "<pre>";
        print_r(($HotelDetails));
        die;
    }


    public function getApiHotelInfoProposalAction()
    {


        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        $ResultIndex = trim($this->getRequest()->getParam('ResultIndex'));
        $HotelCode = trim($this->getRequest()->getParam('HotelCode'));
        $TraceId = trim($this->getRequest()->getParam('TraceId'));
        $source = trim($this->getRequest()->getParam('source'));
        $OfferPrice = trim($this->getRequest()->getParam('OfferPrice'));

        $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
        $this->view->hotelCityTitle = $sessionhotelDirectSearchData->params['hotelCityTitle'];
        $sessionhotelDirectSearchData->params['apiSourceSysId'] = $source;
        $sessionhotelDirectSearchData->params['strTraceId']     = $TraceId;
        $sessionhotelDirectSearchData->params['strResultIndex'] = $ResultIndex;
        $sessionhotelDirectSearchData->params['strHotelCode']   = $HotelCode;

        $AdultPax = $sessionhotelDirectSearchData->params['totalMemberCount']['AdultPax'];
        $ChildPax = $sessionhotelDirectSearchData->params['totalMemberCount']['ChildPax'];

        $intTotalPaxCount = $AdultPax + $ChildPax;
        $intNoOfRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];
        $intNoOfNights = $sessionhotelDirectSearchData->params['hotelTotalNights'];
        $nationality = $sessionhotelDirectSearchData->params['selectNationality'];
        $strCheckInDate = $sessionhotelDirectSearchData->params['hotelFromDateSession'];

        $arrCheckInDate = explode("/", $strCheckInDate);
        if (!empty($arrCheckInDate)) {
            $strCheckInDate = $arrCheckInDate[2] . "-" . $arrCheckInDate[1] . "-" . $arrCheckInDate[0];
        }

        $strCheckOutDate = $sessionhotelDirectSearchData->params['hotelToDateSession'];
        $arrCheckOutDate = explode("/", $strCheckOutDate);
        if (!empty($arrCheckOutDate)) {
            $strCheckOutDate = $arrCheckOutDate[2] . "-" . $arrCheckOutDate[1] . "-" . $arrCheckOutDate[0];
        }
        $intGTXCityId = $sessionhotelDirectSearchData->params['hotelXrefCityId'];
        $intCountryId = $sessionhotelDirectSearchData->params['selectNationality'];
        $strCountryCode = $sessionhotelDirectSearchData->params['countryCode'];



        $arrPriceAndMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($OfferPrice, "0", $intNoOfNights, $intNoOfRooms, $strCountryCode);
        //echo "<pre>";print_r($arrPriceAndMarkUps);echo "</pre>";exit;
        if (!empty($arrPriceAndMarkUps)) {
            $intBasePrice = $arrPriceAndMarkUps['intBasePrice'];
            $intSTaxOnBasePrice = $arrPriceAndMarkUps['intSTaxOnBasePrice'];
            $intPriceWithMarkUpsAndSTax = $arrPriceAndMarkUps['intPriceWithMarkUpsAndSTax'];
            $intGTXMarkUp = $arrPriceAndMarkUps['intGTXMarkUp'];
            $intSTaxOnGTXMarkUp = $arrPriceAndMarkUps['intSTaxOnGTXMarkUp'];
            $intGTXMarkUpWithSTax = $arrPriceAndMarkUps['intGTXMarkUpWithSTax'];
            $intAgencyMarkUp = $arrPriceAndMarkUps['intAgencyMarkUp'];
            $intSTaxOnAgencyMarkUp = $arrPriceAndMarkUps['intSTaxOnAgencyMarkUp'];
            $intAgencyMarkUpWithSTax = $arrPriceAndMarkUps['intAgencyMarkUpWithSTax'];
            $intNetSTax = $arrPriceAndMarkUps['intNetSTax'];
        } else {
            $intBasePrice = $arrPriceAndMarkUps['intBasePrice'];
            $intSTaxOnBasePrice = $arrPriceAndMarkUps['intSTaxOnBasePrice'];
            $intPriceWithMarkUpsAndSTax = 0;
            $intGTXMarkUp = 0;
            $intSTaxOnGTXMarkUp = 0;
            $intGTXMarkUpWithSTax = 0;
            $intAgencyMarkUp = 0;
            $intSTaxOnAgencyMarkUp = 0;
            $intAgencyMarkUpWithSTax = 0;
            $intNetSTax = 0;
        }



        if ($source == 3) {
            $data = [
                "ResultIndex" => $ResultIndex,
                "HotelCode" => $HotelCode,
                "TraceId" => $TraceId,
                "source" => $source
            ];


            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getApiHotelInfo($data);
            $arrResponse = json_decode($apiResponse, true);
            //            echo "<pre>";print_r($arrResponse);exit;
            $ResponseStatus = $arrResponse['HotelInfoResult']['ResponseStatus'];
            $ErrorCode = isset($arrResponse['HotelInfoResult']['Error']['ErrorCode']) ? $arrResponse['HotelInfoResult']['Error']['ErrorCode'] : 1;
            if ($ResponseStatus == 1 && $ErrorCode == 0) {
                $arrHotelDetails = $arrResponse['HotelInfoResult']['HotelDetails'];

                $arrHotelDetails['TraceId'] = $arrResponse['HotelInfoResult']['TraceId'];
                $arrHotelDetails['ResultIndex'] = $ResultIndex;
                $arrHotelDetails['source'] = $source;

                $arrHotelDetails['totalpax'] = $intTotalPaxCount;
                $arrHotelDetails['totalrooms'] = $intNoOfRooms;
                $arrHotelDetails['nights'] = $intNoOfNights;
                $arrHotelDetails['nationality'] = $nationality;
                $arrHotelDetails['checkin'] = $strCheckInDate;
                $arrHotelDetails['checkout'] = $strCheckOutDate;
                $arrHotelDetails['gtxcity'] = $intGTXCityId;
                $arrHotelDetails['countrycode'] = $intCountryId;
                $arrHotelDetails['PublishedFare'] = $intBasePrice + $intGTXMarkUp;

                $intAccomSysId = $this->insertHotelDetailsAction($arrHotelDetails);
            } else {
                echo json_encode(array('status' => false, 'msg' => 'information not available!'));
                exit;
            }
        } else if ($source == 4) {
            $arrResponseData = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiHotelRoomInfo($sessionhotelDirectSearchData->params);
            $arrHotelInfoGRN = (isset($arrResponseData['hotels'][0]) && !empty($arrResponseData['hotels'][0])) ? $arrResponseData['hotels'][0] : [];

            $sessionhotelDirectSearchData->params['strTraceId']     = $arrResponseData['search_id'];
            if (!empty($arrHotelInfoGRN) && isset($arrHotelInfoGRN)) {

                $arrHotelDetails['TraceId'] = $arrResponseData['search_id'];
                $arrHotelDetails['ResultIndex'] = $ResultIndex;
                $arrHotelDetails['source'] = $source;

                $arrHotelDetails['totalpax'] = $intTotalPaxCount;
                $arrHotelDetails['totalrooms'] = $intNoOfRooms;
                $arrHotelDetails['nights'] = $intNoOfNights;
                $arrHotelDetails['nationality'] = $nationality;
                $arrHotelDetails['checkin'] = $strCheckInDate;
                $arrHotelDetails['checkout'] = $strCheckOutDate;
                $arrHotelDetails['gtxcity'] = $intGTXCityId;
                $arrHotelDetails['countrycode'] = $intCountryId;
                $arrHotelDetails['PublishedFare'] = $intBasePrice + $intGTXMarkUp;

                $arrHotelDetails['HotelName'] = isset($arrHotelInfoGRN['name']) ? $arrHotelInfoGRN['name'] : '';
                $arrHotelDetails['HotelPicture'] = isset($arrHotelInfoGRN['images']['url']) ? $arrHotelInfoGRN['images']['url'] : '';
                $arrHotelDetails['HotelCode'] = isset($arrHotelInfoGRN['hotel_code']) ? $arrHotelInfoGRN['hotel_code'] : '';
                $arrHotelDetails['Longitude'] = isset($arrHotelInfoGRN['geolocation']['longitude']) ? $arrHotelInfoGRN['geolocation']['longitude'] : '';
                $arrHotelDetails['Latitude'] = isset($arrHotelInfoGRN['geolocation']['latitude']) ? $arrHotelInfoGRN['geolocation']['latitude'] : '';
                $arrHotelDetails['Description'] = isset($arrHotelInfoGRN['description']) ? $arrHotelInfoGRN['description'] : '';
                $arrHotelDetails['StarRating'] = isset($arrHotelInfoGRN['category']) ? $arrHotelInfoGRN['category'] : '';
                $arrHotelDetails['Address'] = isset($arrHotelInfoGRN['address']) ? $arrHotelInfoGRN['address'] : '';
                $intAccomSysId = $this->insertHotelDetailsAction($arrHotelDetails);
            } else {
                echo json_encode(array('status' => false, 'msg' => 'information not available!'));
                exit;
            }
        } else if ($source == 'Inv') {
            $intAccomSysId = $TraceId;
            $InvnItemSysId = $ResultIndex;
        }




        $_SESSION['SELECTED_HTL_ID'] = $intAccomSysId;

        $objHotel = new Travel_Model_TblBuyHotel();
        // For Hotel Basic Details From DB...


        if ($source == 'Inv') {


            //                $sessionhotelDirectSearchData = new Zend_Session_Namespace('sessionHotelDirectSearchData');
            $intNoOfNights = $sessionhotelDirectSearchData->params['hotelTotalNights'];
            $intNoOfRooms = $sessionhotelDirectSearchData->params['hotelTotalRooms'];
            $strcountryCode = $sessionhotelDirectSearchData->params['countryCode'];
            $arrmemberDetails = $sessionhotelDirectSearchData->params['memberDetails'];

            if (!empty($arrmemberDetails)) {
                $arrMembers = [];
                $IntRoom = 0;
                foreach ($arrmemberDetails as $memDetails) {
                    $arrMembers[$IntRoom]['Adult'] = $memDetails['AdultPax'];
                    $arrMembers[$IntRoom]['Child'] = $memDetails['ChildPax'];
                    $IntRoom++;
                }
            }


            $hotelInfo = $objHotel->getINVHotelInfoById($intAccomSysId, $InvnItemSysId);


            $PublishedPrice = Zend_Controller_Action_HelperBroker::getStaticHelper("Hotel")->getTotalCostOfHotelByTravelersNew($hotelInfo, $arrMembers);
            $PublishedPrice = round($PublishedPrice * $intNoOfNights);
            //  $PublishedPrice = round($PublishedPrice*$intNoOfNights*$intNoOfRooms);


            //echo $PublishedPrice;exit;
            $arrPriceAndMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper('Hotel')->getApiPriceWithMarkupAndServiceTax($PublishedPrice, "0", $intNoOfNights, $intNoOfRooms, $strcountryCode);
            //echo "<pre>";print_r($arrPriceAndMarkUps);exit;
            $intPriceWithMarkUpsAndSTax = round($arrPriceAndMarkUps['intPriceWithMarkUpsAndSTax']);
            $intAgencyMarkUp = ($arrPriceAndMarkUps['intAgencyMarkUp']);


            $hotelPreviewDetails = array(
                'AccomSysId' => trim($intAccomSysId),
                'InvnItemSysId' => trim($hotelInfo['InvnItemSysId']),
                'SupplierSysId' => trim($hotelInfo['SupplierSysId']),
                'InvHotelRoomType' => isset($hotelInfo['InvHotelRoomType']) ? trim($hotelInfo['InvHotelRoomType']) : '',
                'intICSourceSysId' => $source,
                'CurrencyType' => trim($hotelInfo['CurrencyType']),
                'hotelId' => trim($intAccomSysId),
                'hotelName' => $hotelInfo['Title'],
                'EconomyTypeTitle' => !empty($hotelInfo['EconomyTypeTitle']) ? $hotelInfo['EconomyTypeTitle'] : '',
                'MealPlanTypeTitle' => !empty($hotelInfo['MealPlanTypeTitle']) ? $hotelInfo['MealPlanTypeTitle'] : '',
                'hotelCode' => trim($HotelCode),
                'hotelResultIndex' => $ResultIndex,
                'hotelStrUserIp' => $_SERVER['REMOTE_ADDR'],
                'hotelTokenId' => !empty($hotelInfo['TokenId']) ? $hotelInfo['TokenId'] : '',
                'hotelTraceId' => !empty($TraceId) ? $TraceId : '',
                'stars' => $hotelInfo['Stars'],
                'rating' => $hotelInfo['Stars'],
                'title' => '',
                //'netFare'=>$intBasePrice,
                'netFare' => trim($PublishedPrice),
                'netTaxOnBasePrice' => isset($intSTaxOnBasePrice) ? $intSTaxOnBasePrice : 0,
                'AgencyMarkUp' => $intAgencyMarkUp,
                'GTXMarkUp' => $intGTXMarkUp,
                'TotalTaxes' => $intSTaxOnAgencyMarkUp + $intSTaxOnGTXMarkUp + $intSTaxOnBasePrice,
                'priceDetails' => $arrPriceAndMarkUps,
                'commission' => round($hotelInfo['MinCommissionEarned']),
                'netPrice' => trim($PublishedPrice),
                'addMarkup' => isset($markupAgency[0]['DOccupMarkUp']) ? round($markupAgency[0]['DOccupMarkUp']) : '',
                'markupType' => isset($markupAgency[0]['MarkUpType']) ? round($markupAgency[0]['MarkUpType']) : '',
                'finalPrice' => $intPriceWithMarkUpsAndSTax,
                'checkInDate' => isset($sessionhotelDirectSearchData->params['hotelFromDateSession']) ? $sessionhotelDirectSearchData->params['hotelFromDateSession'] : '',
                'checkOutdate' => isset($sessionhotelDirectSearchData->params['hotelToDateSession']) ? $sessionhotelDirectSearchData->params['hotelToDateSession'] : '',
                'address' => $hotelInfo['Address'],
                'nights' => isset($sessionhotelDirectSearchData->params['hotelTotalNights']) ? $sessionhotelDirectSearchData->params['hotelTotalNights'] : 0,
                'cityName' => isset($sessionhotelDirectSearchData->params['hotelCityTitle']) ? $sessionhotelDirectSearchData->params['hotelCityTitle'] : '',
                'sessionhotelDirectSearchData' => $sessionhotelDirectSearchData->params
            );
            //echo "<pre>";print_r($hotelPreviewDetails);exit;
            echo base64_encode(json_encode($hotelPreviewDetails));
            exit;
        } else {
            $hotelInfo = $objHotel->getHotelInfoById($intAccomSysId);
        }


        $markupAgency = $objHotel->getAgencyMarkup();

        $hotelPreviewDetails = array(
            'InvnItemSysId' => trim($intAccomSysId),
            'SupplierSysId' =>  isset($hotelInfo['SupplierSysId']) ? trim($hotelInfo['SupplierSysId']) : 0,
            'InvHotelRoomType' => isset($hotelInfo['InvHotelRoomType']) ? trim($hotelInfo['InvHotelRoomType']) : '',
            'intICSourceSysId' => $source,
            'CurrencyType' => trim($hotelInfo['CurrencyType']),
            'hotelId' => trim($intAccomSysId),
            'hotelName' => $hotelInfo['Title'],
            'EconomyTypeTitle' => !empty($hotelInfo['EconomyTypeTitle']) ? $hotelInfo['EconomyTypeTitle'] : '',
            'MealPlanTypeTitle' => !empty($hotelInfo['MealPlanTypeTitle']) ? $hotelInfo['MealPlanTypeTitle'] : '',
            'hotelCode' => trim($HotelCode),
            'hotelResultIndex' => $ResultIndex,
            'hotelStrUserIp' => $_SERVER['REMOTE_ADDR'],
            'hotelTokenId' => !empty($hotelInfo['TokenId']) ? $hotelInfo['TokenId'] : '',
            'hotelTraceId' => !empty($TraceId) ? $TraceId : '',
            'stars' => $hotelInfo['Stars'],
            'rating' => $hotelInfo['Stars'],
            'title' => '',
            //'netFare'=>$intBasePrice,
            'netFare' => trim($hotelInfo['MinPublishedFare']),
            'netTaxOnBasePrice' => isset($intSTaxOnBasePrice) ? $intSTaxOnBasePrice : 0,
            'AgencyMarkUp' => $intAgencyMarkUp,
            'GTXMarkUp' => $intGTXMarkUp,
            'TotalTaxes' => $intSTaxOnAgencyMarkUp + $intSTaxOnGTXMarkUp + $intSTaxOnBasePrice,
            'priceDetails' => $arrPriceAndMarkUps,
            'commission' => round($hotelInfo['MinCommissionEarned']),
            'netPrice' => trim($hotelInfo['MinPublishedFare']),
            'addMarkup' => isset($markupAgency[0]['DOccupMarkUp']) ? round($markupAgency[0]['DOccupMarkUp']) : '',
            'markupType' => isset($markupAgency[0]['MarkUpType']) ? round($markupAgency[0]['MarkUpType']) : '',
            'finalPrice' => $intPriceWithMarkUpsAndSTax,
            'checkInDate' => isset($sessionhotelDirectSearchData->params['hotelFromDateSession']) ? $sessionhotelDirectSearchData->params['hotelFromDateSession'] : '',
            'checkOutdate' => isset($sessionhotelDirectSearchData->params['hotelToDateSession']) ? $sessionhotelDirectSearchData->params['hotelToDateSession'] : '',
            'address' => $hotelInfo['Address'],
            'nights' => isset($sessionhotelDirectSearchData->params['hotelTotalNights']) ? $sessionhotelDirectSearchData->params['hotelTotalNights'] : 0,
            'cityName' => isset($sessionhotelDirectSearchData->params['hotelCityTitle']) ? $sessionhotelDirectSearchData->params['hotelCityTitle'] : '',
            'sessionhotelDirectSearchData' => $sessionhotelDirectSearchData->params
        );
        //echo "<pre>";print_r($hotelPreviewDetails);exit;

        echo base64_encode(json_encode($hotelPreviewDetails));
        exit;
    }


    public function insertHotelDetailsAction($hotelData = [])
    {




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


            $objHotel = new Travel_Model_TblBuyHotel();
            $HotelCode = !empty($hotelData["HotelCode"]) ? $hotelData["HotelCode"] : 0;
            $TraceId = !empty($hotelData["TraceId"]) ? $hotelData["TraceId"] : '';
            $HotelAccomSysIdIfAlreadyExists = $objHotel->checkIfHotelAlreadyExists($HotelCode, $TraceId);  // Get All Hotels Info On perticular City Id And Check If Hotel Alredy Exists in Our DB B4 inserting...
            if (!empty($HotelAccomSysIdIfAlreadyExists)) {
                return $HotelAccomSysIdIfAlreadyExists;
            }



            $CreateDate = date('Y-m-d H:i:s');

            $data = array(
                'IsAgentSpec' => '0',
                'ICSourceSysId' => $hotelData["source"],
                'ShortName' => trim($hotelData["HotelCode"]),
                'Title' => trim($hotelData['HotelName']),
                'ResultIndex' => trim($hotelData['ResultIndex']),
                'TraceId' => trim($hotelData['TraceId']),
                'TokenId' => '',
                'AliasAndMeta' => '',
                'PlaceSysId_XRef' => 0,
                'Icon' => '',
                'ThumnailImg' => '',
                'DetailImg' => !empty($hotelData['HotelPicture']) ? trim($hotelData['HotelPicture']) : '',
                'Stars' => !empty($hotelData['StarRating']) ? trim($hotelData['StarRating']) : '0',
                'Rating' => '0',
                'Popularity' => '0',
                'AwardRecognizations' => !empty($hotelData['AwardRecognizations']) ? 'TripAdvisor' : '',
                'AwardURL' => !empty($hotelData['AwardURL']) ? trim($hotelData['AwardURL']) : '',
                'PropertyType' => '1',
                'EconomyType' => '1',
                'AccoAminitiesMask' => '',
                'MaxPaxCount' => trim($hotelData['totalpax']),
                'RoomCounts' => trim($hotelData['totalrooms']),
                'NightCount' => trim($hotelData['nights']),
                'Nationality' => trim($hotelData['nationality']),
                'Brief' => trim($hotelData['Description']),
                'CheckinTime' => trim($hotelData['checkin']),
                'CheckOutTime' => trim($hotelData['checkout']),
                'CurrencyType' => 1,
                'MinPublishedFare' => trim($hotelData['PublishedFare']),
                "MinCommissionEarned" => 0,
                'IsDayLightApp' => '0',
                'GeoLat' => trim($hotelData['Latitude']),
                'GeoLong' => trim($hotelData['Longitude']),
                'Address' => ucfirst($hotelData['Address']),
                'Location' => '',
                'PinCode' => '',
                'APICityId' => 0,
                'CitySysId' => $hotelData['gtxcity'],
                'ZoneSysId' => '0',
                'ZoneType' => '0',
                'StateSysId' => '0',
                'ContSysId' => '0',
                'PrimaryContact' => '0',
                'SecondaryContact' => '0',
                'OtherContacts' => '0',
                'ApproveBy' => '1',
                'CreateDate' => $CreateDate,
                'UpdateDate' => $CreateDate,
                'ApproveDate' => $CreateDate,
                'IsApproved' => '1',
                'IsActive' => '1',
                'IsExpired' => '0',
                'IsMarkForDel' => '0'
            );
            // echo "<pre>";print_r($data);exit;

            $intLastInsertedId = $objHotel->insertApiHotels($data);
            $objHotel->deleteApiHotelsImages($intLastInsertedId);
            if (!empty($intLastInsertedId)) {
                $imgData = array(
                    'AccomSysId' => $intLastInsertedId,
                    'Seq' => 1,
                    'ImgType' => 2,
                    'HotelCode' => trim($hotelData["HotelCode"]),
                    'CitySysId' => $hotelData['gtxcity'],
                    'ImageType' => 'FullImage',
                    'ImageURL' => !empty($hotelData['HotelPicture']) ? trim($hotelData['HotelPicture']) : '',
                    'UpdateDate' => $CreateDate,
                    'CreateDate' => $CreateDate,
                    'IsActive' => 1,
                    'IsMarkForDel' => 0,
                );

                $objHotel->insertApiHotelsImages($imgData);
            }

            return $intLastInsertedId;
        }
    }


    // New Function For Api Hotels Ends.............



    public function emailVoucherAction()
    {


        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        if ($this->_request->isXmlHttpRequest()) {

            $emailId = trim($this->getRequest()->getParam('emailId'));
            $FromName = trim($this->getRequest()->getParam('FromName'));
            $FromEmail = trim($this->getRequest()->getParam('FromEmail'));
            $bodyText = $this->getRequest()->getParam('bodyText');


            if (empty($emailId)) {
                $response = array('success' => false, 'msg' => 'Please enter Email ID.');
                echo json_encode($response);
                exit;
            }

            if (!filter_var($emailId, FILTER_VALIDATE_EMAIL)) {
                $msg =  "Email address is not valid.";
                $response = array('success' => false, 'msg' => $msg);
                echo json_encode($response);
                exit;
            }



            $emailData = array('fromEmail' => $FromEmail, 'fromName' => $FromName, 'subject' => 'Hotel Booking Voucher', 'to' => array($emailId), 'bodyHtml' => $bodyText, 'bodyText' => '');

            $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
            $arrEmailStatistics = array(
                "TPSysId" => 0,
                "TypeSysId" => 1,  // 1 For Email 2 For SMS
                "AgencySysId" => $this->intLoggedinUserAgencySysId,
                "AgentSysId" => $this->intLoggedinUserId,
                "Title" => $bodyText,
                "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => date('Y-m-d H:i:s')
            );

            $emailResponse = json_decode($this->mailSentByElastice($emailData, $arrEmailStatistics), true);
            try {
                if ($emailResponse['success']) {
                    $msg =  "Voucher Emailed successfully.";
                    $response = array('success' => true, 'msg' => $msg);
                    echo json_encode($response);
                    exit;
                }
            } catch (Exception $err) {
                if ($mail->send($transport)) {
                    $msg =  "Oops! there might be some technical issue, please try after some time.";
                    $response = array('success' => false, 'msg' => $msg);
                    echo json_encode($response);
                    exit;
                }
            }
        }
    }



    public function bookOfflineAction()
    {

        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        $searchIDSearch = $this->view->searchIDSearch = $this->getRequest()->getParam('data');
        $MasterTPSysId = $this->view->MasterTPSysId = $this->getRequest()->getParam('MasterTPSysId');
        $objTempFlight = new Travel_Model_TblFlight();
        $FlightTempData = $objTempFlight->GetFlightTempDataByTPSysId(base64_decode($MasterTPSysId));
        if ($searchIDSearch) {

            $PostData = ['TPSysId' => base64_decode($searchIDSearch), 'MasterTPSysId' => base64_decode($MasterTPSysId)];
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/hotel-api/hotel-voucher-offline';
            $HOTEL_VOUCHER = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $HotelData = isset($HOTEL_VOUCHER['data']) ? $HOTEL_VOUCHER['data'] : [];
            $TaxPercentage = isset($HOTEL_VOUCHER['TaxSettingDetail'][0]['TaxPercentage']) ? $HOTEL_VOUCHER['TaxSettingDetail'][0]['TaxPercentage'] : 0;

            // echo "<pre>";
            // print_r($this->agencyDetails['SecurityKey']);
            // echo "<pre>";

            $TPSysId = base64_decode($searchIDSearch);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $SearchParams = $arrUrlData['SearchParams'];
            $HotelQueryid = isset($arrUrlData['HotelQueryid'][base64_decode($searchIDSearch)]) ? $arrUrlData['HotelQueryid'][base64_decode($searchIDSearch)] : [];
            $arrUrlData['HotelQueryids'] = $HotelQueryid;

            // echo "<pre>";
            // print_r($arrUrlData);
            // echo "<pre>";
            // die;
            if ($this->_request->isXmlHttpRequest()) {

                $post = $this->getRequest()->getPost();
                $post = json_decode(file_get_contents('php://input'), true);
                $selectedIndex = isset($post['selectedIndex']) ? $post['selectedIndex'] : 0;

                if ($TPSysId && $searchIDSearch) {
                    $TotalBaseFare = 0;
                    $TotalTaxesandFee = 0;
                    $TotalDiscount = 0;
                    $Currncy = '';
                    $TotalCommissionEarned = 0;
                    $TotalFixedMarkUp = 0;
                    $TotalGSTOnMarkUp = 0;
                    $TotalTDSEarn = 0;
                    $BaseFareArray = [];
                    $AdjustmentsAmount = isset($HotelData['HotelData']['AdjustmentsAmount']) ? $HotelData['HotelData']['AdjustmentsAmount'] : 0;
                    $PaymentStatus = isset($HotelData['HotelData']['PaymentStatus']) ? $HotelData['HotelData']['PaymentStatus'] : '';
                    $CurrentStatus = isset($HotelData['HotelData']['CurrentStatus']) ? $HotelData['HotelData']['CurrentStatus'] : '';
                    $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                    $RoomOptionArray = isset($HotelData['RoomOptionArray']) ? $HotelData['RoomOptionArray'] : [];
                    // if (empty($HotelData) || ($CurrentStatus == 24)) {
                    //     $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => 'This Trace id already expired', 'urlData' => $strUrlData, 'formAction' => "/flight-new/booking-confirmation/data/" . $TPSysId . "");
                    //     echo json_encode($response);
                    //     exit;
                    // }
                    $RoomArraySelected = [];

                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $RoomArraySelected[$values['RoomIndex']][] = $values;
                        }
                        $HotelData['accom_room'] = isset($RoomArraySelected[$selectedIndex]) ? $RoomArraySelected[$selectedIndex] : [];
                    }

                    $accom_room = isset($HotelData['accom_room']) ? $HotelData['accom_room'] : [];
                    if ($accom_room) {
                        foreach ($accom_room as $key => $values) {
                            $Currncy = $values['Currency'];
                            $BaseFare = ($values['RoomPrice']);
                            $TotalDiscount += ($values['Discounts']);
                            $TotalBaseFare += ($values['RoomPrice']);
                            $TotalFixedMarkUp += ($values['AgencyMarkUp']);
                            $TotalGSTOnMarkUp += ($values['GSTOnAgencyMarkUp']);
                            $TotalTaxesandFee += (($values['Taxes']));
                            $BaseFareArray[$key] = ['BaseFare' => $BaseFare, 'Taxes' => $values['Taxes'], 'name' => $values['RoomTypeName'], 'MealBase' => $values['MealPlanType']];
                        }
                    }
                    $fare = array(
                        'Currncy' => $Currncy,
                        'BaseFare' => round($TotalBaseFare, 2),
                        'TaxesandFee' => round($TotalTaxesandFee, 2),
                        'GrandTotal' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp + $AdjustmentsAmount - $TotalDiscount, 2),
                        'TotalPayable' => round($TotalBaseFare + $TotalTaxesandFee + $TotalFixedMarkUp + $TotalGSTOnMarkUp + $AdjustmentsAmount - $TotalDiscount, 2),
                        'CommissionEarned' => round($TotalCommissionEarned, 2),
                        'Adjustments' => round($AdjustmentsAmount, 2),
                        'TDSEarn' => round($TotalTDSEarn, 2),
                        'Discount' => round($TotalDiscount, 2),
                        'FixedMarkUp' => round($TotalFixedMarkUp, 2),
                        'GSTOnMarkUp' => round($TotalGSTOnMarkUp, 2),
                        'roomCoun' => count($accom_room),
                        'nightCoun' => ($HotelData['HotelData']['TotalNights']),
                        'BaseFareArray' => ($BaseFareArray),
                    );
                    // echo "<pre>post";
                    // print_r(($accom_room));
                    // die;

                    echo json_encode([
                        'status' => true,
                        'message' => 'SUCESS',
                        'fare' => $fare,
                        'HotelData' => $HotelData,
                        'RoomOptionArray' => $RoomOptionArray,
                        'TaxPercentage' => $TaxPercentage,
                    ]);
                    exit;
                }
            }

            $RoomOptionArray = isset($HotelData['RoomOptionArray']) ? $HotelData['RoomOptionArray'] : [];
            $CurrencyType = isset($HotelData['HotelData']['CurrencyType']) ? $HotelData['HotelData']['CurrencyType'] : 1;
            $SupplierSysId = isset($HotelData['HotelData']['SupplierSysId']) ? $HotelData['HotelData']['SupplierSysId'] : 0;
            $EmailId = isset($HotelData['HotelData']['EmailId']) ? $HotelData['HotelData']['EmailId'] : '';
            $Contacts = isset($HotelData['HotelData']['Contacts']) ? $HotelData['HotelData']['Contacts'] : 0;
            $TPIntSysId = isset($HotelData['HotelData']['VersionId']) ? $HotelData['HotelData']['VersionId'] : 0;

            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinUserAgencySysId);
            $getAgentDetailById = $crmcustomerObj->getAgentDetailById($this->intLoggedinUserId);
            $this->view->IsAllowFlightBooking = isset($getAgentDetailById[0]['IsAllowFlightBooking']) ? $getAgentDetailById[0]['IsAllowFlightBooking'] : 0;
            $this->view->IsCheckWallet = isset($getAgencyDetail['IsCheckWallet']) ? $getAgencyDetail['IsCheckWallet'] : 0;
            $intCustomerSysId = isset($SearchParams['customerId']) ? $SearchParams['customerId'] : 0;
            $customerDetails = $crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);
            $AgencySysId = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            $IsEnabledWallet = isset($customerDetails['IsEnabledWallet']) ? $customerDetails['IsEnabledWallet'] : 0;
            $CustomerSysId = isset($customerDetails['CustomerSysId']) ? $customerDetails['CustomerSysId'] : 0;
            $this->view->IsB2BCustomer = $IsB2BCustomer;
            $this->view->IsEnabledWallet = $IsEnabledWallet;
            $this->view->walletBalanceAmount = '0.00';
            $this->view->RoomOptionArray = $RoomOptionArray;
            $this->view->TPIntSysId = $TPIntSysId;

            $model = new Gtxwebservices_Model_Webservices();
            if ($IsB2BCustomer == 1) {
                $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId);
                $B2BAgencySysIdKey = $getAgencyDetail['SecurityKey'];
                $B2CAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
                $apiDataIV = array(
                    "B2BAgencySysIdKey" => $B2BAgencySysIdKey,
                    "B2CAgencySysIdKey" => $B2CAgencySysIdKey,
                );

                $result = json_decode($model->GetB2Bbalance($apiDataIV), true);
                $this->view->walletBalanceAmount = $result['creditBalance'];
            } elseif ($IsEnabledWallet == 1) {
                $apiDataIV = array(
                    "CustomerSysId" => $CustomerSysId,
                );

                $result = json_decode($model->GetB2Cbalance($apiDataIV, $this->agencyDetails['SecurityKey']), true);
                $this->view->walletBalanceAmount = (isset($result['WalletBalance'][0]['BalanceAmount']) && !empty($result['WalletBalance'][0]['BalanceAmount'])) ? $result['WalletBalance'][0]['BalanceAmount'] : 0;
            }
            // echo "<pre>post";
            // print_r(($HOTEL_VOUCHER));
            // die;
            $this->view->EmailId = $EmailId;
            $this->view->Contacts = $Contacts;
            $this->view->intLoggedinUserId = $this->intLoggedinUserId;
            $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupSysId;
            $this->view->intLoggedinUserAgencySysId = $this->intLoggedinUserAgencySysId;
            $this->view->searchID = $searchIDSearch;
            $this->view->TPSysId = $TPSysId;
            $this->view->ActionName = 'book-offline';

            $fullBaseUrl = $this->view->baseUrl();
            $this->view->strPayWithWalletUrl = $fullBaseUrl . "/payment/wallet-pay";
            $this->view->strRechargeNowUrl = $fullBaseUrl . "/payment/payment-options";
            $this->view->strSearchPageUrl = $fullBaseUrl . "/buyhotel/search-result";
            $this->view->strReturnURL = $fullBaseUrl . "/buyhotel/book-hotel/data/" . $searchIDSearch . '/MasterTPSysId/' . $MasterTPSysId . '?IsOffline=1';
            $this->view->strErrorURL = $fullBaseUrl . "/buyhotel/review/data/" . $searchIDSearch . '/MasterTPSysId/' . $MasterTPSysId . '?IsOffline=1';
            $this->view->strPayWithPaymentGatewayUrl = Catabatic_Helper::getSiteUrl() . "payment/payment-options/customer-pay";
            $this->view->strReturnURLCustomerPayment = $fullBaseUrl . "/buyhotel/check-flight-payment/data/" . $searchIDSearch;
            $this->view->intPlanType = "1";
            $this->view->strTrxType = "A";

            $Customer = new Zend_Session_Namespace('Customer');
            $this->view->intTpSysId = $intTpSysId = $Customer->intTPSysId;
            $this->view->intCustomerSysId = $intCustomerSysId = $Customer->intCustomerSysId;

            $objTblSupplier = new Travel_Model_TblSupplier();
            $TblCurrency = new Travel_Model_TblCurrency();
            $this->view->Currency = $Currency = $TblCurrency->getCurrencyTypes();
            $this->view->TrxCurrency = $CurrencyType;
            $this->view->supplier_id = $SupplierSysId;
            $supplierData = $objTblSupplier->getSupplierList($SupplierSysId);
            $this->view->supplier_name = isset($supplierData['SupplierName']) ? $supplierData['SupplierName'] : '';
        }
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit