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

/**
 * Class Flight
 *
 * @name		Flight
 * @author		Praveen Kumar
 * @version 	1.0
 * @copyright 	Catabatic India Pvt Ltd
 * Handle Flight Related function
 *
 */
class FlightNewController extends Catabatic_ValidateGtx {

    private $SMSURL;
    private $SMSMETHOD;
    private $SMSAPIKEY;
    private $SMSSENDER;
    private $SMSFORMAT;
    private $IsSMSApi;
    private $intLoggedinUserId = 0;
    private $intLoggedinAgencyId = 0;
    private $agencyDetails = '';
    public $baseUrl = '';
    public $intLoggedinUserFirstName = '';
    public $intLoggedinUserGroupId = '';
    public $intLoggedinUserTrxCurrency = '';
    public $intLoggedinUserEmailId = '';
    public $intLoggedinUserContactNo = '';
    public $InfoSourceSysId = '';
    public $_crmcustomerObj;
    public $_crmcustomertravelItenary;
    public $_crmcusttravelplan;
    public $_crmcusttravelplanAir;
    public $objFlight;
    public $CurrencyTitle;
    public $CurrencyRate;
    public $CurrencyId;
    public $BITLYLOGIN;
    public $BITLYAPIKEY;
    public $_crmremarkObj;
    public $paymentMdl;
    public $smtpUserName;
    public $smtpPassword;
    public $smtpPort;
    public $smtpHost;
    public $fromEmail;
    public $fromName;

    public function init() {

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

        $this->view->headScript()->appendFile($this->baseUrl . '/public/js/flight/flight.js');

        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $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();

        //Zend_Session::rememberMe(60 * 60 * 24 * 7);
        // marking session as read only locked
        $sessionLogin_user->lock();

        //echo "==========".$sessionLogin_user->intLoggedinUserAgencySysId;
        #get session variable

        $this->intLoggedinUserId = $sessionLogin_user->intLoggedinUserId;
        $this->intLoggedinUserGroupId = $sessionLogin_user->intLoggedinUserGroupSysId;
        $this->intLoggedinAgencyId = $sessionLogin_user->intLoggedinUserAgencySysId;
        $this->view->intLoggedinUserTrxCurrency = $this->intLoggedinUserTrxCurrency = $sessionLogin_user->intLoggedinUserTrxCurrency;

        $this->intLoggedinUserFirstName = $sessionLogin_user->FirstName;
        $this->intLoggedinUserEmailId = $sessionLogin_user->EmailId;
        $this->intLoggedinUserContactNo = $sessionLogin_user->ContactNo1;
        $this->agencyDetails = $sessionLogin_user->agencyDetails;
        $this->IsSMSApi = $sessionLogin_user->agencyDetails['IsSMSApi'];
        if (!empty($this->intLoggedinAgencyId)) {
            $this->InfoSourceSysId = '2'; // Information Source is Agent //
        }

        // unlocking read-only lock
        if ($sessionLogin_user->isLocked()) {
            $sessionLogin_user->unLock();
        }
        $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
        $this->_crmcustomertravelItenary = new Travel_Model_CRM_CustomerTravelItenary();
        $this->_crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $this->_crmcusttravelplanAir = new Travel_Model_CRM_CustomerTravelPlanAir();
        $this->objFlight = new Travel_Model_TblFlight();
        $this->paymentMdl = new Payment_Model_Payment();
        $this->_crmremarkObj = new Travel_Model_CRM_Remark();
        #### Script to send email ####

        $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'];

        #### Script to send email End ####
        $this->BITLYLOGIN = 'gpurwar';
        $this->BITLYAPIKEY = 'R_c1c94b5c789249d5a59d585bc0e7ef80';

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

    public function indexAction() {
        $objFlight = new Travel_Model_TblFlight();
        $objAirline = new Travel_Model_TblAirline();

        //get All Airline List
        $airlineList = $objAirline->getAirlineList();
        $this->view->airlineList = $airlineList;

        //Get City List
        //$cityList = $objFlight->getInventoryCityList($this->intLoggedinAgencyId);
        //$this->view->cityList = $cityList;
        //Get Supplier List
        $supplierList = $objFlight->getSuppliersList($cityId = '', $this->intLoggedinUserId);
        $this->view->supplierList = $supplierList;

        //Get Flight Total Seat
        $totalResult = $objFlight->getFlightTotalSeat($this->intLoggedinAgencyId);
        $this->view->totalResult = $totalResult;

        //Get Flight Total Cost
        $totalCostResult = $objFlight->getFlightTotalCost($this->intLoggedinAgencyId);
        $this->view->totalCostResult = $totalCostResult;

        //Get Flight Total Sold Cost
        $totalSoldCostResult = $objFlight->getFlightTotalSoldCost($this->intLoggedinAgencyId);

        //Get Total Standard Cost
        $totalStandardCostResult = $objFlight->getFlightStandardTotalCost($this->intLoggedinAgencyId);

        //Get Total Standard Sold Cost
        $totalStandardSoldCostResult = $objFlight->getFlightStandardTotalSoldCost($this->intLoggedinAgencyId);

        //get Final Total seat cost
        $final_total_cost = $totalCostResult['total_cost'] + $totalStandardCostResult;
        $this->view->final_total_cost = $final_total_cost;

        //Get Final Total Sold Cost
        $final_total_sold_cost = $totalSoldCostResult['total_sold_cost'] + $totalStandardSoldCostResult;
        $this->view->final_total_sold_cost = $final_total_sold_cost;

        //Get Final Unsold Total Cost
        $final_total_unsold_cost = $final_total_cost - $final_total_sold_cost;
        $this->view->final_total_unsold_cost = $final_total_unsold_cost;

        //Start Search Code
        $searchArr = array();
        $getData = array();
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();

            if (!empty($getData)) {
                if (@$getData['fromCityName'] != "") {
                    $fromCityName = @$getData['fromCityName'];
                } else {
                    $fromCityName = "";
                }
                if (@$getData['DestinationId'] != 0) {
                    $DestinationId = @$getData['DestinationId'];
                } else {
                    $DestinationId = "";
                }
                if (@$getData['toDestinationId'] != 0) {
                    $toDestinationId = @$getData['toDestinationId'];
                } else {
                    $toDestinationId = "";
                }
                if (@$getData['toCityName'] != "") {
                    $toCityName = @$getData['toCityName'];
                } else {
                    $toCityName = "";
                }
                if (@$getData['date'] != 0) {
                    $date = $getData['date'];
                } else {
                    $date = "";
                }
                if (@$getData['supplierId'] != 0) {
                    $supplierId = $getData['supplierId'];
                } else {
                    $supplierId = "";
                }
                if (@$getData['airlineId'] != 0) {
                    $airlineId = $getData['airlineId'];
                } else {
                    $airlineId = "";
                }
                $searchArr = array(
                    'isWay' => @$getData['isWay'],
                    'fromCityName' => @$getData['fromCityName'],
                    'toCityName' => @$getData['toCityName'],
                    'DestinationId' => $DestinationId,
                    'toDestinationId' => $toDestinationId,
                    'date' => $date,
                    'supplierId' => $supplierId,
                    'airlineId' => $airlineId
                );
            }
        } else {
            $isWay = $this->_getParam('isWay');
            $fromCityName = $this->_getParam('fromCityName');
            $toCityName = $this->_getParam('toCityName');
            $DestinationId = $this->_getParam('DestinationId');
            $toDestinationId = $this->_getParam('toDestinationId');
            $date = $this->_getParam('date');
            $supplierId = $this->_getParam('supplierId');
            $airlineId = $this->_getParam('airlineId');

            if ($DestinationId != 0) {
                $DestinationId = $DestinationId;
            } else {
                $DestinationId = "";
            }
            if ($toDestinationId != 0) {
                $toDestinationId = $toDestinationId;
            } else {
                $toDestinationId = "";
            }
            if ($date != 0) {
                $date = $date;
            } else {
                $date = "";
            }
            if ($supplierId != 0) {
                $supplierId = $supplierId;
            } else {
                $supplierId = "";
            }
            if ($airlineId != 0) {
                $airlineId = $airlineId;
            } else {
                $airlineId = "";
            }
            $searchArr = array(
                'isWay' => $isWay,
                'fromCityName' => $fromCityName,
                'toCityName' => $toCityName,
                'DestinationId' => $DestinationId,
                'toDestinationId' => $toDestinationId,
                'date' => $date,
                'supplierId' => $supplierId,
                'airlineId' => $airlineId
            );
        }

        //
        //$objFlight->searchArr = $searchArr;
        $this->view->searchArr = $searchArr;

        $flightList = $objFlight->getAllFlightList($this->intLoggedinAgencyId, $searchArr);
        //echo "<pre>"; print_r($flightList);  die;
        //$this->view->flightList = $flightList;
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory($flightList);
        $paginator->setCurrentPageNumber($this->getRequest()->getParam('page')); // page number
        $perPage = $paginator->setItemCountPerPage(10); // number of items to show per page
        $this->view->paginator = $paginator;
        $this->view->totalrec = $paginator->getTotalItemCount();

        //For display message
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
    }

    public function searchResultAction() {
        $this->view->typeQuick = $typeQuick = $this->getRequest()->getParam('type');
        $this->view->SearchID = $SearchID = $this->getRequest()->getParam('SearchID');
        $this->view->baseUrl = $this->baseUrl;
        if (!$this->_request->isXmlHttpRequest()) {
            $objTempFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objTempFlight->GetFlightTempData($SearchID);
            $APIBookingData = json_decode($FlightTempData['APIBookingData'], true);
            $sessionFlightSearchParams = $APIBookingData['sessionFlightSearchParams'];
            $searchids = isset($APIBookingData['searchids']) ? $APIBookingData['searchids'] : [];
            $route = $sessionFlightSearchParams['route'];
            // echo "<pre>";
            // print_r($APIBookingData);
            // die;
            $intSourceCityId = ($sessionFlightSearchParams['sourceCityId']);
            $intDestinationCityId = ($sessionFlightSearchParams['destinationCityId']);
            if (isset($sessionFlightSearchParams['customerID']) && !empty($sessionFlightSearchParams['customerID'])) {
                $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = isset($sessionFlightSearchParams['customerID']) ? $this->_crmcustomerObj->GetAgencyCustomerById(trim($sessionFlightSearchParams['customerID'])) : '';
                $sessionFlightSearchParams['customername'] = trim($customerDetails['FirstName']) . "&nbsp;" . trim($customerDetails['LastName']);
                $this->view->customerDetails = $customerDetails;
            }

            $intCountryCode = ($route == 3) ? $sessionFlightSearchParams['intCountryCode'][0] : $sessionFlightSearchParams['intCountryCode'];
            $B2BType = (int) $sessionFlightSearchParams['B2BType'];
            $CustomerSysId = $sessionFlightSearchParams['CustomerSysId'];
            // echo '<pre>';print_r($sessionFlightSearchParams); 
            // exit;
            $getMarkupB2B = $this->getMarkupB2B($intCountryCode, $CustomerSysId, $B2BType);
            $getMarkup = $getMarkupB2B;

            /* For Displaying Temprary Result set of flights */
            // echo '<pre>';
            // print_r($getMarkup);
            // exit;
            $arrTempFlightList = [];
            if (!empty($intSourceCityId) && !empty($intDestinationCityId) && $route != 3) {
                $objTempFlight->strCondition = " t1.SourcePlaceSysId = '" . $intSourceCityId . "' AND t1.DestPlaceSysId = '" . $intDestinationCityId . "'";
                $arrTempFlightList = $objTempFlight->getTempFlightSearchResultList();
            }
            $this->view->arrTempFlightList = $arrTempFlightList;
            /* For Displaying Temprary Result set of flights */

            $sessionFlightRecordInfo = new Zend_Session_Namespace('sessionFlightRecordInfo');
            $sessionFlightRecordInfo->params['intTotalRecordCount'] = 0;  // Set Total Records to '0' on page Refresh...
            $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
            $AgencySysId = trim($sessionLogin_user->intLoggedinUserAgencySysId);
            $agencyModel = new Travel_Model_TblAgency();
            $getActiveSenderEmailIdArr = $agencyModel->getActiveSenderEmailID($AgencySysId);
            $this->view->getActiveSenderEmailIdArr = $getActiveSenderEmailIdArr;
            $SenderEmailSysId = isset($_SESSION['AgencyUser']['user']->SenderEmailSysId) ? $_SESSION['AgencyUser']['user']->SenderEmailSysId : 0;
            $this->view->SenderEmailSysId = $SenderEmailSysId;
            $this->view->sessionFlightSearchParams = $sessionFlightSearchParams;
            $this->view->getActiveStaff = $getActiveStaff = $agencyModel->getActiveStaff($AgencySysId);
            $this->view->getAgencyTnCDetails = $getAgencyTnCDetails = $agencyModel->getAgencyTnCDetails($AgencySysId);
            $getleadSource = $this->_crmcustomerObj->getLeadSourceByAgency($AgencySysId);
            $this->view->getleadSource = $getleadSource;
            $this->view->searchids = json_encode($searchids);
            $this->view->IsOwnApi = isset($this->agencyDetails['IsCheckWallet']) ? $this->agencyDetails['IsCheckWallet'] : false;
            $this->view->TaxPercentage = (isset($getMarkup['arrApiServiceTax'][0]['TaxPercentage']) && $this->agencyDetails['TaxLabelId'] != 0) ? (float) $getMarkup['arrApiServiceTax'][0]['TaxPercentage'] : 0;
        }

        if ($this->_request->isXmlHttpRequest()) {
            /* Disable Layout */
            $this->_helper->layout->disableLayout();
        }

        $markupMdl = new Markup_Model_Markup();
        // $this->view->getTaxSettingDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $this->intLoggedinAgencyId,0,0,1);
        $getTaxSettingDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $this->intLoggedinAgencyId, 0, 0, 1);
        //
        if (empty($getTaxSettingDetail)) {
            $this->view->getTaxSettingDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $this->intLoggedinAgencyId, 0, 0, 5);
        } else {
            $this->view->getTaxSettingDetail = $markupMdl->getTaxSettingDetail("TB_Master_Agency_Tax_Settings", $this->intLoggedinAgencyId, 0, 0, 1);
        }
    }

    public function getflightsearchAction() {
        $getData = $this->getRequest()->getParams();
        $getData = json_decode(file_get_contents('php://input'), true);

        $sessionFlightSearchParams = json_decode($getData['sessionFlightSearchParams'], true);
        $interNationalSearch = trim($sessionFlightSearchParams['interNationalSearch']);
        $strFlightRoute = isset($sessionFlightSearchParams['route']) ? trim($sessionFlightSearchParams['route']) : 1;
        $Symbol = $this->agencyDetails['Symbol'];
        $APIBookingData['SearchQueryid'] = $getData['searchid'];
        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        $URL = GTX_API_URL . '/flight/v4/search';
        $apiSearchRequest = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($APIBookingData, $getData, $URL);
        $ResponseStatus = (isset($apiSearchRequest['status']) && $apiSearchRequest['status']) ? true : false;
        $MultiHead = [];
        if (isset($sessionFlightSearchParams['sourceCityText']) && !empty($sessionFlightSearchParams['sourceCityText'])) {
            if ($sessionFlightSearchParams['sourceCityText'] && $strFlightRoute == 3) {
                foreach ($sessionFlightSearchParams['sourceCityText'] as $sk => $source_) {
                    $destination_ = isset($sessionFlightSearchParams['destinationCityText'][$sk]) ? explode(',', $sessionFlightSearchParams['destinationCityText'][$sk]) : '';
                    $source_ = isset($source_) ? explode(',', $source_) : '';
                    $departure_date_ = isset($sessionFlightSearchParams['departure_dates'][$sk]) ? $sessionFlightSearchParams['departure_dates'][$sk] : '';
                    $MultiHead[] = array(
                        'source' => isset($source_[0]) ? $source_[0] : '',
                        'destination' => isset($destination_[0]) ? $destination_[0] : '',
                        'departure_date' => isset($departure_date_) ? $departure_date_ : '',
                    );
                }
            }
        }
        // echo "<pre>";
        // print_r($MultiHead);
        // echo "<pre>";
        // print_r($sessionFlightSearchParams);
        // die;
        $FlightRoute = (isset($apiSearchRequest['route']) && $apiSearchRequest['route']) ? $apiSearchRequest['route'] : 1;
        $interNationalSearch = (isset($apiSearchRequest['interNationalSearch']) && $apiSearchRequest['interNationalSearch']) ? $apiSearchRequest['interNationalSearch'] : 0;
        if ($ResponseStatus) {

            $outbound = (isset($apiSearchRequest['outbound']) && $apiSearchRequest['outbound']) ? $apiSearchRequest['outbound'] : [];
            $inbound = (isset($apiSearchRequest['inbound']) && $apiSearchRequest['inbound']) ? $apiSearchRequest['inbound'] : [];

            $FiltAirlineName = (isset($apiSearchRequest['FiltAirlineName']) && $apiSearchRequest['FiltAirlineName']) ? $apiSearchRequest['FiltAirlineName'] : [];
            $FiltAirlineNameSp = (isset($apiSearchRequest['FiltAirlineNameSp']) && $apiSearchRequest['FiltAirlineNameSp']) ? $apiSearchRequest['FiltAirlineNameSp'] : [];
            $FiltStop = (isset($apiSearchRequest['FiltStop']) && $apiSearchRequest['FiltStop']) ? $apiSearchRequest['FiltStop'] : [];
            $FiltPrice = (isset($apiSearchRequest['FiltPrice']) && $apiSearchRequest['FiltPrice']) ? $apiSearchRequest['FiltPrice'] : [];
            $checkingBaggage = (isset($apiSearchRequest['checkingBaggage']) && $apiSearchRequest['checkingBaggage']) ? $apiSearchRequest['checkingBaggage'] : [];
            $cabinBaggage = (isset($apiSearchRequest['cabinBaggage']) && $apiSearchRequest['cabinBaggage']) ? $apiSearchRequest['cabinBaggage'] : [];
            $data = array('MultiHead' => $MultiHead, 'outbound' => $outbound, 'inbound' => $inbound, 'FlightRoute' => $FlightRoute, 'interNationalSearch' => $interNationalSearch, 'arrAirlineName' => $FiltAirlineName, 'FiltStopCount' => $FiltStop, 'FiltPrice' => $FiltPrice, 'FiltSupplier' => [], 'cabinBaggage' => $cabinBaggage, 'checkingBaggage' => $checkingBaggage, 'FiltAirlineNameSp' => $FiltAirlineNameSp, 'CurrencyTitle' => $Symbol, 'MinriceRange' => 0, 'MaxriceRange' => 0);
            echo json_encode($data);
            exit;
        } else {
            $data = array('MultiHead' => [], 'outbound' => [], 'inbound' => [], 'FlightRoute' => $FlightRoute, 'interNationalSearch' => $interNationalSearch, 'arrAirlineName' => [], 'FiltStopCount' => [], 'FiltPrice' => [], 'FiltSupplier' => [], 'FiltAirlineNameSp' => [], 'cabinBaggage' => [], 'checkingBaggage' => [], 'CurrencyTitle' => $Symbol, 'MinriceRange' => 0, 'MaxriceRange' => 0);
            echo json_encode($data);
            exit;
        }
    }

    public function farerulesAction() {
        $post = json_decode(file_get_contents('php://input'), true);
        if ($post['item']) {
            $ICSourceSysId = $post['item']['ICSourceSysId'];
            $JourneyType = $post['item']['JourneyType'];
            $IsInternational = $post['item']['IsInternational'];
            $searchID = $post['item']['SearchTraceId'];

            $DataAPI = [
                'CurrencyRate' => !empty($post['prices']['CurrencyRate']) ? $post['prices']['CurrencyRate'] : 1,
                'CurrencyTitle' => !empty($post['prices']['Currency']) ? $post['prices']['Currency'] : 'INR',
                'CurrencyId' => !empty($post['prices']['currencySysId']) ? $post['prices']['currencySysId'] : 1,
            ];
            $flowType = (isset($post['flowType']) && !empty($post['flowType'])) ? $post['flowType'] : 'REVIEW';
            if ($ICSourceSysId == 7) {
                $datah = array(
                    'id' => $post['prices']['PriceID'],
                    'flowType' => $flowType,
                );
            } elseif ($ICSourceSysId == 3) {
                $datah = array(
                    'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                    'TokenId' => '',
                    'TraceId' => $post['item']['apiTraceId'],
                    'ResultIndex' => $post['prices']['PriceID']
                );
            } elseif ($ICSourceSysId == 11 || $ICSourceSysId == 13 || $ICSourceSysId == 14 || $ICSourceSysId == 20 || $ICSourceSysId == 30) {
                $datah = array(
                    'Auth_Header' => array(
                        "IP_Address" => $_SERVER['REMOTE_ADDR'],
                        "Request_Id" => $post['item']['SearchTraceId'],
                        "IMEI_Number" => "3434334343111"
                    ),
                    'Fare_Id' => $post['prices']['PriceID'],
                    'Search_Key' => $post['item']['Search_Key'],
                    'Flight_Key' => $post['item']['Flight_Key'],
                );
            }

            $getData = [];
            $DataAPI['farerule'] = $datah;
            $DataAPI['ICSourceSysId'] = $ICSourceSysId;
            $DataAPI['JourneyType'] = $JourneyType;
            $DataAPI['IsInternational'] = $IsInternational;
            $DataAPI['searchID'] = $searchID;
            $DataAPI['B2B'] = [];

            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            if ($this->intLoggedinAgencyId == '1') {
                $URL = GTX_API_URL . '/flight/v3/farerules';
            } else {
                $URL = 'https://gtxapi.hellogtx.com/flight/v3/farerules';
            }

            $apiSearchRequest = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataAPI, $getData, $URL);
            $ResponseStatus = (isset($apiSearchRequest['status']) && $apiSearchRequest['status']) ? true : false;
            // echo "<pre>";
            // print_r($apiSearchRequest);
            // die;
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight-new/');
            $html->assign(array('apiResponse' => $apiSearchRequest, 'prices' => $post['prices'], 'item' => $post['item']));
            $bodyText = $html->render('getflightfarerules.phtml');
            $response = array('success' => true, 'message' => 'success', 'html' => $bodyText);
            echo json_encode($response);
            exit;
        }
    }

    public function bookNowAction() {
        $post = json_decode(file_get_contents('php://input'), true);

        $FareArr = isset($post['FareArr']) ? $post['FareArr'] : [];
        $Outbound = isset($post['Outbound']) ? $post['Outbound'] : [];
        $Inbound = isset($post['Inbound']) ? $post['Inbound'] : [];
        $FareOption = isset($post['FareOption']) ? $post['FareOption'] : [];
        // echo "<pre>";
        // print_r(($post));
        // die;
        $SearchTraceId = isset($Outbound['SearchTraceId']) ? $Outbound['SearchTraceId'] : ($Outbound[0]['SearchTraceId'] ?? 0);
        $ProposaltraceID = isset($post['ProposaltraceID']) ? $post['ProposaltraceID'] : '';
        if (isset($post['sessionFlightSearchParams']) && !empty($post['sessionFlightSearchParams'])) {
            $sessionParams = json_decode($post['sessionFlightSearchParams'], true);
        }
        $ICSourceSysId = ($Outbound['ICSourceSysId']) ? $Outbound['ICSourceSysId'] : ($Outbound[0]['ICSourceSysId'] ?? 0);

        $route = ($sessionParams['route']);

        $SearchTrace = ($sessionParams['SearchTraceId']);
        $interNationalSearch = !empty($sessionParams['interNationalSearch']) ? $sessionParams['interNationalSearch'] : 0;

        if (!empty($Inbound) && $route == 2 && $interNationalSearch == 0) {
            $Outbound['FairRules'] = $Outbound['FairRules'][0];
            $Outbound['TripType'] = 1;
            $FlightBookingData[0] = $Outbound;
            $Inbound['FairRules'] = $Inbound['FairRules'][0];
            $Inbound['TripType'] = 2;
            $FlightBookingData[1] = $Inbound;
        } else {
            $Outbound['FairRules'] = $FareOption;
            $FlightBookingData[0] = $Outbound;
        }
        
        if ($route == 3 && $interNationalSearch == 0 && $ICSourceSysId == 7) {
            $FlightBookingData = [];
            $apiTraceId = [];
            if ($Outbound) {
                foreach ($Outbound as $key__ => $item) {
                    $FairRules = isset($FareArr[$key__]) ? $FareArr[$key__] : [];
                    if ($FairRules) {
                        $apiTraceId[$key__] = $FairRules['PriceID'];
                        $FlightBookingData[$key__] = $item;
                        $FlightBookingData[$key__]['FairRules'] = $FairRules;
                    }
                }
            }
            $apiTraceId = implode(',', $apiTraceId);
        }
        // echo "<pre>";
        // print_r(($FlightBookingData));
        // die;
        try {
            $objFlight = new Travel_Model_TblFlight();
            $TPSysId = 0;
            $arrData['FlightBookingData'] = $FlightBookingData;
            $arrData['apiTraceId'] = $SearchTrace;
            $arrData['SearchTraceId'] = $SearchTraceId;
            $arrData['AirInvenSysIdArr'] = [];
            $arrData['sessionFlightSearchParams'] = $sessionParams;

            $tempData = array(
                'TraceId' => $SearchTraceId,
                'TPSysId' => $TPSysId,
                'APIBookingData' => json_encode($arrData),
            );

            $objFlight->deleteFlightTempData($SearchTraceId);
            $objFlight->insertFlightTempData($tempData);
            //$strUrlData = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->dataEncode($arrData);
            if ($FlightBookingData) {
                if (!empty($ProposaltraceID)) {
                    $response = array('success' => true, 'message' => 'Plase wait...', 'url' => $this->baseUrl . '/flight-proposal/view-flight-proposal-travellers/data/' . $SearchTraceId . '/id/' . $ProposaltraceID);
                    echo json_encode($response);
                    exit;
                } else {
                    $response = array('success' => true, 'message' => 'Plase wait...', 'url' => $this->baseUrl . '/flight-new/travellers/data/' . $SearchTraceId);
                    echo json_encode($response);
                    exit;
                }
            } else {
                $response = array('success' => false, 'message' => 'Oops something went wrong', 'url' => '');
                echo json_encode($response);
                exit;
            }
        } catch (Exception $e) {
            //echo $e->getMessage();
            $response = array('success' => false, 'message' => 'Traceid expired. please search again', 'url' => '');
            echo json_encode($response);
            exit;
        }
    }

    public function travellersAction() {
        $objFlight = new Travel_Model_TblFlight();
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $strUrlData = $this->view->strUrlData = $this->getRequest()->getParam('data');
        if ($this->getRequest()->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);
            $strUrlData = $post['SearchID'];
        }

        $FlightTempData = $objFlight->GetFlightTempData($strUrlData);
        $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);

        $GeoCountry = $this->view->GeoCountry = $objFlight->GetGeoCountry();
        $FlightBookingData = $arrUrlData['FlightBookingData'];
        $ICSourceSysId = isset($FlightBookingData[0]['ICSourceSysId']) ? $FlightBookingData[0]['ICSourceSysId'] : 0;
        $AirInvenSysIdArr = $arrUrlData['AirInvenSysIdArr'];
        $SearchTraceId = $arrUrlData['SearchTraceId'];
        $requestAPIOld = isset($arrUrlData['requestAPI']) ? $arrUrlData['requestAPI'] : '';
        $customerSaved = isset($arrUrlData['customer']) ? $arrUrlData['customer'] : [];
        $sessionFlightSearchParams = $arrUrlData['sessionFlightSearchParams'];
        $this->view->AgencySysId = ($sessionFlightSearchParams['AgencySysId']);
        $this->view->apiTraceId = ($SearchTraceId);
        $this->view->ICSourceSysId = ($ICSourceSysId);
        $this->view->FlightBookingData = ($FlightBookingData);
        $intCountryCode = ($sessionFlightSearchParams['intCountryCode']);
        $adultCount = ($sessionFlightSearchParams['adults']);
        $childCount = ($sessionFlightSearchParams['child']);
        $infantCount = ($sessionFlightSearchParams['infant']);
        $JourneyType = ($sessionFlightSearchParams['route']);
        $interNationalSearch = !empty($sessionFlightSearchParams['interNationalSearch']) ? $sessionFlightSearchParams['interNationalSearch'] : 0;
        $intMemberCount = ($adultCount + $childCount + $infantCount);
        $flight_class = trim($sessionFlightSearchParams['flight_class']);
        $arrFlightClass = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getFlightClasses();
        $cabinClass = isset($arrFlightClass[$flight_class]) ? $arrFlightClass[$flight_class] : 'Economy';

        // $intCustomerSysId = isset($sessionFlightSearchParams['CustomerSysId']) ? $sessionFlightSearchParams['CustomerSysId'] : 0;
        // $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($intCustomerSysId);

        $objMarkup = new Markup_Model_Markup();
        if (!empty(($intCountryCode)) && ($intCountryCode) != "IN") {
            $intAirType = 2;
        } else {
            $intAirType = 1;
        }

        $arrAgencyUserDetail = $objMarkup->getAgencyUserDetail(array("AgencySysId" => $this->intLoggedinAgencyId, "ItemSourceType" => (int) $intAirType, "PlanType" => 0));
        $this->view->arrAgencyUserDetail = $arrAgencyUserDetail;
        $this->view->sessionFlightSearchParams = $sessionFlightSearchParams;
        $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
        $customerDetails = isset($sessionFlightSearchParams['customerID']) ? $this->_crmcustomerObj->GetAgencyCustomerById(trim($sessionFlightSearchParams['customerID'])) : '';
        $this->view->arrTrevllerDetails = $customerDetails;

        $departureDates = $sessionFlightSearchParams['departure_dates'];
        if ($JourneyType == '3') {
            $departureDates = $sessionFlightSearchParams['departure_dates'][0];
        }
        $arrDepartureDates = explode("/", $departureDates);
        $this->view->departureDates = $departureDates = $arrDepartureDates[2] . "/" . $arrDepartureDates[1] . "/" . ($arrDepartureDates[0] - 1);
        $this->view->departureMonthInfant = $departureMonthInfant = $arrDepartureDates[1];
        $this->view->departureDayInfant = $departureDayInfant = ($arrDepartureDates[0] + 1);

        $this->view->departureMonthChild = $departureMonthChild = $arrDepartureDates[1];
        $this->view->departureDayChild = $departureDayChild = ($arrDepartureDates[0]);

        $this->view->intFlightRoute = $JourneyType;
        $this->view->intAdultsCount = $adultCount;
        $this->view->intChildrenCount = $childCount;
        $this->view->intInfantCount = $infantCount;
        $this->view->totalPaxCount = $adultCount + $childCount + $infantCount;
        $B2BType = isset($sessionFlightSearchParams['B2BType']) ? ($sessionFlightSearchParams['B2BType']) : 0;
        $B2BSearch = [];
        if ($B2BType == 1) {
            $CreatedByUserSysId = isset($customerDetails['CreatedByUserSysId']) ? $customerDetails['CreatedByUserSysId'] : 0;
            $BusinessType = isset($customerDetails['BusinessType']) ? $customerDetails['BusinessType'] : 0;
            $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
            $IsB2BCustomer = isset($customerDetails['IsB2BAgent']) ? $customerDetails['IsB2BAgent'] : 0;
            $B2bAgencyDetailById = $this->_crmcustomerObj->GetAgencyDetailById($AgencySysId__);
            $AgentUserDetail = $this->_crmcustomerObj->getAgentDetailById(($BusinessType == 1) ? $CreatedByUserSysId : $AgencySysId__);
            $this->view->AgentUserDetail = $AgentUserDetail;
            $this->view->BusinessType = $BusinessType;
            $UserSysId = isset($AgentUserDetail[0]['UserSysId']) ? $AgentUserDetail[0]['UserSysId'] : 0;
            $B2BAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
            $AgencyMarketPlaceSysId = $B2bAgencyDetailById['AgencyMarketPlaceSysId'];
            $B2BSearch = array(
                'B2BAgencySysIdKey' => $B2BAgencySysIdKey,
                'B2CAgencySysIdKey' => $this->agencyDetails['SecurityKey'],
                'MasterAgencySysId' => $this->intLoggedinAgencyId,
                'AgencyMarketPlaceSysId' => $AgencyMarketPlaceSysId
            );
            $searchApiFlightsNew['B2B'] = $B2BSearch;
        }
        // echo "<pre>AgentUserDetail";
        // print_r(($AgentUserDetail));
        // echo "<pre>customerDetails";
        // print_r(($customerDetails));
        // die;
        if ($this->getRequest()->isXmlHttpRequest()) {
            $ARR_SALUTIONTBO = array("1" => "Mr", "2" => "Mrs", "3" => "Ms", "4" => "Mstr", "5" => "Miss");
            // echo '<pre>';
            // print_r($searchApiFlightsNew);
            // echo '<pre>';
            // print_r($FlightBookingData);
            // die;
            $priceId = [];
            $ItineraryInfo = [];
            $AirRepriceRequests = [];
            $AirSSRRequestDetails = [];
            $intPublishedFareCheck = 0;
            if ($FlightBookingData) {
                foreach ($FlightBookingData as $key => $value) {
                    if (isset($value['FairRules']['PriceID']) && !empty($value['FairRules']['PriceID'])) {
                        $priceId[] = $value['FairRules']['PriceID'];
                    }

                    $intPublishedFareCheck += $value['FairRules']['intPublishedFare'];
                    $arrData[$key]['TraceId'] = $value['FairRules']['PriceID'];
                    $arrData[$key]['ResultIndex'] = $value['FairRules']['ApiResultIndex'];
                    $FlightDetails = [];
                    if ($value['Segments']) {
                        foreach ($value['Segments'] as $i => $vl) {
                            $FlightDetails[] = array(
                                'FlightID' => $vl['segmentid'],
                                'FlightNumber' => str_replace('-', ' ', $vl['SegFlightNumber']),
                                'Origin' => $vl['originAirportCode'],
                                'Destination' => $vl['destinationAirportCode'],
                                'DepartureDateTime' => date('d M Y H:i', strtotime($vl['originDepTime'])),
                                'ArrivalDateTime' => date('d M Y H:i', strtotime($vl['destinationArrTime'])),
                            );
                        }
                    }
                    $BaseFare = $value['FairRules']['APIBaseFare'];
                    $GrossAmount = $value['FairRules']['GrossAmount'];
                    $ItineraryInfo[$key]['FlightDetails'] = $FlightDetails;
                    $ItineraryInfo[$key]['BaseAmount'] = $BaseFare;
                    $ItineraryInfo[$key]['GrossAmount'] = $GrossAmount;
                    // Etrav Data
                    $AirSSRRequestDetails[$key]['Flight_Key'] = isset($value['Flight_Key']) ? $value['Flight_Key'] : '';
                    $AirRepriceRequests[$key]['Flight_Key'] = isset($value['Flight_Key']) ? $value['Flight_Key'] : '';
                    $AirRepriceRequests[$key]['Fare_Id'] = isset($value['FairRules']['PriceID']) ? $value['FairRules']['PriceID'] : '';
                }
            }
            // echo '<pre>';print_r($priceId);
            // echo '<pre>';print_r($FlightBookingData);
            // die;
            $tripSeatMap = [];
            $requestAPIArray = [];
            $ResponseStatus = 0;
            $farerulerequestArray = [];
            if ($ICSourceSysId == 7) {
                $requestAPI = array(
                    'priceIds' => $priceId
                );
                $requestAPIArray = $requestAPI;
                $DataS = array(
                    'apidata' => !empty($requestAPIOld) ? $requestAPIOld : $requestAPI,
                    'memberCount' => $intMemberCount,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $SearchTraceId,
                    'ICSourceSysId' => $ICSourceSysId,
                    'cabinClass' => $cabinClass,
                    'AdultCount' => $adultCount,
                    'ChildCount' => $childCount,
                    'InfantCount' => $infantCount,
                    'AgentMarkUp' => 0,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
                );
                $DataS['B2B'] = $B2BSearch;
                // echo '<pre>';(print_r($requestAPI));
                // die('ddd');
                $url = GTX_API_URL . '/flight/v3/farequote';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                
            } elseif ($ICSourceSysId == 3) {
                $FlightData = [];
                $FARERULE = [];
                $FareChange = false;
                $intPublishedFare = 0;
                $intPublishedFareNew = 0;
                if ($FlightBookingData) {
                    foreach ($FlightBookingData as $key => $vl) {

                        $intPublishedFare += $vl['FairRules']['PublishedFareAgent'];
                        $requestAPI = array(
                            'TraceId' => $vl['apiTraceId'],
                            'ResultIndex' => $vl['FairRules']['PriceID'],
                        );

                        $requestAPIArray[$key] = $requestAPI;
                        $DataS = array(
                            'apidata' => !empty($requestAPIOld[$key]) ? $requestAPIOld[$key] : $requestAPI,
                            'memberCount' => $intMemberCount,
                            'JourneyType' => $JourneyType,
                            'interNationalSearch' => $interNationalSearch,
                            'searchID' => $SearchTraceId,
                            'ICSourceSysId' => $ICSourceSysId,
                            'cabinClass' => $cabinClass,
                            'AdultCount' => $adultCount,
                            'ChildCount' => $childCount,
                            'InfantCount' => $infantCount,
                            'AgentMarkUp' => 0,
                            'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
                        );
                        $DataS['B2B'] = $B2BSearch;
                        // echo '<pre>';
                        // print_r($DataS);
                        // die;
                        $url = GTX_API_URL . '/flight/v3/farequote';
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $apiResponseTBO = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);

                        $ResponseStatus = isset($apiResponseTBO['status']) ? $apiResponseTBO['status'] : false;
                        $ErrorMessage = isset($apiResponseTBO['message']) ? $apiResponseTBO['message'] : '';

                        $FlightDataTBO = isset($apiResponseTBO['results']) ? $apiResponseTBO['results'] : [];

                        $tripSeatMap[] = isset($apiResponseTBO['tripSeatMap']) ? $apiResponseTBO['tripSeatMap'] : [];
                        $FareChange = isset($apiResponseTBO['FareChange']) ? $apiResponseTBO['FareChange'] : 0;
                        $FARERULE[] = isset($apiResponseTBO['FARERULE']) ? $apiResponseTBO['FARERULE'] : [];
                        if ($FlightDataTBO) {
                            foreach ($FlightDataTBO as $kddd => $value) {
                                $intPublishedFareNew += $value['FairRules']['PublishedFareAgent'];
                                $FlightData[] = $value;
                            }
                        }
                    }
                }

                // if (ceil($intPublishedFare) != ceil($intPublishedFareNew)) {
                //     $FareChange = true;
                // }

                $apiResponse = ["status" => $ResponseStatus, "message" => $ErrorMessage, 'results' => $FlightData, 'FareChange' => $FareChange, 'FARERULE' => $FARERULE, 'tripSeatMap' => $tripSeatMap];
            } elseif ($ICSourceSysId == 8) {
                $apiResponse = ["status" => 1, "message" => 'Success', 'results' => $FlightBookingData, 'FareChange' => false, 'FARERULE' => [], 'tripSeatMap' => []];
            } elseif ($ICSourceSysId == 11 || $ICSourceSysId == 13 || $ICSourceSysId == 14 || $ICSourceSysId == 20 || $ICSourceSysId == 30) {
                $Contacts = !empty($this->agencyDetails['PrimaryContactNo']) ? $this->agencyDetails['PrimaryContactNo'] : '';
                $requestAPIArray = $FlightBookingData;
                $DataS = array(
                    'apidata' => [],
                    'requestSSR' => [],
                    'BookingData' => !empty($requestAPIOld) ? $requestAPIOld : $FlightBookingData,
                    'memberCount' => $intMemberCount,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $SearchTraceId,
                    'ICSourceSysId' => $ICSourceSysId,
                    'cabinClass' => $cabinClass,
                    'AdultCount' => $adultCount,
                    'ChildCount' => $childCount,
                    'InfantCount' => $infantCount,
                    'AgentMarkUp' => 0,
                    'Contacts' => $Contacts,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
                );
                $DataS['B2B'] = $B2BSearch;

                $url = GTX_API_URL . '/flight/v3/farequote';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);

                // echo '<pre>';
                // print_r($apiResponse);
                // die('ddd');
            }
            // $apiResponse = json_decode('', 1);
            $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : false;
            $ErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';

            if ($ResponseStatus == 1) {
                $FlightData = isset($apiResponse['results']) ? $apiResponse['results'] : '';
                $FareChange = isset($apiResponse['FareChange']) ? (bool) $apiResponse['FareChange'] : '';
                $FARERULE = isset($apiResponse['FARERULE']) ? $apiResponse['FARERULE'] : '';
                $tripSeatMap = isset($apiResponse['tripSeatMap']) ? $apiResponse['tripSeatMap'] : [];

                // if ($adultCount > 0) {
                //     $intPaxCount = 1;
                //     for ($i = 1; $i <= $adultCount; $i++) {
                //         $memberDetails[$i]['index'] = $i;
                //         $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]['FFAirlineCode'] = (isset($FlightData[0]['AirlineCode']) && !empty($FlightData[0]['AirlineCode'])) ? $FlightData[0]['AirlineCode'] : '';
                //         $memberDetails[$i]['FFNumber'] = '';
                //         $memberDetails[$i]['passno'] = '';
                //         $memberDetails[$i]['passisse'] = '';
                //         $memberDetails[$i]['passexp'] = '';
                //         $memberDetails[$i]['city'] = '';
                //         $memberDetails[$i]['address'] = '';
                //         $memberDetails[$i]['passnational'] = 'IN'; //$ISOcountryCode; 
                //         $memberDetails[$i]['isdobr'] = (isset($FlightData[0]['isDobAdult']) && !empty($FlightData[0]['isDobAdult'])) ? $FlightData[0]['isDobAdult'] : $FlightData[0]['IsPassDateOfBirth'];
                //         $memberDetails[$i]['IsPassM'] = isset($FlightData[0]['IsPassMandatory']) ? $FlightData[0]['IsPassMandatory'] : false;
                //         $memberDetails[$i]['IsDocIdM'] = isset($FlightData[0]['isDocIdAllowedMandatory']) ? $FlightData[0]['isDocIdAllowedMandatory'] : false;
                //         $memberDetails[$i]['addonns'] = true;
                //         $memberDetails[$i]['selectedBad'] = 'NA@NA@@0';
                //         $memberDetails[$i]['selectedMeal'] = 'NA@NA@@0';
                //         $memberDetails[$i]['docid'] = '';
                //         $memberDetails[$i]['checked'] = ($i == 1) ? true : false;
                //         $memberDetails[$i]['ICSourceSysId'] = $ICSourceSysId;
                //         $intPaxCount++;
                //     }
                // }
                if ($adultCount > 0) {
                    $intPaxCount = 1;
                    for ($i = 1; $i <= $adultCount; $i++) {
                        $SavedData = (isset($customerSaved[$i - 1]) && !empty($customerSaved[$i - 1])) ? $customerSaved[$i - 1] : [];

                        $memberDetails[$i]['index'] = $i;
                        $memberDetails[$i]['PaxCount'] = $intPaxCount;
                        $memberDetails[$i]['PaxType'] = 1;
                        $memberDetails[$i]['pax'] = 'ADULT';
                        $memberDetails[$i]['AgeR'] = '12 yrs+';
                        $memberDetails[$i]['cid'] = 0;
                        $memberDetails[$i]['fname'] = (isset($SavedData['firstname']) && !empty($SavedData['firstname'])) ? $SavedData['firstname'] : '';
                        $memberDetails[$i]['lname'] = (isset($SavedData['lastname']) && !empty($SavedData['lastname'])) ? $SavedData['lastname'] : '';
                        $memberDetails[$i]['name'] = '';
                        $memberDetails[$i]['title'] = (isset($SavedData['salution']) && !empty($SavedData['salution'])) ? $ARR_SALUTIONTBO[$SavedData['salution']] : '';
                        $memberDetails[$i]['dob'] = (isset($SavedData['dateofbirth']) && !empty($SavedData['dateofbirth'])) ? date('d/m/Y', strtotime($SavedData['dateofbirth'])) : '';
                        $memberDetails[$i]['FFAirlineCode'] = (isset($FlightData[0]['AirlineCode']) && !empty($FlightData[0]['AirlineCode'])) ? $FlightData[0]['AirlineCode'] : '';
                        $memberDetails[$i]['FFNumber'] = '';
                        $memberDetails[$i]['passno'] = (isset($SavedData['passportno']) && !empty($SavedData['passportno'])) ? $SavedData['passportno'] : '';
                        $memberDetails[$i]['passisse'] = (isset($SavedData['passporIssue']) && !empty($SavedData['passporIssue'])) ? date('d/m/Y', strtotime($SavedData['passporIssue'])) : '';
                        $memberDetails[$i]['passexp'] = (isset($SavedData['passportnoexpiry']) && !empty($SavedData['passportnoexpiry'])) ? date('d/m/Y', strtotime($SavedData['passportnoexpiry'])) : '';
                        $memberDetails[$i]['city'] = (isset($SavedData['city']) && !empty($SavedData['city'])) ? $SavedData['city'] : '';
                        $memberDetails[$i]['address'] = (isset($SavedData['address']) && !empty($SavedData['address'])) ? $SavedData['address'] : '';
                        $memberDetails[$i]['city_id'] = (isset($SavedData['city_id']) && !empty($SavedData['city_id'])) ? $SavedData['city_id'] : '';
                        $memberDetails[$i]['country_id'] = (isset($SavedData['country_id']) && !empty($SavedData['country_id'])) ? $SavedData['country_id'] : '';
                        $memberDetails[$i]['passnational'] = (isset($SavedData['PassportNationality']) && !empty($SavedData['PassportNationality'])) ? $SavedData['PassportNationality'] : 'IN';
                        $memberDetails[$i]['isdobr'] = (isset($FlightData[0]['isDobAdult']) && !empty($FlightData[0]['isDobAdult'])) ? $FlightData[0]['isDobAdult'] : $FlightData[0]['IsPassDateOfBirth'];
                        $memberDetails[$i]['IsPassM'] = isset($FlightData[0]['IsPassMandatory']) ? $FlightData[0]['IsPassMandatory'] : false;
                        $memberDetails[$i]['IsDocIdM'] = isset($FlightData[0]['isDocIdAllowedMandatory']) ? $FlightData[0]['isDocIdAllowedMandatory'] : false;
                        $memberDetails[$i]['addonns'] = true;
                        $memberDetails[$i]['selectedBad'] = 'NA@NA@@0';
                        $memberDetails[$i]['selectedMeal'] = 'NA@NA@@0';
                        $memberDetails[$i]['docid'] = (isset($SavedData['docid']) && !empty($SavedData['docid'])) ? $SavedData['docid'] : '';
                        ;
                        $memberDetails[$i]['checked'] = ($i == 1) ? true : false;
                        $memberDetails[$i]['ICSourceSysId'] = $ICSourceSysId;
                        $intPaxCount++;
                    }
                }
                if ($childCount > 0) {
                    $intPaxCount = 1;
                    for ($kk = $i; $kk <= ($childCount + $adultCount); $kk++) {
                        $SavedData = (isset($customerSaved[$kk - 1]) && !empty($customerSaved[$kk - 1])) ? $customerSaved[$kk - 1] : [];

                        $memberDetails[$kk]['index'] = $kk;
                        $memberDetails[$kk]['PaxCount'] = $intPaxCount;
                        $memberDetails[$kk]['PaxType'] = 2;
                        $memberDetails[$kk]['pax'] = 'CHILD';
                        $memberDetails[$kk]['AgeR'] = '2-12 Yrs';
                        $memberDetails[$kk]['cid'] = 0;
                        $memberDetails[$kk]['fname'] = (isset($SavedData['firstname']) && !empty($SavedData['firstname'])) ? $SavedData['firstname'] : '';
                        $memberDetails[$kk]['lname'] = (isset($SavedData['lastname']) && !empty($SavedData['lastname'])) ? $SavedData['lastname'] : '';
                        $memberDetails[$kk]['name'] = '';
                        $memberDetails[$kk]['title'] = (isset($SavedData['salution']) && !empty($SavedData['salution'])) ? $ARR_SALUTIONTBO[$SavedData['salution']] : '';
                        $memberDetails[$kk]['dob'] = (isset($SavedData['dateofbirth']) && !empty($SavedData['dateofbirth'])) ? date('d/m/Y', strtotime($SavedData['dateofbirth'])) : '';
                        $memberDetails[$kk]['FFAirlineCode'] = (isset($FlightData[0]['AirlineCode']) && !empty($FlightData[0]['AirlineCode'])) ? $FlightData[0]['AirlineCode'] : '';
                        $memberDetails[$kk]['FFNumber'] = '';
                        $memberDetails[$kk]['passno'] = (isset($SavedData['passportno']) && !empty($SavedData['passportno'])) ? $SavedData['passportno'] : '';
                        $memberDetails[$kk]['passisse'] = (isset($SavedData['passporIssue']) && !empty($SavedData['passporIssue'])) ? date('d/m/Y', strtotime($SavedData['passporIssue'])) : '';
                        $memberDetails[$kk]['passexp'] = (isset($SavedData['passportnoexpiry']) && !empty($SavedData['passportnoexpiry'])) ? date('d/m/Y', strtotime($SavedData['passportnoexpiry'])) : '';
                        $memberDetails[$kk]['city'] = '';
                        $memberDetails[$kk]['address'] = '';
                        $memberDetails[$kk]['passnational'] = (isset($SavedData['PassportNationality']) && !empty($SavedData['PassportNationality'])) ? $SavedData['PassportNationality'] : 'IN';
                        $memberDetails[$kk]['isdobr'] = (isset($FlightData[0]['isDobChild']) && !empty($FlightData[0]['isDobChild'])) ? $FlightData[0]['isDobChild'] : $FlightData[0]['IsPassDateOfBirth'];
                        $memberDetails[$kk]['IsPassM'] = isset($FlightData[0]['IsPassMandatory']) ? $FlightData[0]['IsPassMandatory'] : false;
                        $memberDetails[$kk]['addonns'] = true;
                        $memberDetails[$kk]['IsDocIdM'] = false;
                        $memberDetails[$kk]['selectedBad'] = 'NA@NA@@0';
                        $memberDetails[$kk]['selectedMeal'] = 'NA@NA@@0';
                        $memberDetails[$kk]['checked'] = false;
                        $memberDetails[$kk]['ICSourceSysId'] = $ICSourceSysId;
                        $intPaxCount++;
                    }
                }
                if ($infantCount > 0) {
                    $intPaxCount = 1;
                    if (isset($kk)) {
                        $kk = $kk;
                    } else {
                        $kk = $i;
                    }
                    for ($kkk = $kk; $kkk <= ($adultCount + $childCount + $infantCount); $kkk++) {
                        $SavedData = (isset($customerSaved[$kkk - 1]) && !empty($customerSaved[$kkk - 1])) ? $customerSaved[$kkk - 1] : [];

                        $memberDetails[$kkk]['index'] = $kkk;
                        $memberDetails[$kkk]['PaxCount'] = $intPaxCount;
                        $memberDetails[$kkk]['PaxType'] = 3;
                        $memberDetails[$kkk]['pax'] = 'INFANT';
                        $memberDetails[$kkk]['AgeR'] = '< 2 Yrs';
                        $memberDetails[$kkk]['cid'] = 0;
                        $memberDetails[$kkk]['fname'] = (isset($SavedData['firstname']) && !empty($SavedData['firstname'])) ? $SavedData['firstname'] : '';
                        $memberDetails[$kkk]['lname'] = (isset($SavedData['lastname']) && !empty($SavedData['lastname'])) ? $SavedData['lastname'] : '';
                        $memberDetails[$kkk]['title'] = (isset($SavedData['salution']) && !empty($SavedData['salution'])) ? $ARR_SALUTIONTBO[$SavedData['salution']] : '';
                        $memberDetails[$kkk]['dob'] = (isset($SavedData['dateofbirth']) && !empty($SavedData['dateofbirth'])) ? date('d/m/Y', strtotime($SavedData['dateofbirth'])) : '';
                        $memberDetails[$kkk]['FFAirlineCode'] = '';
                        $memberDetails[$kkk]['FFNumber'] = '';
                        $memberDetails[$kkk]['passno'] = (isset($SavedData['passportno']) && !empty($SavedData['passportno'])) ? $SavedData['passportno'] : '';
                        $memberDetails[$kkk]['passisse'] = (isset($SavedData['passporIssue']) && !empty($SavedData['passporIssue'])) ? date('d/m/Y', strtotime($SavedData['passporIssue'])) : '';
                        $memberDetails[$kkk]['passexp'] = (isset($SavedData['passportnoexpiry']) && !empty($SavedData['passportnoexpiry'])) ? date('d/m/Y', strtotime($SavedData['passportnoexpiry'])) : '';
                        $memberDetails[$kkk]['address'] = '';
                        $memberDetails[$kkk]['city'] = '';
                        $memberDetails[$kkk]['passnational'] = (isset($SavedData['PassportNationality']) && !empty($SavedData['PassportNationality'])) ? $SavedData['PassportNationality'] : 'IN';
                        $memberDetails[$kkk]['isdobr'] = (isset($FlightData[0]['isDobInfant']) && !empty($FlightData[0]['isDobInfant'])) ? $FlightData[0]['isDobInfant'] : $FlightData[0]['IsPassDateOfBirth'];
                        $memberDetails[$kkk]['IsPassM'] = isset($FlightData[0]['IsPassMandatory']) ? $FlightData[0]['IsPassMandatory'] : false;
                        $memberDetails[$kkk]['addonns'] = false;
                        $memberDetails[$kkk]['IsDocIdM'] = false;
                        $memberDetails[$kkk]['selectedBad'] = 'NA@NA@@0';
                        $memberDetails[$kkk]['selectedMeal'] = 'NA@NA@@0';
                        $memberDetails[$kkk]['checked'] = false;
                        $memberDetails[$kkk]['ICSourceSysId'] = $ICSourceSysId;
                        $intPaxCount++;
                    }
                }
                $BaseFare = 0;
                $Taxesfee = 0;
                $CommDiscount = 0;
                $TotalPay = 0;
                $ServiceFee__ = 0;
                $AirlineTax = 0;
                $FuelSurcharge = 0;
                $GSTOnMarkUp_ = 0;
                $FixedMarkUp_ = 0;
                $CommissionEarned_ = 0;
                $TDSEarn_ = 0;
                if ($FlightData) {
                    foreach ($FlightData as $key => $value) {
                        foreach ($value['FairRules']['FareBreakdown'] as $FareBreakdown) {
                            // echo "<pre>";
                            // print_r(($FareBreakdown));
                            // echo "</pre>";
                            $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                            $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                            $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                            $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                            $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                            $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                            $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                            $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                            $AirlineTax += ($Tax);
                            $FuelSurcharge += ($YQ);
                            $GSTOnMarkUp_ += ($GSTOnMarkUp);
                            $FixedMarkUp_ += ($FixedMarkUp);
                            $CommissionEarned_ += ($CommissionEarned);
                            $TDSEarn_ += ($TDSEarn);
                        }
                    }
                }
                $fare = [
                    'Currency' => isset($FlightData[0]['FairRules']['Currency']) ? trim($FlightData[0]['FairRules']['Currency']) : 'INR',
                    'BaseFare' => round($BaseFare, 2),
                    'Taxesfee' => round($Taxesfee, 2),
                    'CommDiscount' => round($CommDiscount, 2),
                    'CommissionEarned' => round($CommissionEarned_, 2),
                    'TDSEarn' => round($TDSEarn_, 2),
                    'TotalPay' => round($TotalPay, 2),
                    'AirlineTax' => round($AirlineTax, 2),
                    'FuelSurcharge' => round($FuelSurcharge, 2),
                    'FixedMarkUp' => round($FixedMarkUp_, 2),
                    'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
                    'MealPrice' => 0,
                    'BagPrice' => 0,
                    'SeatPrice' => 0,
                    'TotalSSR' => 0,
                ];
                $FromUTCTime = date('Y-m-d', strtotime($FlightData[0]['FromUTCTime']));
                $response = array(
                    'success' => true,
                    'message' => $ErrorMessage,
                    'fareData' => $fare,
                    'arrFlightData' => $FlightData,
                    'memberDetails' => array_values($memberDetails),
                    'FareChange' => $FareChange,
                    'TotalPay' => number_format($TotalPay, 2),
                    'CurrencyTitle' => $this->CurrencyTitle,
                    'departureDates' => $FromUTCTime,
                    'departureMonthInfant' => $departureMonthInfant,
                    'departureDayInfant' => $departureDayInfant,
                    'departureMonthChild' => $departureMonthChild,
                    'departureDayChild' => $departureDayChild,
                );
                $arrUrlData['FlightBookingData'] = $FlightData;
                $arrUrlData['tripSeatMap'] = $tripSeatMap;
                $arrUrlData['requestAPI'] = !empty($requestAPIOld) ? $requestAPIOld : $requestAPIArray;
                ;
                $arrUrlData['FARERULE'] = $FARERULE;
                $arrUrlData['fare'] = $fare;
                $tempData = array(
                    'TraceId' => $SearchTraceId,
                    'TPSysId' => 0,
                    'APIBookingData' => json_encode($arrUrlData),
                );

                $objFlight->deleteFlightTempData($SearchTraceId);
                $objFlight->insertFlightTempData($tempData);

                echo json_encode($response);
                exit;
                // echo "<pre>";
                // print_r(($FARERULE));
                // echo "<pre>";
                // print_r(($apiResponse));
                // echo json_encode($apiResponse);
                die;
            } else {

                $response = array('success' => false, 'message' => $ErrorMessage, 'apiResponse' => $apiResponse);
                echo json_encode($response);
                exit;
            }
        }
        // echo "<pre>";
        // print_r(($ICSourceSysId));
    }

    public function reviewAction() {
        $getData = $this->getRequest()->getParams();
        $objFlight = new Travel_Model_TblFlight();
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $strUrlData = $this->view->strUrlData = $this->getRequest()->getParam('data');
        if ($this->getRequest()->isXmlHttpRequest()) {
            $post = json_decode(file_get_contents('php://input'), true);
            $strUrlData = $post['SearchID'];
        }
        $confirm = isset($getData['confirm']) ? $getData['confirm'] : 0;

        $FlightTempData = $objFlight->GetFlightTempData($strUrlData);
        //echo $strUrlData."<pre>";print_r($FlightTempData);die;
        $this->view->TPSysId = $TPSysId = ($FlightTempData['TPSysId'] > 0) ? $FlightTempData['TPSysId'] : 0;
        $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        $FlightBookingData = $arrUrlData['FlightBookingData'];
        $customer = $arrUrlData['customer'];
        $gstData = isset($arrUrlData['gstData']) ? $arrUrlData['gstData'] : [];
        $isHoldAllowed = isset($FlightBookingData[0]['isHoldAllowed']) ? trim($FlightBookingData[0]['isHoldAllowed']) : false;
        $sessionFlightSearchParams = $arrUrlData['sessionFlightSearchParams'];
        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        $PostData = ['TPSysId' => $TPSysId, 'version' => null];
        $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
        $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
        $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
        $CurrentStatus = isset($bookingDataByAPI[0]['CurrentStatus']) ? $bookingDataByAPI[0]['CurrentStatus'] : 0;
        $PaymentStatus = isset($bookingDataByAPI[0]['PaymentStatus']) ? $bookingDataByAPI[0]['PaymentStatus'] : 0;
        if (empty($arrUrlData) || ($CurrentStatus == 142 && $PaymentStatus == 130)) {
            echo 'Link expired!';
            exit;
        }
//         echo "<pre>";
//         print_r(($bookingDataByAPI));
//         die;
        $BaseFare = 0;
        $Taxesfee = 0;
        $CommDiscount = $Discount = 0;
        $TotalPay = 0;
        $ServiceFee__ = 0;
        $AirlineTax = 0;
        $FuelSurcharge = 0;
        $GSTOnMarkUp_ = 0;
        $FixedMarkUp_ = 0;
        $CommissionEarned_ = 0;
        $TDSEarn_ = 0;
        if ($FlightBookingData) {
            foreach ($FlightBookingData as $key => $value) {
                foreach ($value['FairRules']['FareBreakdown'] as $FareBreakdown) {
                    $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                    $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                    $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                    $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                    $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                    $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                    $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                    $Discount += isset($FareBreakdown['Discount']) ? ($FareBreakdown['Discount']) : 0;
                    $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                    $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                    $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                    $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                    $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                    $AirlineTax += ($Tax);
                    $FuelSurcharge += ($YQ);
                    $GSTOnMarkUp_ += ($GSTOnMarkUp);
                    $FixedMarkUp_ += ($FixedMarkUp);
                    $CommissionEarned_ += ($CommissionEarned);
                    $TDSEarn_ += ($TDSEarn);
                }
            }
        }
        $BagPrice = 0;
        $MealPrice = 0;
        $SeatPrice = 0;
        foreach ($customer as $kkkk => $ValCustomer) {
            $BagPrice += !empty($ValCustomer['BagPrice']) ? $ValCustomer['BagPrice'] : 0;
            $MealPrice += !empty($ValCustomer['MealPrice']) ? $ValCustomer['MealPrice'] : 0;
            $SeatPrice += !empty($ValCustomer['SeatPrice']) ? $ValCustomer['SeatPrice'] : 0;
        }
        $fare = [
            'Currency' => isset($FlightBookingData[0]['FairRules']['Currency']) ? trim($FlightBookingData[0]['FairRules']['Currency']) : 'INR',
            'BaseFare' => round($BaseFare, 2),
            'Taxesfee' => round($Taxesfee, 2),
            'CommDiscount' => round($CommDiscount+$Discount, 2),
            'CommissionEarned' => round($CommissionEarned_, 2),
            'TDSEarn' => round($TDSEarn_, 2),
            'TotalPay' => round($TotalPay - $CommDiscount - $Discount + $MealPrice + $BagPrice + $SeatPrice, 2),
            'AirlineTax' => round($AirlineTax, 2),
            'FuelSurcharge' => round($FuelSurcharge, 2),
            'FixedMarkUp' => round($FixedMarkUp_, 2),
            'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
            'MealPrice' => $MealPrice,
            'BagPrice' => $BagPrice,
            'SeatPrice' => $SeatPrice,
            'TotalSSR' => ($MealPrice + $BagPrice + $SeatPrice),
            'TotalProfit' => round(($TDSEarn_ + $CommissionEarned_ + $FixedMarkUp_ + $GSTOnMarkUp_ - $CommDiscount - $Discount), 2),
        ];
        $crmcustomerObj = new Travel_Model_CRM_Customer();
        $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);
        $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($sessionFlightSearchParams['CustomerSysId']) ? $sessionFlightSearchParams['CustomerSysId'] : 0;
        $customerDetails = $this->_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->confirm = $confirm;
        $wallet = Zend_Controller_Action_HelperBroker::getStaticHelper('Dashboard')->getWalletPrice($this->intLoggedinAgencyId);
        $this->view->walletBalanceAmount = '0.00'; //$wallet[0]['BalanceAmount'];
        $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;
        }
        $this->view->intLoggedinUserId = $this->intLoggedinUserId;
        $this->view->intLoggedinUserGroupSysId = $this->intLoggedinUserGroupId;
        $this->view->intLoggedinUserAgencySysId = $this->intLoggedinAgencyId;

        $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 . "/flight-new/search-result";
        $this->view->strReturnURL = $fullBaseUrl . "/flight-new/book-flight/data/" . $strUrlData;
        $this->view->strErrorURL = $fullBaseUrl . "/flight-new/review/data/" . $strUrlData;
        $this->view->strPayWithPaymentGatewayUrl = Catabatic_Helper::getSiteUrl() . "payment/payment-options/customer-pay";
        $this->view->strReturnURLCustomerPayment = $fullBaseUrl . "/flight/check-flight-payment/data/" . $strUrlData;
        $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;
        // echo "<pre>";
        // print_r(($customer));
        // die;
        $this->view->FlightBookingData = $FlightBookingData;
        $this->view->arrtravellerList = $customer;
        $this->view->fare = $fare;
        $this->view->gstData = $gstData;
        $this->view->isHoldAllowed = $isHoldAllowed;
    }

    public function seatmapAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $objFlight = new Travel_Model_TblFlight();
            $this->_helper->layout->disableLayout();
            $post = json_decode(file_get_contents('php://input'), true);
            $itemSg = $post['itemSg'];
            $FlightTempData = $objFlight->GetFlightTempData($post['searchids']);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $FlightBooking = $arrUrlData['FlightBookingData'];
            $tripSeatMap = (isset($arrUrlData['tripSeatMap']) && !empty($arrUrlData['tripSeatMap'])) ? $arrUrlData['tripSeatMap'][0] : '';
            $searchId = $SearchTraceId = $FlightBooking[0]['SearchTraceId'];
            $sessionFlightSearchParams = $arrUrlData['sessionFlightSearchParams'];
            $ICSourceSysId = $FlightBooking[0]['ICSourceSysId'];
            $SecKey = $itemSg['originAirportCode'] . '-' . $itemSg['destinationAirportCode'];
            $segmentid = $itemSg['segmentid'];
            $memberDetails = $post['memberDetails'];
            $selectedSeatSession = isset($post['selectedSeatSession']) ? $post['selectedSeatSession'] : [];
            $adultCount = ($sessionFlightSearchParams['adults']);
            $childCount = ($sessionFlightSearchParams['child']);
            $infantCount = ($sessionFlightSearchParams['infant']);
            $JourneyType = ($sessionFlightSearchParams['route']);
            $interNationalSearch = !empty($sessionFlightSearchParams['interNationalSearch']) ? $sessionFlightSearchParams['interNationalSearch'] : 0;

            $SegmentsArr = [];
            if ($FlightBooking) {
                foreach ($FlightBooking as $Datass) {
                    if ($Datass['Segments']) {
                        foreach ($Datass['Segments'] as $keys => $value) {
                            unset($value['BAGGAGE']);
                            unset($value['MEAL']);
                            $SegmentsArr[$SecKey] = $value;
                        }
                    }
                }
            }
            $selectedSeat = isset($selectedSeatSession[$segmentid]) ? $selectedSeatSession[$segmentid] : [];
            $CurrencyTitle = !empty($this->CurrencyTitle) ? trim($this->CurrencyTitle) : 'INR';
            $CurrencyRate = !empty($this->CurrencyRate) ? $this->CurrencyRate : 1;

            $POSTSEAT = [];
            if ($selectedSeat) {
                foreach ($selectedSeat as $pst) {
                    $POSTSEAT[] = [
                        'seatNo' => $pst['seatNo'],
                        'segmentid' => $segmentid,
                    ];
                }
            }

            if ($ICSourceSysId == 7) {
                $requestAPI = array(
                    'bookingId' => $FlightBooking[0]['APIBookingId'],
                );
                $DataS = array(
                    'apidata' => $requestAPI,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $SearchTraceId,
                    'ICSourceSysId' => $ICSourceSysId,
                    'AdultCount' => $adultCount,
                    'ChildCount' => $childCount,
                    'InfantCount' => $infantCount,
                    'segmentid' => $segmentid,
                    'SecKey' => $SecKey,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
                );
                $url = GTX_API_URL . '/flight/v3/getseatmap';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                
                $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);

                $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                $ErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';

                $arrUrlData['tripSeatMap'] = $apiResponse;
                $tempData = array(
                    'TraceId' => $SearchTraceId,
                    'TPSysId' => 0,
                    'APIBookingData' => json_encode($arrUrlData),
                );

                $objFlight->deleteFlightTempData($SearchTraceId);
                $objFlight->insertFlightTempData($tempData);
                // echo "<pre>";
                // print_r(($apiResponse['DataSet']));
                // echo "<pre>";
                // print_r(json_encode($apiResponse));
                // die;
            } else {
                $ResponseStatus = isset($tripSeatMap['status']['success']) ? $tripSeatMap['status']['success'] : false;
                $ErrorMessage = (isset($tripSeatMap['message']) && !empty($tripSeatMap['message'])) ? $tripSeatMap['message'] : 'Record Not Found';
                $apiResponse['tripSeatMap'] = isset($tripSeatMap['tripSeatMap']) ? $tripSeatMap['tripSeatMap'] : [];
                $apiResponse['DataSet'] = isset($tripSeatMap['tripSeatMap']['DataSet']) ? $tripSeatMap['tripSeatMap']['DataSet'] : [];
                $apiResponse['status'] = $ResponseStatus;
            }
            if ($ResponseStatus == 1) {
                $DataSet = isset($apiResponse['DataSet']) ? $apiResponse['DataSet'] : [];
                $status = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                if (isset($DataSet[$segmentid]) && $DataSet) {
                    $Data = $SegmentsArr[$SecKey];
                    $value = $DataSet[$segmentid];
                    $SelectedSeatArr = [];
                    $rows = (int) $value['rows'];
                    $column = (int) $value['column'];
                    $items = $value['items'];
                    $seats = $value['seats'];
                    $ColorArr = $value['ColorArr'];
                    // echo '<pre>';
                    // print_r($selectedSeat);
                    // echo '</pre>';
                    // echo '<pre>';
                    // print_r($memberDetails);
                    // echo '</pre>';
                    // die;
                    $SeatPrice = 0;
                    $memberData = [];
                    if ($memberDetails) {
                        foreach ($memberDetails as $key => $vl) {
                            if ($vl['PaxType'] != 3) {
                                $selectedData = isset($selectedSeat[$key]) ? $selectedSeat[$key] : '';
                                $SelectedSeatArr[] = $seatno = !empty($selectedData['seatNo']) ? $selectedData['seatNo'] : 'NA';
                                $amount = !empty($selectedData['amount']) ? $selectedData['amount'] : 0;
                                $SeatPrice += $amount;
                                $memberData[$key] = $vl;
                                $memberData[$key]['seatno'] = $seatno;
                                $memberData[$key]['amount'] = $amount;
                            }
                        }
                    }

                    $seatLayout = [];
                    $trr = 0;
                    for ($tr = 1; $tr <= $rows; $tr++) {
                        $tdd = 0;
                        for ($td = 1; $td <= $column; $td++) {

                            $SeatData = isset($seats[$tr . '-' . $td]) ? $seats[$tr . '-' . $td] : [];
                            $amounts = isset($SeatData['amount']) && !empty($SeatData['amount']) ? $SeatData['amount'] : 0;
                            $Prices = isset($SeatData['Price']) && !empty($SeatData['Price']) ? $SeatData['Price'] : 0;

                            $amount = round($amounts, 2);
                            $Price = round($Prices, 2);
                            $isAisle = isset($SeatData['isAisle']) ? $SeatData['isAisle'] : 0;
                            $isBooked = isset($SeatData['isBooked']) ? $SeatData['isBooked'] : 0;
                            $seatNo__ = isset($SeatData['seatNo']) ? $SeatData['seatNo'] : '';

                            if ($isBooked == 1) {
                                $CellColor = 'a4b4c1';
                                $Cell = 'CellBoked';
                                $tools = 'This seat is taken';
                            } else {
                                $CellColor = isset($ColorArr['' . $Price . '']) ? $ColorArr['' . $Price . ''] : '';
                                $Cell = 'Cell';
                                $tools = 'Seat No. ' . $seatNo__ . ' ' . $CurrencyTitle . ' ' . $Price;
                            }
                            if (in_array($seatNo__, $SelectedSeatArr)) {
                                $Cell = 'CellSelected';
                            } elseif ($isBooked != 1) {
                                $Cell = 'Cell';
                            }

                            if ($td == 3 && $ICSourceSysId == 3) {
                                $CellTypeC = 'CellTypeC';
                            } else {
                                $CellTypeC = '';
                            }

                            $seatLayout[$trr][$tdd] = [
                                'CellColor' => $CellColor,
                                'Cell' => $Cell,
                                'CellTypeC' => $CellTypeC,
                                'tools' => $tools,
                                'seatNo' => $seatNo__,
                                'isBooked' => $isBooked,
                                'isAisle' => $isAisle,
                                'amount' => $amount,
                                'Price' => $Price,
                            ];
                            $tdd++;
                        }
                        $trr++;
                    }
                    $ColorArray = [];
                    if ($ColorArr) {
                        foreach ($ColorArr as $key => $vl) {
                            $ColorArray[] = [
                                'color' => $vl,
                                'amount' => $key,
                            ];
                        }
                    }

                    $value['ColorArr'] = $ColorArray;

                    if ($seatLayout) {
                        foreach ($seatLayout as $x => $trValue) {
                            
                        }
                    }
                    $response = array(
                        'success' => true,
                        'message' => 'success',
                        'APIstatus' => $status,
                        'CurrencyTitle' => trim($CurrencyTitle),
                        'CurrencyRate' => $CurrencyRate,
                        'ICSourceSysId' => $ICSourceSysId,
                        'BookingID' => $SearchTraceId,
                        'memberData' => array_values($memberData),
                        'value' => $value,
                        'segmentid' => $segmentid,
                        'SecKey' => $SecKey,
                        'Data' => $Data,
                        'seatLayout' => $seatLayout,
                        'POSTSEAT' => $POSTSEAT,
                        'SeatPrice' => round($SeatPrice, 2),
                    );
                    $html = new Zend_View();
                    $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight-new/');
                    $html->assign(array('response' => $response));
                    $bodyText = $html->render('seatmap.phtml');
                    $response['bodyText'] = $bodyText;
                    echo json_encode($response);
                    exit;
                } else {
                    $response = array('success' => false, 'message' => 'Seat Selection Not Applicable for this Itinerary');
                    echo json_encode($response);
                    exit;
                }
            } else {
                $response = array('success' => false, 'message' => $ErrorMessage);
                echo json_encode($response);
                exit;
            }
            // echo "<pre>";
            // print_r(($apiResponse));
            // echo "<pre>";
            // print_r(($post));
            // die;
        }
    }

    public function continuewithseatmapAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $objFlight = new Travel_Model_TblFlight();
            $this->_helper->layout->disableLayout();
            $post = json_decode(file_get_contents('php://input'), true);

            $segmentid = $post['segmentid'];
            $MemberData = $post['MemberData'];
            $actiontype = $post['actiontype'];
            $selectedSeatSession = isset($post['selectedSeatSession']) ? $post['selectedSeatSession'] : [];
            $SelectedSeats = isset($post['SelectedSeats']) ? $post['SelectedSeats'] : [];
            $FlightTempData = $objFlight->GetFlightTempData($post['searchids']);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $FlightBooking = $arrUrlData['FlightBookingData'];
            // echo "<pre>";
            // print_r(($post));
            // die;
            $searchId = $SearchTraceId = $FlightBooking[0]['SearchTraceId'];
            $ICSourceSysId = $FlightBooking[0]['ICSourceSysId'];
            if ($ICSourceSysId == 3) {
                $tripSeatMap = (isset($arrUrlData['tripSeatMap']) && !empty($arrUrlData['tripSeatMap'])) ? $arrUrlData['tripSeatMap'][0] : '';
                $DataSet = isset($tripSeatMap['tripSeatMap']['DataSet']) ? $tripSeatMap['tripSeatMap']['DataSet'] : [];
            }
            $ResponseStatus = isset($tripSeatMap['status']['success']) ? $tripSeatMap['status']['success'] : false;
            $ErrorMessage = (isset($tripSeatMap['message']) && !empty($tripSeatMap['message'])) ? $tripSeatMap['message'] : 'Record Not Found';
            $apiResponse['tripSeatMap'] = isset($tripSeatMap['tripSeatMap']) ? $tripSeatMap['tripSeatMap'] : [];
            $apiResponse['DataSet'] = isset($tripSeatMap['tripSeatMap']['DataSet']) ? $tripSeatMap['tripSeatMap']['DataSet'] : [];
            $apiResponse['status'] = $ResponseStatus;
            if ($ICSourceSysId == 7) {
                $DataSet = isset($arrUrlData['tripSeatMap']['DataSet']) ? $arrUrlData['tripSeatMap']['DataSet'] : [];
            }
            // echo "<pre>";
            // print_r(($DataSet));
            // die;

            $CurrencyTitle = !empty($this->CurrencyTitle) ? trim($this->CurrencyTitle) : 'INR';
            $CurrencyRate = !empty($this->CurrencyRate) ? $this->CurrencyRate : 1;

            if ($post['segmentid'] && $post['MemberData'] && $post['actiontype'] && $post['SelectedSeats'] && $post['searchids']) {
                if (!empty($DataSet)) {
                    $value = $DataSet[$segmentid];

                    if (isset($DataSet[$segmentid]) && $DataSet) {
                        $items = $value['items'];

                        $selectedSeat = [];
                        $SelectedSegment = [];
                        if ($MemberData) {
                            foreach ($MemberData as $keys => $Customer) {
                                $seatNo = isset($SelectedSeats[$keys]['seatNo']) ? $SelectedSeats[$keys]['seatNo'] : '';
                                $paxType = $Customer['pax'] . '-' . ($keys + 1);
                                $checkSeat = str_replace(' ', '', $seatNo);
                                if (trim($checkSeat) != 'NA' && !empty($checkSeat)) {
                                    $SelectedSegment[] = $paxType . ': ' . $seatNo;
                                } else {
                                    $SelectedSegment[] = '';
                                }

                                foreach ($items as $k => $val) {
                                    if ($val['seatNo'] == $seatNo) {
                                        $val['cost'] = round($val['Price'], 2);
                                        $selectedSeat[$segmentid][$keys] = $val;
                                    }
                                }
                            }
                        }

                        if (count(array_filter($SelectedSegment)) == count($SelectedSegment)) {
                            $SelectedSegmentst = implode(', ', $SelectedSegment);
                        } else {
                            $SelectedSegmentst = '----';
                        }
                        $selectedSeatSession = !empty($selectedSeatSession) ? $selectedSeatSession : [];
                        // pr($selectedSeat);
                        // pr($selectedSeatSession);
                        // die;
                        if (!empty($selectedSeatSession)) {
                            foreach ($selectedSeatSession as $segid => $value) {
                                $index = 0;
                                if ($segid == $segmentid) {
                                    foreach ($value as $CustomerId => $val) {
                                        $seatNo = isset($SelectedSeats[$index]['seatNo']) ? $SelectedSeats[$index]['seatNo'] : '';
                                        $itemsdata = isset($items[$seatNo]) ? $items[$seatNo] : [];
                                        if (trim($val['seatNo']) == trim($seatNo)) {
                                            $val['cost'] = round($val['Price'], 2);
                                            $selectedSeatSession[$segmentid][$CustomerId] = $val;
                                        } else {
                                            $selectedSeatSession[$segmentid][$CustomerId] = $itemsdata;
                                        }
                                        $index++;
                                    }
                                } else {
                                    if ($MemberData) {
                                        foreach ($MemberData as $keys => $CustomerSysId) {
                                            $seatNo = isset($SelectedSeats[$keys]['seatNo']) ? $SelectedSeats[$keys]['seatNo'] : '';
                                            foreach ($items as $k => $val) {
                                                if ($val['seatNo'] == $seatNo) {
                                                    $val['cost'] = round($val['Price'], 2);
                                                    $selectedSeatSession[$segmentid][$keys] = $val;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            $selectedSeatSession = $selectedSeat;
                        }
                        if ($actiontype == '2') {
                            $selectedSeatSession = [];
                            $SelectedSegmentst = '----';
                        }
                        // echo "<pre>";
                        // print_r(($selectedSeatSession));
                        // die;
                        $SeatPrice = 0;
                        if ($selectedSeatSession) {
                            foreach ($selectedSeatSession as $values) {
                                foreach ($values as $val) {
                                    $SeatPrice += isset($val['Price']) ? $val['Price'] : 0;
                                }
                            }
                        }

                        $response = array(
                            'success' => true,
                            'message' => 'success',
                            'SelectedSegmentst' => $SelectedSegmentst,
                            'selectedSeatSession' => $selectedSeatSession,
                            'CurrencyTitle' => trim($CurrencyTitle),
                            'CurrencyRate' => $CurrencyRate,
                            'ICSourceSysId' => $ICSourceSysId,
                            'BookingID' => $SearchTraceId,
                            'SeatPrice' => round($SeatPrice, 2),
                        );
                        echo json_encode($response);
                        exit;
                    } else {
                        $response = array('success' => false, 'message' => 'Seat Selection Not Applicable for this Itinerary');
                        echo json_encode($response);
                        exit;
                    }
                } else {
                    $response = array('success' => false, 'message' => 'record not found');
                    echo json_encode($response);
                    exit;
                }
            }
            echo "<pre>";
            print_r(($tripSeatMap));
            echo "<pre>";
            print_r(($post));
            die;
        }
    }

    public function savePassengerDetailsAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $objFlight = new Travel_Model_TblFlight();
            $this->_helper->layout->disableLayout();
            $post = json_decode(file_get_contents('php://input'), true);
            parse_str($post['data'], $data);

            
            $isgstapply = isset($data['isgstapply']) ? trim($data['isgstapply']) : 0;
            $gstnnumber = isset($data['gstnnumber']) ? trim($data['gstnnumber']) : '';
            $companyname = isset($data['companyname']) ? trim($data['companyname']) : '';
            $gstemail = isset($data['gstemail']) ? trim($data['gstemail']) : '';
            $gstphone = isset($data['gstphone']) ? trim($data['gstphone']) : '';
            $gstaddress = isset($data['gstaddress']) ? trim($data['gstaddress']) : '';
            $gststate = isset($data['gststate']) ? trim($data['gststate']) : '';
            
            $memberDetails = isset($post['memberDetails']) ? $post['memberDetails'] : [];
            $selectedSeatSession = isset($post['selectedSeatSession']) ? $post['selectedSeatSession'] : [];
            $SelectedSeats = isset($post['SelectedSeats']) ? $post['SelectedSeats'] : [];
            $FlightTempData = $objFlight->GetFlightTempData($post['searchids']);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $FlightBooking = $arrUrlData['FlightBookingData'];
            $FARERULE = (isset($arrUrlData['FARERULE']) && !empty($arrUrlData['FARERULE'])) ? $arrUrlData['FARERULE'] : '';
            $tripSeatMap = (isset($arrUrlData['tripSeatMap']) && !empty($arrUrlData['tripSeatMap'])) ? $arrUrlData['tripSeatMap'][0] : '';
            $sessionFlightSearchParams = (isset($arrUrlData['sessionFlightSearchParams']) && !empty($arrUrlData['sessionFlightSearchParams'])) ? $arrUrlData['sessionFlightSearchParams'] : '';
            $searchId = $SearchTraceId = $FlightBooking[0]['SearchTraceId'];
            $ICSourceSysId = $FlightBooking[0]['ICSourceSysId'];
            
            $isGSTMandatory = isset($FlightBooking[0]['isGSTMandatory']) ? $FlightBooking[0]['isGSTMandatory'] : 0;
            
            $isDobAdult = isset($FlightBooking[0]['isDobAdult']) ? $FlightBooking[0]['isDobAdult'] : 0;
            $departureDates = isset($FlightBooking[0]['FromUTCTime']) ? date('Y-m-d', strtotime($FlightBooking[0]['FromUTCTime'])) : '';
            $ResponseStatus = isset($tripSeatMap['status']['success']) ? $tripSeatMap['status']['success'] : false;
            $ErrorMessage = (isset($tripSeatMap['message']) && !empty($tripSeatMap['message'])) ? $tripSeatMap['message'] : 'Record Not Found';
            $apiResponse['tripSeatMap'] = isset($tripSeatMap['tripSeatMap']) ? $tripSeatMap['tripSeatMap'] : [];
            $apiResponse['DataSet'] = isset($tripSeatMap['tripSeatMap']['DataSet']) ? $tripSeatMap['tripSeatMap']['DataSet'] : [];
            $apiResponse['status'] = $ResponseStatus;
            $DataSet = isset($apiResponse['DataSet']) ? $apiResponse['DataSet'] : [];

            $CurrencyTitle = !empty($this->CurrencyTitle) ? trim($this->CurrencyTitle) : 'INR';
            $CurrencyRate = !empty($this->CurrencyRate) ? $this->CurrencyRate : 1;
            $countryCodeISO = strtoupper($data['countryCodeISO']);
            $countrycode = $data['countrycode'];
            $mobileNumber = $data['mobile_number'];
            $email_id = $data['email_id'];
            $airline_number = $data['airline_number'];
            $airline_email = $data['airline_email'];
            // echo "<pre>";
            // print_r(($data));
            // die('wwwww');
            if (empty($airline_number)) {
                $response = array('success' => false, 'message' => 'Please enter airline 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 valid airline 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 airline Email ID.', 'index' => 'airline_email');
                echo json_encode($response);
                exit;
            }
            if (!filter_var($airline_email, FILTER_VALIDATE_EMAIL)) {
                $msg = "Airline 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;
            }
            
            $paxArray = [];
            $memberData = [];
            if ($memberDetails) {
                foreach ($memberDetails as $i => $value) {
                    $paxType = $value['PaxType'];
                    $pax = $value['pax'];
                    $isdobr = $value['isdobr'];
                    $IsPassM = $value['IsPassM'];
                    $IsDocIdM = isset($value['IsDocIdM']) ? $value['IsDocIdM'] : false;
                    $firstName = $fname = $data['passenger-firstname-' . $i];
                    $lastName = $data['passenger-lastname-' . $i];
                    $relation = $data['relation-' . $i];
                    $salutation = $data['passenger-salutation-' . $i];
                    $cityName = ($data['passenger-city-name-0']) ? $data['passenger-city-name-0'] : '';
                    $CitySysId = ($data['passenger-city-0']) ? $data['passenger-city-0'] : 0;
                    $passengerCountry = ($data['passenger-country-0']) ? $data['passenger-country-0'] : 0;
                    $passengerAddress = ($data['passenger-address-0']) ? $data['passenger-address-0'] : '';

                    $docid = isset($data['passenger-docid-' . $i]) ? $data['passenger-docid-' . $i] : '';
                    $passengerDob = isset($data['passenger-dob-' . $i]) ? $data['passenger-dob-' . $i] : '';
                    $nationality = isset($data['passenger-nationality-' . $i]) ? $data['passenger-nationality-' . $i] : '';
                    $passengerPassportNo = isset($data['passenger-PassportNo-' . $i]) ? $data['passenger-PassportNo-' . $i] : '';
                    $PassportExpiry = isset($data['passenger-PassportExpiry-' . $i]) ? $data['passenger-PassportExpiry-' . $i] : '';
                    $passporIssue = isset($data['passenger-passporIssue-' . $i]) ? $data['passenger-passporIssue-' . $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');
                    $paxArray[] = ucfirst(trim($firstName)) . ' ' . ucfirst(trim($lastName));
                    $memberData[$i] = $value;
                    $memberData[$i]['relation'] = $relation;
                    $memberData[$i]['title'] = $salutation;
                    $memberData[$i]['passno'] = $passengerPassportNo;
                    $memberData[$i]['passisse'] = $passporIssue;
                    $memberData[$i]['passexp'] = $PassportExpiry;
                    $memberData[$i]['passnational'] = $nationality;
                    $memberData[$i]['fname'] = $firstName;
                    $memberData[$i]['lname'] = $lastName;
                    $memberData[$i]['city'] = $cityName;
                    $memberData[$i]['address'] = $passengerAddress;
                    $memberData[$i]['CountrySysId'] = $passengerCountry;
                    $memberData[$i]['CitySysId'] = $CitySysId;
                    $memberData[$i]['dob'] = $passengerDob;
                    $memberData[$i]['countrycode'] = $countrycode;
                    $memberData[$i]['countryCodeISO'] = $countryCodeISO;
                    $memberData[$i]['docid'] = $docid;

                    if (empty($cityName)) {
                        $response = array('success' => false, 'message' => 'Please enter city name.', 'index' => 'passenger-city-name-0');
                        echo json_encode($response);
                        exit;
                    }
                    if (empty($CitySysId)) {
                        $response = array('success' => false, 'message' => 'Please enter valid city name.', 'index' => 'passenger-city-name-0');
                        echo json_encode($response);
                        exit;
                    }
                    if (empty($passengerAddress)) {
                        $response = array('success' => false, 'message' => 'Please enter address.', 'index' => 'passenger-address-0');
                        echo json_encode($response);
                        exit;
                    }
                    if (empty($firstName)) {
                        $response = array('success' => false, 'message' => 'Please enter first name.', 'index' => 'passenger-firstname-' . $i);
                        echo json_encode($response);
                        exit;
                    }

                    if (empty($lastName)) {
                        $response = array('success' => false, 'message' => 'Please enter last name.', 'index' => 'passenger-lastname-' . $i);
                        echo json_encode($response);
                        exit;
                    }
                    if (strlen(trim($firstName)) < 2) {
                        $response = array('success' => false, 'message' => 'Length of first name should be between 2 to 32 alphabets for passenger.', 'index' => 'passenger-firstname-' . $i);
                        echo json_encode($response);
                        exit;
                    }
                    if (strlen(trim($lastName)) < 2) {
                        $response = array('success' => false, 'message' => 'Length of last name should be between 2 to 32 alphabets for passenger.', 'index' => 'passenger-lastname-' . $i);
                        echo json_encode($response);
                        exit;
                    }

                    if ($isdobr == 1 && $paxType == 1) {
                        if (empty($passengerDob) && ($passengerDob == '1900-01-01' || $passengerDob == '00/00/0000' || $passengerDob == '____-__-__')) {
                            $response = array('success' => false, 'message' => 'Please enter ' . $pax . ' date of birth.', 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        $AdultAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                        if ($AdultAge < 12) {
                            $response = array('success' => false, 'message' => " " . $pax . " age should be greater than 12 years. ", 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                    }
                    if ($isdobr == 1 && $paxType == 2) {
                        if (empty($passengerDob) && ($passengerDob == '1900-01-01' || $passengerDob == '00/00/0000' || $passengerDob == '____-__-__')) {
                            $response = array('success' => false, 'message' => 'Please enter ' . $pax . ' date of birth.', 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        $childAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                        if ($childAge < 2 || $childAge >= 12) {
                            $response = array('success' => false, 'message' => " " . $pax . " age should be greater than 12 years. ", 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                    }
                    if ($isdobr == 1 && $paxType == 3) {
                        if (empty($passengerDob) && ($passengerDob == '1900-01-01' || $passengerDob == '00/00/0000' || $passengerDob == '____-__-__')) {
                            $response = array('success' => false, 'message' => 'Please enter ' . $pax . ' date of birth.', 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        $infantAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                        if ($infantAge >= 2) {
                            $response = array('success' => false, 'message' => " " . $pax . " age should be greater than 12 years. ", 'index' => 'passenger-dob-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if ($IsPassM == 1) {
                        if (empty($passengerPassportNo)) {
                            $response = array('success' => false, 'message' => 'Please enter passenger passport no.', 'index' => 'passenger-PassportNo-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        if (empty($nationality)) {
                            $response = array('success' => false, 'message' => 'Please select Nationality.', 'index' => 'passenger-nationality-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        if (empty($passporIssue) || ($passporIssue == '1900-01-01' || $passporIssue == '00/00/0000' || $passporIssue == '____-__-__')) {
                            $response = array('success' => false, 'message' => 'Please enter passport issue date.', 'index' => 'passenger-passporIssue-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                        if (empty($PassportExpiry) || ($PassportExpiry == '1900-01-01' || $PassportExpiry == '00/00/0000' || $PassportExpiry == '____-__-__')) {
                            $response = array('success' => false, 'message' => 'Please enter passport expiry date.', 'index' => 'passenger-PassportExpiry-' . $i);
                            echo json_encode($response);
                            exit;
                        }
                    }
                }
                if ($FlightBooking && $isgstapply == 0) {
                    foreach ($FlightBooking as $values) {
                        if (trim($values['isGSTMandatory']) == 1) {
                                $response = array('success' => false, 'message' => 'GST mandatory for this flight.', 'index' => 'gstnnumber');
                                echo json_encode($response);
                                exit;
                        }
                    }
                }
                if ($isgstapply == 1) {
                        if (empty(trim($gstnnumber))) {
                                $response = array('success' => false, 'message' => 'Please enter GSTIN number.', 'index' => 'gstnnumber');
                                echo json_encode($response);
                                exit;
                        }
                        $is_valid_gstin = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->is_valid_gstin($gstnnumber);
                        if ($is_valid_gstin == 0) {
                                $response = array('success' => false, 'message' => 'Enter Valid GST Number', 'index' => 'gstnnumber');
                                echo json_encode($response);
                                exit;
                        }
                        if (empty(trim($companyname))) {
                                $response = array('success' => false, 'message' => 'Please enter company name.', 'index' => 'companyname');
                                echo json_encode($response);
                                exit;
                        }
                        if (empty(trim($gstemail))) {
                                $response = array('success' => false, 'message' => 'Please enter registered email id.', 'index' => 'gstemail');
                                echo json_encode($response);
                                exit;
                        }
                        if (!filter_var($gstemail, FILTER_VALIDATE_EMAIL)) {
                                $msg = "GST Email address is not valid.";
                                $response = array('success' => false, 'message' => $msg, 'index' => 'gstemail');
                                echo json_encode($response);
                                exit;
                        }
                        if (empty(trim($gstphone))) {
                                $response = array('success' => false, 'message' => 'Please enter registered phone.', 'index' => 'gstphone');
                                echo json_encode($response);
                                exit;
                        }
                        if (strlen($gstphone) != 10 && strlen($gstphone) != 11) {
                                $response = array('success' => false, 'message' => 'Please enter a valid GST phone number.', 'index' => 'gstphone');
                                echo json_encode($response);
                                exit;
                        }
                        if (empty(trim($gstaddress))) {
                                $response = array('success' => false, 'message' => 'Please enter GST address.', 'index' => 'gstaddress');
                                echo json_encode($response);
                                exit;
                        }
                }
                
            }

            if (array_diff_assoc($paxArray, array_unique($paxArray))) {
                $response = array('success' => false, 'message' => " Any two passengers can't have same name.", 'index' => '');
                echo json_encode($response);
                exit;
            }
            // echo "<pre>";
            // print_r(($memberData));
            // die;
            
            $selectedBag = isset($post['SelectedBags']) ? $post['SelectedBags'] : [];
            $selectedMeal = isset($post['SelectedMeals']) ? $post['SelectedMeals'] : [];
            $selectedSeatSession = isset($post['selectedSeatSession']) ? $post['selectedSeatSession'] : [];

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

            $intCustomerSysId = isset($data['customerId']) ? trim($data['customerId']) : '';
            $AgencySysId = isset($sessionFlightSearchParams['AgencySysId']) ? $sessionFlightSearchParams['AgencySysId'] : '';
            $B2BType = isset($sessionFlightSearchParams['B2BType']) ? $sessionFlightSearchParams['B2BType'] : 0;
            $editLeadId = isset($sessionFlightSearchParams['editLeadId']) ? $sessionFlightSearchParams['editLeadId'] : '';

            $adultCount = isset($sessionFlightSearchParams['adults']) ? $sessionFlightSearchParams['adults'] : 0;
            $childCount = isset($sessionFlightSearchParams['child']) ? $sessionFlightSearchParams['child'] : 0;
            $infantCount = isset($sessionFlightSearchParams['infant']) ? $sessionFlightSearchParams['infant'] : 0;
            $route = $JourneyType = isset($sessionFlightSearchParams['route']) ? $sessionFlightSearchParams['route'] : '';
            $interNationalSearch = isset($sessionFlightSearchParams['interNationalSearch']) ? $sessionFlightSearchParams['interNationalSearch'] : '';
            $totalPassengers = $adultCount + $childCount + $infantCount;
            $departure_dates_string = $sessionFlightSearchParams['departure_dates'];
            $return_dates_string = $sessionFlightSearchParams['return_dates'];
            $oneway_origin_text = isset($sessionFlightSearchParams['from']) ? $sessionFlightSearchParams['from'] : $sessionFlightSearchParams['sourceCityText'];
            $oneway_destination_text = isset($sessionFlightSearchParams['to']) ? $sessionFlightSearchParams['to'] : $sessionFlightSearchParams['destinationCityText'];
            $flight_class = $sessionFlightSearchParams['flight_class'];
            $sourceCityId = $sessionFlightSearchParams['sourceCityId'];
            $destinationCityId = $sessionFlightSearchParams['destinationCityId'];
            $UserSysId = $sessionFlightSearchParams['UserSysId'];
            $MasterAgencySysId = $sessionFlightSearchParams['MasterAgencySysId'];

            $roomjson = array();
            $roomjson[1]['route'] = $route;
            $roomjson[1]['Adult'] = $adultCount;
            $roomjson[1]['Child'] = $childCount;
            $roomjson[1]['Infant'] = $infantCount;
            $roomjson[1]['bedtype'] = '';
            $roomjson[1]['departuredate'] = $departure_dates_string;
            $roomjson[1]['returndate'] = ($route == 2) ? $return_dates_string : null;
            $roomjson[1]['fromaircode'] = $oneway_origin_text;
            $roomjson[1]['toaircode'] = $oneway_destination_text;
            $roomjson[1]['airclass'] = $flight_class;

            if ($route == 3) {
                $oneway_origin_text = (current($sessionFlightSearchParams['from']));
                $oneway_destination_text = (end($sessionFlightSearchParams['to']));
                $sourceCityId = (current($sessionFlightSearchParams['sourceCityId']));
                $destinationCityId = (end($sessionFlightSearchParams['destinationCityId']));
            }

            if ($ICSourceSysId == 8) {
                $DataS = array(
                    'apidata' => [],
                    'BookingData' => $FlightBooking,
                    'customer' => [],
                    'gstData' => $gstData,
                    'memberCount' => $totalPassengers,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $post['searchids'],
                    'ICSourceSysId' => $ICSourceSysId,
                    'AgentMarkUp' => 0,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                );
                // echo "<pre>";
                // print_r(($DataS));
                // die;
                $url = GTX_API_URL . '/flight/v3/book';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                $Bookres = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                if ($Bookres['results']) {
                    foreach ($Bookres['results'] as $k => $value) {
                        if (empty($value['IsLCC'])) {
                            $ResponseStatus = $value['ResponseStatus'];
                            if ($ResponseStatus != 1) {
                                $response = array('success' => false, 'message' => 'Oops ! No Seats are available', 'index' => '');
                                echo json_encode($response);
                                exit;
                            }
                        }
                    }
                    $FlightBooking = isset($Bookres['results']) ? $Bookres['results'] : [];
                }
            }

            // echo "<pre>";
            // print_r(($FlightBooking));
            // die;
            $FLData = [];
            $BaggageArr = [];
            $MealArr = [];
            $segment_ssr = [];
            $customer = [];
            $baggageByPax = [];
            $Sectors = [];
            $BaseFare = 0;
            $PublishedFare = 0;
            $AgencyMarkUpINT_ = 0;
            $AgencyMarkUpGSTINT_ = 0;
            $CommissionEarnedAPI = 0;
            if ($FlightBooking) {
                foreach ($FlightBooking as $k => $value) {
                    $BagPrice = 0;
                    $MealPrice = 0;
                    $SeatPrice = 0;
                    $FareBreakdown_ = [];
                    $GrossAmount = 0;
                    $AgentMarkUp = 0;
                    $TotalCommDiscount = 0;
                    foreach ($value['FairRules']['FareBreakdown'] as $valueB) {
                        // echo '<pre>';print_r($valueB);
                        $baggageByPax[$valueB['PassengerType']]['Baggage'] = $valueB['Baggage'];
                        $baggageByPax[$valueB['PassengerType']]['CabinBaggage'] = $valueB['CabinBaggage'];
                        $FareBreakdown_[] = array(
                            "Currency" => $valueB['Currency'],
                            "PassengerCount" => $valueB['PassengerCount'],
                            "PassengerType" => $valueB['PassengerType'],
                            "BaseFare" => $valueB['BaseFare'],
                            "Tax" => isset($valueB['Tax']) ? ($valueB['Tax']) : (($valueB['TaxIN'])),
                            "OfferedFare" => ($valueB['OfferedFare']) ? $valueB['OfferedFare'] : 0,
                            "TotalFare" => $valueB['PublishedFare'],
                            "PublishedFare" => $valueB['PublishedFare'],
                            "TDSEarn" => $valueB['TDSEarn'],
                            "MF" => isset($valueB['TaxBR']['MF']) ? $valueB['TaxBR']['MF'] : $valueB['MF'],
                            "YQ" => isset($valueB['TaxBR']['YQ']) ? $valueB['TaxBR']['YQ'] : 0,
                            "AGST" => isset($valueB['TaxBR']['AGST']) ? $valueB['TaxBR']['AGST'] : $valueB['AGST'],
                            "MFT" => isset($valueB['TaxBR']['MFT']) ? $valueB['TaxBR']['MFT'] : $valueB['MFT'],
                            "OT" => isset($valueB['TaxBR']['OT']) ? $valueB['TaxBR']['OT'] : (($valueB['OT'])),
                            "YR" => isset($valueB['TaxBR']['YR']) ? $valueB['TaxBR']['YR'] : $valueB['YR'],
                            "CommissionEarned" => $valueB['CommissionEarned'],
                            "FixedMarkUp" => ($valueB['FixedMarkUp']) ? $valueB['FixedMarkUp'] : 0,
                            "GSTOnMarkUp" => ($valueB['GSTOnMarkUp']) ? $valueB['GSTOnMarkUp'] : 0,
                            "couponVal" => isset($valueB['couponVal']) ? $valueB['couponVal'] : 0,
                            "CommDiscount" => $valueB['CommDiscount'],
                            "AgentMarkUp" => isset($valueB['AgentMarkUp']) ? (($valueB['AgentMarkUp'])) : 0
                        );
                    }
                    $couponApply = isset($value['FairRules']['couponApply']) ? $value['FairRules']['couponApply'] : 0;
                    $couponVal = 0;
                    if ($couponApply == 1) {
                        $couponVal = isset($value['FairRules']['couponVal']) ? $value['FairRules']['couponVal'] : 0;
                    }

                    $BaseFare += (($value['FairRules']['BaseFare'] + $value['FairRules']['Tax']) - $couponVal);
                    $PublishedFare += ($value['FairRules']['PublishedFare'] - $couponVal);
                    $AgencyMarkUpINT_ += $value['FairRules']['FixedMarkUp'];
                    $AgencyMarkUpGSTINT_ += $value['FairRules']['GSTOnMarkUp'];
                    $CommissionEarnedAPI += ($value['FairRules']['CommissionEarned'] + $value['FairRules']['TDSEarn']);
                    $fareRuless = array(
                        "Currency" => $value['FairRules']['Currency'],
                        "BaseFare" => $value['FairRules']['BaseFare'],
                        "Tax" => isset($value['FairRules']['Tax']) ? (($value['FairRules']['Tax'])) : 0,
                        "PublishedFare" => ($value['FairRules']['PublishedFare']) ? $value['FairRules']['PublishedFare'] : 0,
                        "OfferedFare" => ($value['FairRules']['OfferedFare']) ? $value['FairRules']['OfferedFare'] : 0,
                        "CommissionEarned" => ($value['FairRules']['CommissionEarned']) ? (($value['FairRules']['CommissionEarned'])) : 0,
                        "FixedMarkUp" => ($value['FairRules']['FixedMarkUp']) ? $value['FairRules']['FixedMarkUp'] : 0,
                        "GSTOnMarkUp" => ($value['FairRules']['GSTOnMarkUp']) ? $value['FairRules']['GSTOnMarkUp'] : 0,
                        "CommDiscount" => ($value['FairRules']['CommDiscount']) ? (($value['FairRules']['CommDiscount'])) : 0,
                        "couponVal" => isset($value['FairRules']['couponVal']) ? (($value['FairRules']['couponVal'])) : 0,
                        "TDSEarn" => ($value['FairRules']['TDSEarn']) ? (($value['FairRules']['TDSEarn'])) : 0,
                        "AgentMarkUp" => 0,
                        "BagPrice" => isset($BagPrice) ? $BagPrice : 0,
                        "MealPrice" => isset($MealPrice) ? $MealPrice : 0,
                        "SeatPrice" => isset($SeatPrice) ? $SeatPrice : 0,
                        "FareBreakdown" => $FareBreakdown_
                    );
                    $segment_ = [];
                    if ($value['Segments']) {
                        foreach ($value['Segments'] as $seg) {

                            if (isset($seg['BAGGAGE'])) {
                                foreach ($seg['BAGGAGE'] as $b => $bag) {
                                    $BaggageArr[] = $bag;
                                }
                            }
                            if (isset($seg['MEAL'])) {
                                foreach ($seg['MEAL'] as $m => $meals) {
                                    $MealArr[] = $meals;
                                }
                            }
                            $Sectors[] = $seg['originAirportCode'] . '-' . $seg['destinationAirportCode'];
                            $segment_[] = $segment_ssr[$seg['segmentid']] = array(
                                "id" => intval($seg['segmentid']),
                                "flight_booking_id" => '',
                                "TraceId" => $value['SearchTraceId'],
                                "segmentid" => intval($seg['segmentid']),
                                "segmentids" => isset($seg['segmentids']) ? intval($seg['segmentids']) : 0,
                                "isReturnSegment" => $seg['isReturnSegment'],
                                "arrivingnextday" => $seg['arrivingnextday'],
                                "originAirportName" => $seg['originAirportName'],
                                "destinationAirportName" => $seg['destinationAirportName'],
                                "originCityName" => $seg['originCityName'],
                                "originCountryName" => $seg['originCountryName'],
                                "destinationCityName" => $seg['destinationCityName'],
                                "destinationCountryName" => $seg['destinationCountryName'],
                                "destinationAirportCode" => $seg['destinationAirportCode'],
                                "destinationArrTime" => date('Y-m-d H:i', strtotime($seg['destinationArrTime'])),
                                "SegFlightNumber" => $seg['SegFlightNumber'],
                                "AirlineCode" => $seg['AirlineCode'],
                                "AirlineName" => $seg['AirlineName'],
                                "FareClass" => $seg['FareClass'],
                                "cabinClass" => ($seg['cabinClass']) ? $seg['cabinClass'] : $value['FlightClass'],
                                "originAirportCode" => $seg['originAirportCode'],
                                "originDepTime" => date('Y-m-d H:i', strtotime($seg['originDepTime'])),
                                "CheckinBaggage" => !empty($seg['CheckinBaggage']) ? $seg['CheckinBaggage'] : $value['FairRules']['CheckinBaggage'],
                                "CabinBaggage" => !empty($seg['CabinBaggage']) ? $seg['CabinBaggage'] : $value['FairRules']['CabinBaggage'],
                                "IsBaggage" => isset($seg['IsBaggage']) ? $seg['IsBaggage'] : false,
                                "IsMealIncludes" => isset($seg['IsMealIncludes']) ? $seg['IsMealIncludes'] : false,
                                "Duration" => $seg['Duration'],
                                "GroundTime" => $seg['GroundTime'],
                                "NoOfSeatAvailable" => $seg['NoOfSeatAvailable'],
                                "FlightDuration" => $seg['FlightDuration'],
                                "LAYOVERDuration" => $seg['LAYOVERDuration'],
                                "LAYOVERCity" => $seg['LAYOVERCity'],
                                "DepTerminal" => $seg['DepTerminal'],
                                "ArrTerminal" => $seg['ArrTerminal'],
                                "filePath" => isset($seg['filePath']) ? $seg['filePath'] : '',
                                "SourceAirportCode" => $seg['originAirportCode'],
                                "DestAirportCode" => $seg['destinationAirportCode'],
                                "strArrivalDtTime" => $seg['strArrivalDtTime'],
                                "strDepartureDtTime" => $seg['strDepartureDtTime'],
                                "TravelDate" => $seg['originDepTime'],
                                "BagPrice" => 0,
                                "MealPrice" => 0,
                                "SeatPrice" => 0
                            );
                        }
                    }
                    // print_r($value);
                    $FLData[$k]['FlightNumber'] = $value['FlightNumber'];
                    $FLData[$k]['AirlineName'] = $value['AirlineName'];
                    $FLData[$k]['SupplierSysId'] = isset($value['SupplierSysId']) ? $value['SupplierSysId'] : 0;
                    $FLData[$k]['BookingId'] = isset($value['bookingId']) ? $value['bookingId'] : '';
                    $FLData[$k]['APIBookingId'] = isset($value['APIBookingId']) ? $value['APIBookingId'] : '';
                    $FLData[$k]['IsLCC'] = $value['IsLCC'];
                    $FLData[$k]['LocalFromTime'] = date('Y-m-d H:i', strtotime($value['FromUTCTime']));
                    $FLData[$k]['LocalToTime'] = date('Y-m-d H:i', strtotime($value['ToUTCTime']));
                    $FLData[$k]['ICSourceSysId'] = $value['ICSourceSysId'];
                    $FLData[$k]['apiTraceId'] = $value['SearchTraceId'];
                    $FLData[$k]['ApiResultIndex'] = $value['FairRules']['PriceID'];
                    $FLData[$k]['JourneyType'] = $value['JourneyType'];
                    $FLData[$k]['TripType'] = intval($value['TripType']);
                    $FLData[$k]['IsRefundable'] = ($value['IsRefundable']) ? $value['IsRefundable'] : false;
                    $FLData[$k]['IsInternational'] = $interNationalSearch;
                    $FLData[$k]['SourceAirportCode'] = $value['SourceAirportCode'];
                    $FLData[$k]['DestAirportCode'] = $value['DestAirportCode'];
                    $FLData[$k]['FairRules'] = $fareRuless;
                    $FLData[$k]['Segments'] = $segment_;
                    $FLData[$k]['FARERULE'] = isset($FARERULE[$k]) ? $FARERULE[$k] : [];
                }
            }

            if ($JourneyType == 2 && $interNationalSearch == 1) {
                $TripCount = 1;
            } else {
                $TripCount = 1; //count($FlightBooking);
            }

            $ARR_SALUTIONTBO = $ARR_SALUTIONTBO = array("1" => "Mr", "2" => "Mrs", "3" => "Ms", "4" => "Mstr", "5" => "Miss");
            $TotalBG = 0;
            $TotalML = 0;
            $TotalST = 0;
            if ($memberData) {
                $A = 1;
                $C = 1;
                $I = 1;

                $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
                $ARR_SALUTION_CHILD = array_flip($ARR_SALUTIONTBO);

                foreach ($memberData as $kkkk => $ValCustomer) {
                    $paxType = $ValCustomer['PaxType'];
                    if ($ValCustomer['PaxType'] == 1) {
                        $paxType = 'ADULT' . $A;
                        $A++;
                    } elseif ($ValCustomer['PaxType'] == 2) {
                        $paxType = 'CHILD' . $C;
                        $C++;
                    } else {
                        $paxType = 'INFANT' . $I;
                        $I++;
                    }
                    $CheckinBaggage = isset($baggageByPax[$ValCustomer['PaxType']]['Baggage']) ? $baggageByPax[$ValCustomer['PaxType']]['Baggage'] : '';
                    $CabinBaggage = isset($baggageByPax[$ValCustomer['PaxType']]['CabinBaggage']) ? $baggageByPax[$ValCustomer['PaxType']]['CabinBaggage'] : '';

                    $getSelectedAddon = $this->getSelectedAddon($selectedBag, $selectedMeal, $paxType, $BaggageArr, $MealArr);
                    $paxTypeBag = (isset($getSelectedAddon['paxTypeBag']) && !empty($getSelectedAddon['paxTypeBag'])) ? $getSelectedAddon['paxTypeBag'] : [];
                    $paxTypeMeal = (isset($getSelectedAddon['paxTypeMeal']) && !empty($getSelectedAddon['paxTypeMeal'])) ? $getSelectedAddon['paxTypeMeal'] : [];
                    $BagPrice = (isset($getSelectedAddon['BagPrice']) && !empty($getSelectedAddon['BagPrice'])) ? $getSelectedAddon['BagPrice'] : 0;
                    $MealPrice = (isset($getSelectedAddon['MealPrice']) && !empty($getSelectedAddon['MealPrice'])) ? $getSelectedAddon['MealPrice'] : 0;
                    $SeatPrice_c = 0;
                    $SelectedSeat = [];
                    if ($selectedSeatSession && ($ValCustomer['PaxType'] == 1 || $ValCustomer['PaxType'] == 2)) {
                        foreach ($selectedSeatSession as $segmentid => $value) {
                            $sorcdes = isset($segment_ssr[$segmentid]) ? $segment_ssr[$segmentid] : [];
                            $Orgin = isset($v['Origin']) ? $v['Origin'] : @$sorcdes['originAirportCode'];
                            $Destination = isset($v['Destination']) ? $v['Destination'] : @$sorcdes['destinationAirportCode'];
                            if (isset($value[$kkkk])) {
                                $SelectedSeat[$Orgin . '-' . $Destination][] = isset($value[$kkkk]) ? $value[$kkkk] : [];
                                $SeatPrice_c += $value[$kkkk]['Price'];
                                $SeatPrice += $value[$kkkk]['Price'];
                            }
                        }
                    }

                    // echo "<pre>";
                    // print_r(($getSelectedAddon));
                    $TotalBG += (float) $BagPrice;
                    $TotalML += (float) $MealPrice;
                    $TotalST += (float) $SeatPrice_c;

                    if ($ValCustomer['PaxType'] == 1) {
                        $paxTitle = ($ARR_SALUTION[$ValCustomer['title']]);
                    } elseif ($ValCustomer['PaxType'] == 2) {
                        $paxTitle = ($ARR_SALUTION_CHILD[$ValCustomer['title']]);
                    } else {
                        $paxTitle = ($ARR_SALUTION_CHILD[$ValCustomer['title']]);
                    }
                    $docid = isset($ValCustomer['docid']) ? $ValCustomer['docid'] : '';
                    $customer[] = array(
                        "city_id" => $ValCustomer['CitySysId'],
                        "country_id" => $ValCustomer['CountrySysId'],
                        "countryName" => isset($ValCustomer['countryName']) ? $ValCustomer['countryName'] : '',
                        "city" => $ValCustomer['city'],
                        "address" => $ValCustomer['address'],
                        "email" => $email_id,
                        "airline_number" => $airline_number,
                        "airline_email" => $airline_email,
                        "mobile" => (int) $mobileNumber,
                        "countryCode" => (int) isset($ValCustomer['countrycode']) ? $ValCustomer['countrycode'] : '',
                        "countryCodeISO" => isset($countryCodeISO) ? $countryCodeISO : '',
                        "relation" => isset($ValCustomer['relation']) ? $ValCustomer['relation'] : '9',
                        "firstname" => $ValCustomer['fname'],
                        "lastname" => $ValCustomer['lname'],
                        "salution" => $paxTitle, //$ValCustomer['title'],
                        "dateofbirth" => $ValCustomer['dob'],
                        "docid" => $docid,
                        "isgstapply" => $isgstapply,
                        "passportnoexpiry" => isset($ValCustomer['passexp']) ? $ValCustomer['passexp'] : '',
                        "passporIssue" => isset($ValCustomer['passisse']) ? $ValCustomer['passisse'] : '',
                        "PassportNationality" => isset($ValCustomer['passnational']) ? $ValCustomer['passnational'] : '',
                        "passportno" => isset($ValCustomer['passno']) ? $ValCustomer['passno'] : '',
                        "paxType" => $ValCustomer['PaxType'],
                        "sectors" => isset($ValCustomer['sectors']) ? $ValCustomer['sectors'] : '',
                        "CheckinBaggage" => isset($CheckinBaggage) ? $CheckinBaggage : '',
                        "CabinBaggage" => isset($CabinBaggage) ? $CabinBaggage : '',
                        "BagPrice" => (!empty($BagPrice)) ? ($BagPrice / $TripCount) : $BagPrice,
                        "MealPrice" => (!empty($MealPrice)) ? ($MealPrice / $TripCount) : $MealPrice,
                        "SeatPrice" => (!empty($SeatPrice_c)) ? ($SeatPrice_c / $TripCount) : $SeatPrice_c,
                        // "BagPrice" => (!empty($BagPrice) && $ICSourceSysId != 3) ? ($BagPrice / $TripCount) : $BagPrice,
                        // "MealPrice" => (!empty($MealPrice) && $ICSourceSysId != 3) ? ($MealPrice / $TripCount) : $MealPrice,
                        // "SeatPrice" => (!empty($SeatPrice_c) && $ICSourceSysId != 3) ? ($SeatPrice_c / $TripCount) : $SeatPrice_c,
                        "SelectedBag" => (!empty($paxTypeBag)) ? json_encode($paxTypeBag) : '',
                        "SelectedMeal" => (!empty($paxTypeMeal)) ? json_encode($paxTypeMeal) : '',
                        "SelectedSeat" => (!empty($SelectedSeat)) ? json_encode($SelectedSeat) : ''
                    );
                }
            }

            $TripCount = count($FlightBooking);
            $FLDataNew = [];
            if ($FLData) {
                foreach ($FLData as $kfl => $vlfl) {
                    $vlfl['FairRules']['BagPrice'] = round($TotalBG / $TripCount, 2);
                    $vlfl['FairRules']['MealPrice'] = round($TotalML / $TripCount, 2);
                    $vlfl['FairRules']['SeatPrice'] = round($TotalST / $TripCount, 2);
                    $FLDataNew[$kfl] = $vlfl;
                }
            }
            $customerNew = [];
            if ($customer) {
                foreach ($customer as $kfl => $vlfl) {
                    $vlfl['BagPrice'] = round($TotalBG / $TripCount, 2);
                    $vlfl['MealPrice'] = round($TotalML / $TripCount, 2);
                    $vlfl['SeatPrice'] = round($TotalST / $TripCount, 2);
                    $customerNew[$kfl] = $vlfl;
                }
            }

            $FlightBookingDataRiya = array(
                "FlightBookingData" => $FLDataNew,
                "customer" => $customerNew,
                "roominfojson" => $roomjson,
                "Cities" => $oneway_origin_text . '-' . $oneway_destination_text,
                "IsHotelFromApi" => 1,
                "ICSourceSysId" => $ICSourceSysId,
                'AgencySysId' => $MasterAgencySysId,
                'AgentSysId' => $UserSysId,
                "SourcePlaces" => $oneway_origin_text,
                "DestinationPlaces" => $oneway_destination_text,
                "SourcePlaceSysId" => $sourceCityId,
                "DestinationPlacesSysId" => $destinationCityId,
                "BaseAmount" => $BaseFare + $TotalBG + $TotalML + $TotalST,
                "PublishedFare" => $PublishedFare + $TotalBG + $TotalML + $TotalST,
                "AgencyMarkUp" => $AgencyMarkUpINT_,
                "AgencyMarkUpGST" => $AgencyMarkUpGSTINT_,
                "AgentCommisionEarned" => $CommissionEarnedAPI,
                "AgentCommisionEarnedGST" => 0,
                "adults" => $adultCount,
                "childs" => $childCount,
                "infants" => $infantCount,
                "route" => $JourneyType,
                "email" => $email_id,
                "mobile" => $mobileNumber,
                "editLeadId" => $editLeadId,
                "CustomerSysId" => $intCustomerSysId,
                'IsB2BQuery' => $B2BType,
                'B2BAgentSysId' => $UserSysId,
                'B2BAgencySysId' => $AgencySysId,
                'leadsource' => 'Agency',
                'IsB2BProposal' => $B2BType,
                'ExchangeCurrencyRate' => $CurrencyRate,
                'APIMode' => 0,
                'IsNewMigration' => 3,
            );

            if ($isgstapply == 1) {
                $FlightBookingDataRiya['gstData'] = $gstData;
            }
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $URL = $this->baseUrl . '/gtxwebservices/flight-api';

            // echo "<pre>";
            // print_r(($TotalBG . '+' . $TotalML . '+' . $TotalST));
            // echo "<pre>";
            // print_r(($FlightBookingDataRiya));
            // die;
            $GENERATE_FLIGHT_QUERY = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($FlightBookingDataRiya, $getData, $URL);
            $GTXQueryStatus = isset($GENERATE_FLIGHT_QUERY['status']) ? $GENERATE_FLIGHT_QUERY['status'] : false;
            $TPSysId = isset($GENERATE_FLIGHT_QUERY['arrIds']['TPSysId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['TPSysId'] : false;
            // echo "<pre>";
            // print_r(($GENERATE_FLIGHT_QUERY));
            // echo "<pre>";
            // print_r(json_encode($FlightBookingDataRiya));
            // die;
            if ($GTXQueryStatus == 1) {
                $gstData['isgstapply'] = $isgstapply;
                if (!empty($arrUrlData)) {
                    $arrUrlData['FlightBookingData'] = $FlightBooking;
                    $arrUrlData['customer'] = $customer;
                    $arrUrlData['gstData'] = $gstData;
                    $arrUrlData['FARERULE'] = $FARERULE;
                    $arrUrlData['GENERATE_FLIGHT_QUERY'] = $GENERATE_FLIGHT_QUERY;
                    $tempData = array(
                        'TraceId' => $SearchTraceId,
                        'TPSysId' => $TPSysId,
                        'APIBookingData' => json_encode($arrUrlData),
                    );

                    $objFlight->deleteFlightTempData($SearchTraceId);
                    $objFlight->insertFlightTempData($tempData);
                    $response = array(
                        'success' => true,
                        'message' => 'success',
                        'SearchTraceId' => $SearchTraceId,
                        'TPSysId' => $TPSysId,
                    );
                    echo json_encode($response);
                    exit;
                } else {
                    $response = array('success' => false, 'message' => 'record not found');
                    echo json_encode($response);
                    exit;
                }
            } else {
                $response = array('success' => false, 'message' => 'Unable to create query. please contact administrator.',);
                echo json_encode($response);
                exit;
            }
        }
    }

    public function getSelectedAddon($selectedBag, $selectedMeal, $paxType, $BaggageArr, $MealArr) {
        $paxTypeBag = [];
        $paxTypeMeal = [];

        if ($selectedBag) {
            foreach ($selectedBag as $key => $val) {
                $value = strstr($val, '@@', true);
                $valueEXP = explode('_', $value);
                if ($paxType == $valueEXP[0]) {
                    $filterBy = ($valueEXP[1]);
                    $sector = ($valueEXP[2]);
                    $bnew = array_filter($BaggageArr, function ($var) use ($filterBy) {
                        $keyCode = $var['Code'] . '@' . $var['key'];
                        return ($keyCode == $filterBy);
                    });
                    $paxTypeBag[$sector] = array_values($bnew);
                }
            }
        }
        if ($selectedMeal) {
            foreach ($selectedMeal as $key => $val) {
                $value = strstr($val, '@@', true);
                $valueEXP = explode('_', $value);
                if ($paxType == $valueEXP[0]) {
                    $filterBy = ($valueEXP[1]);
                    $sector = ($valueEXP[2]);
                    $new = array_filter($MealArr, function ($var) use ($filterBy) {
                        $keyCode = $var['Code'] . '@' . $var['key'];
                        return ($keyCode == $filterBy);
                    });
                    $paxTypeMeal[$sector] = array_values($new);
                }
            }
        }

        $BagPrice = 0;
        $paxTypeBag_ = [];
        if ($paxTypeBag) {
            foreach ($paxTypeBag as $sec => $val) {
                foreach ($val as $v) {
                    $paxTypeBag_[] = $v;
                    $BagPrice += $v['Price'];
                }
            }
        }
        $MealPrice = 0;
        $paxTypeMeal_ = [];
        if ($paxTypeMeal) {
            foreach ($paxTypeMeal as $sec => $val) {
                foreach ($val as $v) {
                    $paxTypeMeal_[] = $v;
                    $MealPrice += $v['Price'];
                }
            }
        }
        // pr($paxTypeBag_);
        // pr($paxTypeMeal_);
        // die;

        return ['paxTypeBag' => $paxTypeBag, 'paxTypeMeal' => $paxTypeMeal, 'BagPrice' => $BagPrice, 'MealPrice' => $MealPrice];
    }

    public function verifyingBookingAction() {
        if ($this->_request->isXmlHttpRequest()) {
            $post = $this->getRequest()->getPost();
            
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $customHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('Custom');
            $crmcustomerObj = new Travel_Model_CRM_Customer();
            $getAgentDetailById = $crmcustomerObj->getAgentDetailById($this->intLoggedinUserId);
            $getAgencyDetail = $crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);
            $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;
            $objFlight = new Travel_Model_TblFlight();
            $FlightTempData = $objFlight->GetFlightTempData($post['strUrlData']);
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $BookingData = !empty($arrUrlData['FlightBookingData']) ? $arrUrlData['FlightBookingData'] : 0;
            $customer = !empty($arrUrlData['customer']) ? $arrUrlData['customer'] : 0;
            $gstData = isset($arrUrlData['gstData']) ? $arrUrlData['gstData'] : [];
            $intTPSysId = $FlightTempData['TPSysId'];
            $confirm = (isset($post['confirm']) && !empty($post['confirm'])) ? 1 : 0;
            $withprice = (isset($post['withprice']) && !empty($post['withprice'])) ? 1 : 0;
            $isHoldBooking = (isset($post['isHoldBooking']) && !empty($post['isHoldBooking'])) ? 1 : 0;
            $paymentModebyUser = (isset($post['paymentModebyUser']) && !empty($post['paymentModebyUser'])) ? $post['paymentModebyUser'] : 1;
            $travelPlanDetais = $this->_crmcusttravelplan->CheckCustomerWithLeadId($intTPSysId);
            if ($FlightTempData && $BookingData) {


                $IsSeriesFareData = !empty($BookingData[0]['IsSeriesFareData']) ? $BookingData[0]['IsSeriesFareData'] : 0;
                $ICSourceSysId = isset($BookingData[0]['ICSourceSysId']) ? $BookingData[0]['ICSourceSysId'] : 0;
                $sessionFlightSearchParams = !empty($arrUrlData['sessionFlightSearchParams']) ? $arrUrlData['sessionFlightSearchParams'] : [];
                $GENERATE_FLIGHT_QUERY = !empty($arrUrlData['GENERATE_FLIGHT_QUERY']['arrIds']) ? $arrUrlData['GENERATE_FLIGHT_QUERY']['arrIds'] : [];
                $VersionId = !empty($GENERATE_FLIGHT_QUERY['VersionId']) ? $GENERATE_FLIGHT_QUERY['VersionId'] : [];
                $intCustomerSysId = isset($sessionFlightSearchParams['CustomerSysId']) ? $sessionFlightSearchParams['CustomerSysId'] : 0;

                $adultCount = ($sessionFlightSearchParams['adults']);
                $childCount = ($sessionFlightSearchParams['child']);
                $infantCount = ($sessionFlightSearchParams['infant']);
                $JourneyType = ($sessionFlightSearchParams['route']);
                $interNationalSearch = !empty($sessionFlightSearchParams['interNationalSearch']) ? $sessionFlightSearchParams['interNationalSearch'] : 0;
                $intMemberCount = ($adultCount + $childCount + $infantCount);

                $customerDetails = $this->_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;
                
                $BaseFare = 0;
                $Taxesfee = 0;
                $CommDiscount = 0;
                $TotalPay = 0;
                $ServiceFee__ = 0;
                $AirlineTax = 0;
                $FuelSurcharge = 0;
                $GSTOnMarkUp_ = 0;
                $FixedMarkUp_ = 0;
                $CommissionEarned_ = 0;
                $TDSEarn_ = 0;
                if ($BookingData) {
                    foreach ($BookingData as $key => $value) {
                        foreach ($value['FairRules']['FareBreakdown'] as $FareBreakdown) {
                            $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                            $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                            $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                            $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                            $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                            $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                            $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                            $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                            $AirlineTax += ($Tax);
                            $FuelSurcharge += ($YQ);
                            $GSTOnMarkUp_ += ($GSTOnMarkUp);
                            $FixedMarkUp_ += ($FixedMarkUp);
                            $CommissionEarned_ += ($CommissionEarned);
                            $TDSEarn_ += ($TDSEarn);
                        }
                    }
                }
                $BagPrice = 0;
                $MealPrice = 0;
                $SeatPrice = 0;
                foreach ($customer as $kkkk => $ValCustomer) {
                    $BagPrice += !empty($ValCustomer['BagPrice']) ? $ValCustomer['BagPrice'] : 0;
                    $MealPrice += !empty($ValCustomer['MealPrice']) ? $ValCustomer['MealPrice'] : 0;
                    $SeatPrice += !empty($ValCustomer['SeatPrice']) ? $ValCustomer['SeatPrice'] : 0;
                }
                $fare = [
                    'Currency' => isset($FlightBookingData[0]['FairRules']['Currency']) ? trim($FlightBookingData[0]['FairRules']['Currency']) : 'INR',
                    'BaseFare' => round($BaseFare, 2),
                    'Taxesfee' => round($Taxesfee, 2),
                    'CommDiscount' => round($CommDiscount, 2),
                    'CommissionEarned' => round($CommissionEarned_, 2),
                    'TDSEarn' => round($TDSEarn_, 2),
                    'TotalPay' => round($TotalPay + $MealPrice + $BagPrice + $SeatPrice, 2),
                    'AirlineTax' => round($AirlineTax, 2),
                    'FuelSurcharge' => round($FuelSurcharge, 2),
                    'FixedMarkUp' => round($FixedMarkUp_, 2),
                    'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
                    'MealPrice' => $MealPrice,
                    'BagPrice' => $BagPrice,
                    'SeatPrice' => $SeatPrice,
                    'TotalSSR' => ($MealPrice + $BagPrice + $SeatPrice),
                    'TotalProfit' => round(($TDSEarn_ + $CommissionEarned_ + $FixedMarkUp_ + $GSTOnMarkUp_), 2),
                ];
                $TotalExtraMarkupAgency = 0;
                $TotalPublishedFare = $fare['TotalPay'];
                $intChargeFromWallet = $fare['TotalPay'];
                $model = new Gtxwebservices_Model_Webservices();
                if ($IsB2BCustomer == 1 && $paymentModebyUser == 1 && $isHoldBooking == 0) {
                    $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 && $isHoldBooking == 0) {
                    $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 ($ICSourceSysId == 9) {
                    $arrUrlData['withprice'] = $withprice;
                    $arrUrlData['confirm'] = $confirm;
                    $arrUrlData['isHoldBooking'] = $isHoldBooking;
                    $arrUrlData['paymentModebyUser'] = $paymentModebyUser;
                    $tempData = array(
                        'TPSysId' => $intTPSysId,
                        'TraceId' => $post['strUrlData'],
                        'APIBookingData' => json_encode($arrUrlData),
                    );

                    $objFlight->deleteFlightTempData($post['strUrlData']);
                    $objFlight->insertFlightTempData($tempData);
                    $response = array('success' => true, 'checkOTP' => false, 'walletPay' => false, 'trxstatus' => 'success', 'checkpr' => 0, 'PhoneNumberDigit' => '');
                    echo json_encode($response);
                    exit;
                }
                if (isset($post['verifying']) && $post['verifying'] == 'true' && !empty($post['verifying'])) {
                    $getBooingOTP = $objFlight->getBooingOTP($intTPSysId);
                    $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' => $hidePhoneNumberDigit);
                            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 && $IsSeriesFareData == 1) {
                        if ($getBooingOTP == $OTPNumber) {
                            $objFlight->updateBookingStatusTravelPlan(array("CustomerRemark" => ''), $intTPSysId, $travelPlanDetais[0]['MasterTPSysId']);
                            $response = array('success' => true, 'checkOTP' => false, 'walletPay' => false, 'checkpr' => 0, 'PhoneNumberDigit' => $hidePhoneNumberDigit);
                            echo json_encode($response);
                            exit;
                        } else {
                            $response = array('success' => false, 'message' => 'Invalid otp');
                            echo json_encode($response);
                            exit;
                        }
                    } elseif ($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' => $hidePhoneNumberDigit);
                            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' => $hidePhoneNumberDigit);
                            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' => $hidePhoneNumberDigit);
                            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;
                    }
                }

                if ($ICSourceSysId == 30) {
                    $request = array(
                        'Auth_Header' => array(
                            "IP_Address" => $_SERVER['REMOTE_ADDR'],
                            "Request_Id" => $post['strUrlData'],
                            "IMEI_Number" => "3434334343111"
                        )
                    );
                } else {
                    $request = array(
                        "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                        'TokenAgencyId' => '',
                        'TokenMemberId' => '',
                    );
                }

                $DataS = array(
                    'apidata' => $request,
                    'memberCount' => $intMemberCount,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $post['strUrlData'],
                    'ICSourceSysId' => $ICSourceSysId,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                );

                $url = GTX_API_URL . '/flight/v3/getbalnace';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                if ($ICSourceSysId == 8) {
                    $CashBalance = 999999;
                } else {
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $CashBalance = (isset($apiResponse['results']) && !empty($apiResponse['results'])) ? (float) $apiResponse['results'] : 0;
                }


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

                $objFlight->deleteFlightTempData($post['strUrlData']);
                $objFlight->insertFlightTempData($tempData);
                $FlightNonLccArr = [];
                if ($ICSourceSysId == 3 && $isHoldBooking == 0) {
                    if ($BookingData && $CashBalance >= (float) ceil($intChargeFromWallet)) {
                        // $DataS = array(
                        //     'apidata' => [],
                        //     'BookingData' => $BookingData,
                        //     'customer' => $customer,
                        //     'gstData' => $gstData,
                        //     'memberCount' => $intMemberCount,
                        //     'JourneyType' => $JourneyType,
                        //     'interNationalSearch' => $interNationalSearch,
                        //     'searchID' => $post['strUrlData'],
                        //     'ICSourceSysId' => $ICSourceSysId,
                        //     'bookingHold' => $isHoldBooking,
                        //     'AgentMarkUp' => 0,
                        //     'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        // );
                        // // echo (json_encode($DataS));
                        // // die;
                        // $url = GTX_API_URL . '/flight/v3/book';
                        // $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        // $Bookres = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                        // foreach ($BookingData as $k => $value) {
                        //     if (empty($value['IsLCC'])) {
                        //         $AirlineName = $value['AirlineName'];
                        //         $FlightNumber = $value['FlightNumber'];
                        //         $results = isset($Bookres['results'][$k]) ? $Bookres['results'][$k] : [];
                        //         $ResponseStatus = isset($results['Response']['ResponseStatus']) ? $results['Response']['ResponseStatus'] : 0;
                        //         if ($ResponseStatus != 1) {
                        //             $response = array('success' => false, 'checkOTP' => false, 'walletPay' => false, 'message' => 'Unable to book ' . $AirlineName . ' ' . $FlightNumber . ' please choose another flight.');
                        //             echo json_encode($response);
                        //             exit;
                        //         } else {
                        //             $FlightNonLccArr[$k] = $results;
                        //         }
                        //     }
                        // }
                    } elseif ($isHoldBooking == 0) {
                        $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;
                    }
                } elseif ($isHoldBooking == 0) {
                    if ($BookingData && $CashBalance >= (float) ceil($intChargeFromWallet) && $isHoldBooking == 0) {
                        
                    } 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;
                    }
                }

                /* OTP setting */
                $data = new Payment_Model_Checkotp();
                $generateNumericOTP = $this->generateNumericOTP(6);
                $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->intLoggedinAgencyId,
                    "AgentSysId" => $this->intLoggedinUserId,
                    "Title" => $bodyText,
                    "Source" => $arrEmailStatisticsType[1], // 1 For Vouchers
                    "Status" => 0,
                    "RefSysId" => "",
                    "RefSysStatus" => "",
                    "CreateDate" => date('Y-m-d H:i:s')
                );

                $objFlight->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 flight booking is $generateNumericOTP do not share it with anyone. valid for 2 minutes only";
                $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;
                // $resultVal = $data->sendSmsDetails($postURL, $postFields,array('AgencySysId'=>$this->intLoggedinAgencyId));
                // echo '<pre>';
                // print_r($IsAllowFlightBooking);
                // echo '</pre>';
                // echo '<pre>';
                // print_r($IsCheckWallet);
                // echo '</pre>';
                // die;
                if ($IsCheckWallet == 1 && $IsAllowFlightBooking == 1 && $IsSeriesFareData == 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 == 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>';
                // print_r($FlightNonLccArr);
                // echo '</pre>';
                // echo "<pre>";
                // print_r(($post));
                // die;
            }
        }
    }

    public function bookFlightAction() {
        $objFlight = new Travel_Model_TblFlight();
        $strUrlData = $this->view->strUrlData = !empty($this->getRequest()->getParam('strUrlData')) ? $this->getRequest()->getParam('strUrlData') : $this->getRequest()->getParam('data');
        $FlightTempData = $objFlight->GetFlightTempData($strUrlData);
        $this->view->TPSysId = $TPSysId = ($FlightTempData['TPSysId'] > 0) ? $FlightTempData['TPSysId'] : 0;
        $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);

        if ($this->getRequest()->isPost() && $this->_request->isXmlHttpRequest()) {
            /* Disable Layout */
            $this->_helper->layout->disableLayout();
            $post = $this->getRequest()->getPost();
            
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => $TPSysId, 'version' => null];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $CurrentStatus = isset($bookingDataByAPI[0]['CurrentStatus']) ? $bookingDataByAPI[0]['CurrentStatus'] : 0;
            $PaymentStatus = isset($bookingDataByAPI[0]['PaymentStatus']) ? $bookingDataByAPI[0]['PaymentStatus'] : 0;
            if (empty($arrUrlData) || ($CurrentStatus == 142 && $PaymentStatus == 130)) {
                $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;
            }
            
            $strTrxStatus = 'success'; //!empty($this->getRequest()->getParam('trxstatus')) ? $this->getRequest()->getParam('trxstatus') : $post['status'];
            $TrxSysId = $this->getRequest()->getParam('TrxSysId');
            $TPSysId = $this->getRequest()->getParam('TPSysId');
            $guid = $this->getRequest()->getParam('guid');
            $param = $this->getRequest()->getParams();

            if ($strTrxStatus == "success") {
                $strUrlData = $TrackId = $this->getRequest()->getParam('strUrlData');
                $FlightTempData = $objFlight->GetFlightTempData($strUrlData);
                $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
                $sessionFlightSearchParams = $arrUrlData['sessionFlightSearchParams'];
                $CustomerSysIdGTX = isset($arrUrlData['CustomerSysId']) ? $arrUrlData['CustomerSysId'] : 0;
                $adultCount_ = isset($arrUrlData['adultCount']) ? $arrUrlData['adultCount'] : 0;
                $childCount_ = isset($arrUrlData['childCount']) ? $arrUrlData['childCount'] : 0;
                $infantCount_ = isset($arrUrlData['infantCount']) ? $arrUrlData['infantCount'] : 0;
                $isHoldBooking = isset($arrUrlData['isHoldBooking']) ? $arrUrlData['isHoldBooking'] : 0;
                $confirm = isset($arrUrlData['confirm']) ? $arrUrlData['confirm'] : 0;
                $intCustomerSysId = !empty($sessionFlightSearchParams['CustomerSysId']) ? $sessionFlightSearchParams['CustomerSysId'] : $CustomerSysIdGTX;

                // echo "<pre>";
                // print_r(($isHoldBooking));
                // echo "<pre>";
                // print_r(($arrUrlData));
                // die;
                $adultCount = !empty($sessionFlightSearchParams['adults']) ? $sessionFlightSearchParams['adults'] : $adultCount_;
                $childCount = !empty($sessionFlightSearchParams['child']) ? $sessionFlightSearchParams['child'] : $childCount_;
                $infantCount = !empty($sessionFlightSearchParams['infant']) ? $sessionFlightSearchParams['infant'] : $infantCount_;
                $JourneyType = ($sessionFlightSearchParams['route']);
                $interNationalSearch = !empty($sessionFlightSearchParams['interNationalSearch']) ? $sessionFlightSearchParams['interNationalSearch'] : 0;
                $intMemberCount = ($adultCount + $childCount + $infantCount);

                $intTPSysId = $FlightTempData['TPSysId'];
                $paymentModebyUser = (isset($arrUrlData['paymentModebyUser']) && !empty($arrUrlData['paymentModebyUser'])) ? $arrUrlData['paymentModebyUser'] : 1;
                $withprice = (isset($arrUrlData['withprice']) && !empty($arrUrlData['withprice'])) ? $arrUrlData['withprice'] : 0;
                $BookingData = !empty($arrUrlData['FlightBookingData']) ? $arrUrlData['FlightBookingData'] : [];
                $customer = !empty($arrUrlData['customer']) ? $arrUrlData['customer'] : [];
                $gstData = isset($arrUrlData['gstData']) ? $arrUrlData['gstData'] : [];
                $GENERATE_FLIGHT_QUERY = !empty($arrUrlData['GENERATE_FLIGHT_QUERY']['arrIds']) ? $arrUrlData['GENERATE_FLIGHT_QUERY']['arrIds'] : [];
                $checkPaymentStatus = $this->paymentMdl->checkPaymentStatus($this->intLoggedinAgencyId, $intTPSysId);
                
                $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);
                $bookingId = !empty($BookingData[0]['bookingId']) ? $BookingData[0]['bookingId'] : $strUrlData;
                $currencySysId = isset($BookingData[0]['FairRules']['currencySysId']) ? $BookingData[0]['FairRules']['currencySysId'] : $this->CurrencyId;
                   
                $BaseFare = 0;
                $Taxesfee = 0;
                $CommDiscount = 0;
                $TotalPay = 0;
                $ServiceFee__ = 0;
                $AirlineTax = 0;
                $FuelSurcharge = 0;
                $GSTOnMarkUp_ = 0;
                $FixedMarkUp_ = 0;
                $CommissionEarned_ = 0;
                $TDSEarn_ = 0;
                $misxItems_name = [];
                $misxItems_paxwise = [];
                //echo "<pre>";print_r($customer);die;
                $BagPrice = 0;
                $MealPrice = 0;
                $SeatPrice = 0;
                $PaxTypeWiseArray = array();
                foreach ($customer as $kkkk => $ValCustomer) {
                    $PaxTypeWiseArray[$ValCustomer['paxType']][] = $ValCustomer;
                    $BagPrice += !empty($ValCustomer['BagPrice']) ? $ValCustomer['BagPrice'] : 0;
                    $MealPrice += !empty($ValCustomer['MealPrice']) ? $ValCustomer['MealPrice'] : 0;
                    $SeatPrice += !empty($ValCustomer['SeatPrice']) ? $ValCustomer['SeatPrice'] : 0;
                }
                $ARR_SALUTION = unserialize(ARR_SALUTIONTBO);
                
//                echo "<pre>";print_r($PaxTypeWiseArray);
                if ($BookingData) {
                    foreach ($BookingData as $key => $value) {
                        $PublishedFare__ = 0;
                        $GSTOnMarkUp__ = 0;
                        $FixedMarkUp__ = 0;
                        
                        $SourceAirportCode = $value['SourceAirportCode'];
                        $DestAirportCode = $value['DestAirportCode'];
                        $FlightNumber = $value['FlightNumber'];
                        $AirlineName = $value['AirlineName'];
                        $Description = $SourceAirportCode . '-' . $DestAirportCode . '-' . $AirlineName . ' ' . $FlightNumber;
                        $TotalcouponVal = 0;
                        $inc = 0;
                        foreach ($value['FairRules']['FareBreakdown'] as $FareBreakdown) {
                            
                            $PassengerType = isset($FareBreakdown['PassengerType']) ? ($FareBreakdown['PassengerType']) : 0;
                            $PaxType = isset($FareBreakdown['PaxType']) ? ($FareBreakdown['PaxType']) : '';
                            $PassengerCount = isset($FareBreakdown['PassengerCount']) ? ($FareBreakdown['PassengerCount']) : 0;
                            
                            
                            $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                            $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                            $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                            $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                            $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                            $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                            $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                            $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                            $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                            $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                            $AirlineTax += ($Tax);
                            $FuelSurcharge += ($YQ);
                            $GSTOnMarkUp_ += ($GSTOnMarkUp);
                            $FixedMarkUp_ += ($FixedMarkUp);
                            $CommissionEarned_ += ($CommissionEarned);
                            $TDSEarn_ += ($TDSEarn);
                            $PublishedFare__ += ($BaseFare_ + $CommissionEarned + $Tax + $TDSEarn);
//                            $FixedMarkUp__ += ($FixedMarkUp);
//                            $GSTOnMarkUp__ += ($GSTOnMarkUp);
                            
                            $ItemRatesM = $BaseFare_ + $CommissionEarned + $Tax + $TDSEarn;
                            $TotalAmountM = $BaseFare_ + $CommissionEarned + $Tax + $TDSEarn + $FixedMarkUp + $GSTOnMarkUp;
                            $SubTotalM = $TotalAmountM - $GSTOnMarkUp;
                            for($mi= 0; $mi < $PassengerCount; $mi++){
                                 
                                $salutionM = isset($PaxTypeWiseArray[$PassengerType][$mi]['salution']) ? $ARR_SALUTION[(int)$PaxTypeWiseArray[$PassengerType][$mi]['salution']] : '';
                                $FirstNameM = isset($PaxTypeWiseArray[$PassengerType][$mi]['firstname']) ? trim($PaxTypeWiseArray[$PassengerType][$mi]['firstname']) : '';
                                $LastNameM = isset($PaxTypeWiseArray[$PassengerType][$mi]['lastname']) ? trim($PaxTypeWiseArray[$PassengerType][$mi]['lastname']) : '';
                                
                                $misxItems_paxwise[$inc]['AgencySysId'] = $this->intLoggedinAgencyId;
                                $misxItems_paxwise[$inc]['AgentSysId'] = $this->intLoggedinUserId;
                                $misxItems_paxwise[$inc]['MisxItems_name'] = $salutionM.' '.$FirstNameM.' '.$LastNameM.' ('.$PaxType.')';
                                $misxItems_paxwise[$inc]['Description'] .= ($key > 0 ? ', ' : '').$Description;
                                $misxItems_paxwise[$inc]['ItemQty'] = 1;
                                $misxItems_paxwise[$inc]['ItemRates'] += ($ItemRatesM/$PassengerCount);
                                $misxItems_paxwise[$inc]['Total'] += ($ItemRatesM/$PassengerCount);
                                $misxItems_paxwise[$inc]['DiscountType'] = 1;
                                $misxItems_paxwise[$inc]['Discount'] = 0;
                                $misxItems_paxwise[$inc]['TotalDiscount'] += ($TotalcouponVal/$PassengerCount);
                                $misxItems_paxwise[$inc]['TotalAmount'] += ($TotalAmountM/$PassengerCount);
                                $misxItems_paxwise[$inc]['MarkupType'] = '';
                                $misxItems_paxwise[$inc]['Markup'] += ($FixedMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['TotalMarkup'] += ($FixedMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['SubTotal'] += ($SubTotalM/$PassengerCount);
                                $misxItems_paxwise[$inc]['ServiceFeeTotal'] = ($GSTOnMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['GSTPercentage'] = 18;
                                $misxItems_paxwise[$inc]['TotalGST'] += ($GSTOnMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['SGST'] += ($GSTOnMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['CGST'] += ($GSTOnMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['IGST'] += ($GSTOnMarkUp/$PassengerCount);
                                $misxItems_paxwise[$inc]['ItemsSACCode'] = '';
                                $inc++;
                            }
                             
//                            $misxItems_paxwise[$key][$PassengerType] = array(
//                                'AgencySysId' => $this->intLoggedinAgencyId,
//                                'AgentSysId' => $this->intLoggedinUserId,
//                                'MisxItems_name' => 'Flight '.$PaxType,
//                                'Description' => $Description.' '.$PaxType,
//                                'ItemQty' => $PassengerCount,
//                                'ItemRates' => round(($ItemRatesM), 2),
//                                'Total' => round(($ItemRatesM), 2),
//                                'DiscountType' => 1,
//                                'Discount' => 1,
//                                'TotalDiscount' => round(($TotalcouponVal), 2),
//                                'TotalAmount' => round(($TotalAmountM), 2),
//                                'MarkupType' => '',
//                                'Markup' => round(($FixedMarkUp), 2),
//                                'TotalMarkup' => round(($FixedMarkUp), 2),
//                                'SubTotal' => round(($SubTotalM), 2),
//                                'ServiceFeeTotal' => $GSTOnMarkUp,
//                                'GSTPercentage' => '18',
//                                'TotalGST' => round($GSTOnMarkUp, 2),
//                                'SGST' => round((($GSTOnMarkUp / 2)), 2),
//                                'CGST' => round((($GSTOnMarkUp / 2)), 2),
//                                'IGST' => round(($GSTOnMarkUp), 2),
//                                'ItemsSACCode' => '',
//                            ); 
                            
                        }
                        $TotalFare = ($PublishedFare__);
                        $TotalAmount = ($PublishedFare__ + $FixedMarkUp__ + $GSTOnMarkUp__);
                        $TotalGST = $GSTOnMarkUp__;
                        $SubTotal = ($TotalAmount - $GSTOnMarkUp__);
                        
                        
                        $misxItems_name[] = [
                            'AgencySysId' => $this->intLoggedinAgencyId,
                            'AgentSysId' => $this->intLoggedinUserId,
                            'MisxItems_name' => 'Flight',
                            'Description' => $Description,
                            'ItemQty' => 1,
                            'ItemRates' => round(($TotalFare), 2),
                            'Total' => round(($TotalFare), 2),
                            'DiscountType' => 1,
                            'Discount' => 1,
                            'TotalDiscount' => round(($TotalcouponVal), 2),
                            'TotalAmount' => round(($TotalAmount), 2),
                            'MarkupType' => '',
                            'Markup' => round(($FixedMarkUp__), 2),
                            'TotalMarkup' => round(($FixedMarkUp__), 2),
                            'SubTotal' => round(($SubTotal), 2),
                            'ServiceFeeTotal' => $TotalGST,
                            'GSTPercentage' => '18',
                            'TotalGST' => round($TotalGST, 2),
                            'SGST' => round((($TotalGST / 2)), 2),
                            'CGST' => round((($TotalGST / 2)), 2),
                            'IGST' => round(($TotalGST), 2),
                            'ItemsSACCode' => '',
                        ];
                    }
                }
//                echo "<pre>";print_r($misxItems_name);
//                echo "<pre>";print_r($misxItems_paxwise);die;
                
                $fare = [
                    'Currency' => isset($FlightBookingData[0]['FairRules']['Currency']) ? trim($FlightBookingData[0]['FairRules']['Currency']) : 'INR',
                    'BaseFare' => round($BaseFare, 2),
                    'Taxesfee' => round($Taxesfee, 2),
                    'CommDiscount' => round($CommDiscount, 2),
                    'CommissionEarned' => round($CommissionEarned_, 2),
                    'TDSEarn' => round($TDSEarn_, 2),
                    'TotalPay' => round($TotalPay, 2),
                    'AirlineTax' => round($AirlineTax, 2),
                    'FuelSurcharge' => round($FuelSurcharge, 2),
                    'FixedMarkUp' => round($FixedMarkUp_, 2),
                    'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
                    'MealPrice' => $MealPrice,
                    'BagPrice' => $BagPrice,
                    'SeatPrice' => $SeatPrice,
                    'TotalSSR' => ($MealPrice + $BagPrice + $SeatPrice),
                    'TotalProfit' => round(($TDSEarn_ + $CommissionEarned_ + $FixedMarkUp_ + $GSTOnMarkUp_), 2),
                ];
                $customerDetails = $this->_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['TotalPay'] + $fare['MealPrice'] + $fare['BagPrice'] + $fare['SeatPrice']);
                $B2BWalletbalance = $PublishedFare;

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

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

                    $URL_ = $this->baseUrl . '/webservice/credit-balance/update-credit-balance-for-offline-request/';
                    $updateCreditBalance = array(
                        'B2BAgencySysIdKey' => $B2BAgencySysIdKey,
                        'B2CAgencySysIdKey' => $B2CAgencySysIdKey,
                        'Remark' => 'Flight Booking ',
                        'Amount' => $B2BWalletbalance,
                        'PlanType' => 1, // for flight
                        '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__);
                    $TransactionId = isset($updateBalance['TransactionId']) ? $updateBalance['TransactionId'] : 0;

                    // echo '<pre>';
                    // print_r(($updateBalance));
                } elseif ($IsEnabledWallet == 1 && $paymentModebyUser == 1 && $isHoldBooking == 0) {
                    $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' => 'Flight Booking ',
                                'Amount' => $PublishedFare,
                                'CustomerSysId' => $CustomerSysId,
                                'PlanType' => 1,
                                '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;
                            if(!empty($TransactionId)){
                                $checkPaymentStatus = 1;
                            }
                        } 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;
                        }
                    }
                }

                $MasterTPSysId = !empty($GENERATE_FLIGHT_QUERY['MasterTPSysId']) ? $GENERATE_FLIGHT_QUERY['MasterTPSysId'] : 0;
                $CustomerSysIdGTX = !empty($GENERATE_FLIGHT_QUERY['CustomerSysId']) ? $GENERATE_FLIGHT_QUERY['CustomerSysId'] : 0;
                $TrxId = !empty($GENERATE_FLIGHT_QUERY['TrxId']) ? $GENERATE_FLIGHT_QUERY['TrxId'] : 0;
                $TPSysId = !empty($GENERATE_FLIGHT_QUERY['TPSysId']) ? $GENERATE_FLIGHT_QUERY['TPSysId'] : 0;
                $VersionId = !empty($GENERATE_FLIGHT_QUERY['VersionId']) ? $GENERATE_FLIGHT_QUERY['VersionId'] : [];
                $GstNumber = !empty($customer[0]['GstNumber']) ? $customer[0]['GstNumber'] : '';
                $isgstapply = !empty($customer[0]['isgstapply']) ? $customer[0]['isgstapply'] : 0;
                $ServiceTaxNo = $this->agencyDetails['ServiceTaxNo'];
                $gstvalidate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->gstvalidate($GstNumber, $ServiceTaxNo);
                
                $itemCount = count($misxItems_name);
                if (!empty($BagPrice)) {
                    $misxItems_name[$itemCount] = array(
                        'MisxItems_name' => 'Add ons',
                        'Description' => 'Baggage',
                        'ItemQty' => 1,
                        'ItemRates' => ($BagPrice),
                        'Total' => $BagPrice,
                        'DiscountType' => 0,
                        'Discount' => 0,
                        'TotalDiscount' => 0,
                        'TotalAmount' => 0,
                        'MarkupType' => '',
                        'Markup' => 0,
                        'TotalMarkup' => 0,
                        'SubTotal' => $BagPrice,
                        'ServiceFeeTotal' => 0,
                        'GSTPercentage' => 0,
                        'TotalGST' => 0,
                        'SGST' => 0,
                        'CGST' => 0,
                        'IGST' => 0,
                        'ItemsSACCode' => '',
                    );
                }
                $itemCount = count($misxItems_name);
                if (!empty($MealPrice)) {
                    $misxItems_name[$itemCount] = array(
                        'MisxItems_name' => 'Add ons',
                        'Description' => 'Meal',
                        'ItemQty' => 1,
                        'ItemRates' => ($MealPrice),
                        'Total' => $MealPrice,
                        'DiscountType' => 0,
                        'Discount' => 0,
                        'TotalDiscount' => 0,
                        'TotalAmount' => 0,
                        'MarkupType' => '',
                        'Markup' => 0,
                        'TotalMarkup' => 0,
                        'SubTotal' => $MealPrice,
                        'ServiceFeeTotal' => 0,
                        'GSTPercentage' => 0,
                        'TotalGST' => 0,
                        'SGST' => 0,
                        'CGST' => 0,
                        'IGST' => 0,
                        'ItemsSACCode' => '',
                    );
                }
                $itemCount = count($misxItems_name);
                if (!empty($SeatPrice)) {
                    $misxItems_name[$itemCount] = array(
                        'MisxItems_name' => 'Add ons',
                        'Description' => 'Seat',
                        'ItemQty' => 1,
                        'ItemRates' => ($SeatPrice),
                        'Total' => $SeatPrice,
                        'DiscountType' => 0,
                        'Discount' => 0,
                        'TotalDiscount' => 0,
                        'TotalAmount' => 0,
                        'MarkupType' => '',
                        'Markup' => 0,
                        'TotalMarkup' => 0,
                        'SubTotal' => $SeatPrice,
                        'ServiceFeeTotal' => 0,
                        'GSTPercentage' => 0,
                        'TotalGST' => 0,
                        'SGST' => 0,
                        'CGST' => 0,
                        'IGST' => 0,
                        'ItemsSACCode' => '',
                    );
                }
                $TotalInvoiceValue = ($fare['TotalPay'] + $fare['MealPrice'] + $fare['BagPrice'] + $fare['SeatPrice'] - $fare['GSTOnMarkUp']);
                $PublishedFare = ($fare['TotalPay'] + $fare['MealPrice'] + $fare['BagPrice'] + $fare['SeatPrice']);
                $agencyMarkUpGST = ($fare['GSTOnMarkUp']);
                $TotalDiscount = 0;
                $Invoicedata = [
                    'AgentSysId' => $this->intLoggedinUserId,
                    'CustomerSysId' => $intCustomerSysId,
                    'TPSysId' => $intTPSysId,
                    'MasterTPSysId' => $MasterTPSysId,
                    'ProposalID' => $intTPSysId . '/V1',
                    'InvoiceDate' => date('Y-m-d'),
                    'isDisplayMarkup' => true,
                    'PaymentDueDate' => date('Y-m-d'),
                    'PaymentDate' => date('Y-m-d'),
                    'ClientGST' => $isgstapply,
                    'ClientGSTNumber' => $GstNumber,
                    'Currency' => $currencySysId,
                    'TotalInvoiceValue' => round(($TotalInvoiceValue), 2),
                    'InvoiceStatus' => ($checkPaymentStatus == 1) ? 1 : 5,
                    'TotalSGST' => ($gstvalidate['SGST'] == 1) ? round((($agencyMarkUpGST / 2)), 2) : 0,
                    'TotalCGST' => ($gstvalidate['CGST'] == 1) ? round((($agencyMarkUpGST / 2)), 2) : 0,
                    'TotalIGST' => ($gstvalidate['IGST'] == 1) ? round(($agencyMarkUpGST), 2) : 0,
                    'SumdiscountItem' => 0,
                    'OtherDiscount' => round(($TotalDiscount), 2),
                    'otherDiscountVal' => round(($TotalDiscount), 2),
                    'TotalAdvance' => ($checkPaymentStatus == 1) ? round(($PublishedFare), 2) : 0,
                    'TotalDueAmount' => ($checkPaymentStatus == 1) ? 0 : round(($PublishedFare), 2),
                    'InvoiceValue' => round(($PublishedFare), 2),
                    'notes' => 'Flight Ticket',
                    'termsandcondition' => '',
                    'client_state' => '',
                    'Advance' => 0,
                    'PaymentType' => 4,
                    'paymentNote' => 'Online',
                    'misxItems_name' => $misxItems_name,
                    'misxItems_paxwise' => $misxItems_paxwise,
                ];
                $IsSeriesFareData = isset($BookingData[0]['IsSeriesFareData']) ? $BookingData[0]['IsSeriesFareData'] : 0;
                $ICSourceSysId = isset($BookingData[0]['ICSourceSysId']) ? $BookingData[0]['ICSourceSysId'] : 0;

                $APIBookingresponse = [];
                $GTXUpdateresponse = [];
                $Bookres = [];

                if ($ICSourceSysId == 30) {
                    $request = array(
                        'Auth_Header' => array(
                            "IP_Address" => $_SERVER['REMOTE_ADDR'],
                            "Request_Id" => $post['strUrlData'],
                            "IMEI_Number" => "3434334343111"
                        )
                    );
                } else {
                    $request = array(
                        "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                        'TokenAgencyId' => '',
                        'TokenMemberId' => '',
                    );
                }
                $DataS = array(
                    'apidata' => $request,
                    'memberCount' => $intMemberCount,
                    'JourneyType' => $JourneyType,
                    'interNationalSearch' => $interNationalSearch,
                    'searchID' => $post['strUrlData'],
                    'ICSourceSysId' => $ICSourceSysId,
                    'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                );
                $url = GTX_API_URL . '/flight/v3/getbalnace';
                $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                if ($ICSourceSysId == 8 || $ICSourceSysId == 9) {
                    $CashBalance = 999999;
                } else {
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $CashBalance = (isset($apiResponse['results']) && !empty($apiResponse['results'])) ? (float) $apiResponse['results'] : 0;
                }
                
                if ($BookingData && $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;
                }

                if ($ICSourceSysId == 8) {
                    $DataS = array(
                        'apidata' => [],
                        'BookingData' => $BookingData,
                        'customer' => $customer,
                        'gstData' => $gstData,
                        'memberCount' => $intMemberCount,
                        'JourneyType' => $JourneyType,
                        'interNationalSearch' => $interNationalSearch,
                        'searchID' => $post['strUrlData'],
                        'ICSourceSysId' => $ICSourceSysId,
                        'bookingHold' => $isHoldBooking,
                        'AgentMarkUp' => 0,
                        'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                    );

                    $url = GTX_API_URL . '/flight/v3/ticketing';
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    //$apiResponse = json_decode('{"status":true,"message":"SUCCESS","results":[{"FlightNumber":"SG-42563","SegFlightNumberArr":"SG-42563","AirlineName":"Spicejet","AirlineCode":"SG","IsLCC":true,"IsRefundable":"1","OnwardAutoTicket":"0","InwardAutoTicket":0,"IsRefundableTxt":"Refundable","SearchTraceId":"GTX000000008600","SearchFlightTraceId":"GTX000000008600","ApiResultIndex":"","DepartureTime":"02:00","ArrivalTime":"04:00","FromUTCTime":"2024-12-10 02:00","ToUTCTime":"2024-12-10 04:00:00","FareClass":"Economy","FlightDuration":"2h ","SourceAirportCode":"BOM","DestAirportCode":"DEL","StopCount":"Non-stop","NoOfSeatAvailable":96,"PublishedFare":3220,"JourneyType":2,"TripType":1,"IsInternational":0,"ICSourceSysId":8,"logo":"https://gtxapi.hellogtx.com/public/AirlineLogo/SG.png","FairRules":{"Currency":"INR","CurrencyRate":1,"currencySysId":1,"BaseFare":3000,"Tax":200,"intPublishedFare":3220,"PublishedFare":3220,"PublishedFareAgent":3220,"PublishedFarePerPax":1073,"CommDiscount":0,"TDS":0,"TDSEarn":0,"fareremarks":"","colors":"","IscheckinBagInc":true,"IscabinbagInc":true,"CheckinBaggage":"4KG","CabinBaggage":"4KG","IsMealIncludes":false,"IsSpecialReturn":false,"OfferedFare":3220,"OnwardAutoTicket":"0","Refundable":"1","IsRefundableTxt":"Refundable","PriceID":"2191_26240","fareIdentifier":"SPECIAL DEALS","SeatAvailable":"96","classOfBooking":"","FareClass":"Economy","FixedMarkUp":20,"GSTOnMarkUp":0,"CommissionEarned":0,"AgentMarkUp":0,"FareBreakdown":[{"Currency":"INR","PassengerType":1,"PassengerCount":"1","PaxType":"ADULT","Tax":100,"BaseFare":1500,"PublishedFare":1610,"OfferedFare":1500,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":100,"MU":0,"YR":0},"FixedMarkUp":10,"GSTOnMarkUp":0,"TDSEarn":0,"TDS":0,"ApiNCM":0,"CommDiscount":0,"Baggage":"4KG","CabinBaggage":"4KG"},{"Currency":"INR","PassengerType":2,"PaxType":"CHILD","PassengerCount":"1","BaseFare":1500,"OfferedFare":1500,"PublishedFare":1610,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":100,"MU":0,"YR":0},"FixedMarkUp":10,"GSTOnMarkUp":0,"Tax":100,"TDSEarn":0,"TDS":0,"ApiNCM":0,"CommDiscount":0,"Baggage":"4KG","CabinBaggage":"4KG"},{"Currency":"INR","PassengerType":3,"PaxType":"INFANT","PassengerCount":"1","BaseFare":0,"OfferedFare":0,"PublishedFare":0,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":0,"MU":0,"YR":0},"FixedMarkUp":0,"GSTOnMarkUp":0,"TDSEarn":0,"Tax":100,"ApiNCM":0,"TDS":0,"CommDiscount":0,"Baggage":"4KG","CabinBaggage":"4KG"}],"OnwardGroupPNR":"","InwardGroupPNR":"","OnwardGroupPNRDummy":"HGYFJK","tripbinfo":{"BOM-DEL":{"ADULT":{"cabin":"4KG","checkin":"4KG"}}}},"Segments":[{"segmentid":"","isReturnSegment":false,"destinationAirportCode":"DEL","SegFlightNumber":"SG-42563","AirlineCode":"SG","AirlineName":"SpiceJet","originAirportCode":"BOM","IscabinbagInc":true,"NoOfSeatAvailable":"96","strDepartureDtTime":"02:00","strArrivalDtTime":"04:00","FlightDuration":"02 hours 00 minute","filePath":"https://gtxapi.hellogtx.com/public/AirlineLogo/SG.png","originAirportName":" Chhatrapati Shivaji (BOM), India","destinationAirportName":" Delhi Indira Gandhi Intl (DEL), India","originCityName":"Mumbai","originCountryName":"India","destinationCityName":"Delhi","destinationCountryName":"India","destinationArrTime":"2024-12-10 04:00","FareClass":"Economy","originDepTime":"2024-12-10 02:00","TripIndicator":"","Duration":120,"GroundTime":0,"LAYOVERDuration":null,"LAYOVERCity":"","DepTerminal":"","ArrTerminal":"","arrivingnextday":"","cabinClass":"Economy","IscheckinBagInc":true,"CheckinBaggage":"4KG","CabinBaggage":"4KG","IsMealIncludes":false}],"FareRules":"","CancellationPolicy":"","InternalRemarks":"","FilterDepartureDtTime":"00:00-10:00","FilterArrivalDtTime":"00:00-10:00","OnwardGroupPNR":"","InwardGroupPNR":"","OnwardGroupPNRDummy":"HGYFJK","IsSeriesFareData":true,"SupplierSysId":"11952","isDobAdult":false,"isDobChild":false,"isDobInfant":true,"Ispassengercity":false,"Ispassengeraddress":false,"isGSTMandatory":false,"IsPassMandatory":false,"IsPassExpiry":false,"IsPassIssue":false,"IsPassDateOfBirth":false,"isHoldAllowed":false,"ResponseStatus":true,"ErrorMessage":"Inventory Sold","bookingId":"GTX000000008600","APIBookingId":"419DBB52D41947B6A4CE97DA98BFC616"},{"FlightNumber":"6E-85692","SegFlightNumberArr":"6E-85692","AirlineName":"Indigo","AirlineCode":"6E","IsLCC":true,"IsRefundable":"1","OnwardAutoTicket":"1","InwardAutoTicket":0,"IsRefundableTxt":"Refundable","SearchTraceId":"GTX000000008600","SearchFlightTraceId":"GTX000000008600","ApiResultIndex":"","DepartureTime":"01:00","ArrivalTime":"03:00","FromUTCTime":"2024-12-15 01:00","ToUTCTime":"2024-12-15 03:00:00","FareClass":"Economy","FlightDuration":"2h ","SourceAirportCode":"DEL","DestAirportCode":"BOM","StopCount":"Non-stop","NoOfSeatAvailable":98,"PublishedFare":2220,"JourneyType":2,"TripType":1,"IsInternational":0,"ICSourceSysId":8,"logo":"https://gtxapi.hellogtx.com/public/AirlineLogo/6E.png","FairRules":{"Currency":"INR","CurrencyRate":1,"currencySysId":1,"BaseFare":2000,"Tax":200,"intPublishedFare":2220,"PublishedFare":2220,"PublishedFareAgent":2220,"PublishedFarePerPax":740,"CommDiscount":0,"TDS":0,"TDSEarn":0,"fareremarks":"","colors":"","IscheckinBagInc":true,"IscabinbagInc":true,"CheckinBaggage":"5kg","CabinBaggage":"4kg","IsMealIncludes":false,"IsSpecialReturn":false,"OfferedFare":2220,"OnwardAutoTicket":"1","Refundable":"1","IsRefundableTxt":"Refundable","PriceID":"2190_26239","fareIdentifier":"SPECIAL DEALS","SeatAvailable":"98","classOfBooking":"","FareClass":"Economy","FixedMarkUp":20,"GSTOnMarkUp":0,"CommissionEarned":0,"AgentMarkUp":0,"FareBreakdown":[{"Currency":"INR","PassengerType":1,"PassengerCount":"1","PaxType":"ADULT","Tax":100,"BaseFare":1000,"PublishedFare":1110,"OfferedFare":1000,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":100,"MU":0,"YR":0},"FixedMarkUp":10,"GSTOnMarkUp":0,"TDSEarn":0,"TDS":0,"ApiNCM":0,"CommDiscount":0,"Baggage":"5kg","CabinBaggage":"4kg"},{"Currency":"INR","PassengerType":2,"PaxType":"CHILD","PassengerCount":"1","BaseFare":1000,"OfferedFare":1000,"PublishedFare":1110,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":100,"MU":0,"YR":0},"FixedMarkUp":10,"GSTOnMarkUp":0,"Tax":100,"TDSEarn":0,"TDS":0,"ApiNCM":0,"CommDiscount":0,"Baggage":"5kg","CabinBaggage":"4kg"},{"Currency":"INR","PassengerType":3,"PaxType":"INFANT","PassengerCount":"1","BaseFare":0,"OfferedFare":0,"PublishedFare":0,"CommissionEarned":0,"TaxBR":{"TDS":0,"MF":0,"YQ":0,"AGST":0,"MFT":0,"OT":0,"MU":0,"YR":0},"FixedMarkUp":0,"GSTOnMarkUp":0,"TDSEarn":0,"Tax":100,"ApiNCM":0,"TDS":0,"CommDiscount":0,"Baggage":"5kg","CabinBaggage":"4kg"}],"OnwardGroupPNR":"QAHGYT","InwardGroupPNR":"","OnwardGroupPNRDummy":"QAHGYT","tripbinfo":{"DEL-BOM":{"ADULT":{"cabin":"4kg","checkin":"5kg"}}}},"Segments":[{"segmentid":"","isReturnSegment":false,"destinationAirportCode":"BOM","SegFlightNumber":"6E-85692","AirlineCode":"6E","AirlineName":"IndiGo","originAirportCode":"DEL","IscabinbagInc":true,"NoOfSeatAvailable":"98","strDepartureDtTime":"01:00","strArrivalDtTime":"03:00","FlightDuration":"02 hours 00 minute","filePath":"https://gtxapi.hellogtx.com/public/AirlineLogo/6E.png","originAirportName":" Delhi Indira Gandhi Intl (DEL), India","destinationAirportName":" Chhatrapati Shivaji (BOM), India","originCityName":"Delhi","originCountryName":"India","destinationCityName":"Mumbai","destinationCountryName":"India","destinationArrTime":"2024-12-15 03:00","FareClass":"Economy","originDepTime":"2024-12-15 01:00","TripIndicator":"","Duration":120,"GroundTime":0,"LAYOVERDuration":null,"LAYOVERCity":"","DepTerminal":"3","ArrTerminal":"2","arrivingnextday":"","cabinClass":"Economy","IscheckinBagInc":true,"CheckinBaggage":"5kg","CabinBaggage":"4kg","IsMealIncludes":false}],"FareRules":"","CancellationPolicy":"","InternalRemarks":"","FilterDepartureDtTime":"00:00-10:00","FilterArrivalDtTime":"00:00-10:00","OnwardGroupPNR":"QAHGYT","InwardGroupPNR":"","OnwardGroupPNRDummy":"QAHGYT","IsSeriesFareData":true,"SupplierSysId":"11952","isDobAdult":false,"isDobChild":false,"isDobInfant":true,"Ispassengercity":false,"Ispassengeraddress":false,"isGSTMandatory":false,"IsPassMandatory":false,"IsPassExpiry":false,"IsPassIssue":false,"IsPassDateOfBirth":false,"isHoldAllowed":false,"ResponseStatus":true,"ErrorMessage":"Inventory Sold","bookingId":"GTX000000008600","APIBookingId":"EFD60F24FFE648BF833721B71722D869"}],"Invoicedata":{"AgentSysId":0,"CustomerSysId":0,"TPSysId":0,"MasterTPSysId":0,"ProposalID":"0/V1","InvoiceDate":"2024-12-03","isDisplayMarkup":true,"PaymentDueDate":"2024-12-03","PaymentDate":"2024-12-03","ClientGST":0,"ClientGSTNumber":"","Currency":1,"TotalInvoiceValue":5640,"InvoiceStatus":1,"TotalSGST":0,"TotalCGST":0,"TotalIGST":0,"SumdiscountItem":0,"OtherDiscount":0,"otherDiscountVal":0,"TotalAdvance":5640,"TotalDueAmount":5640,"InvoiceValue":5640,"notes":"Flight Ticket","termsandcondition":"","client_state":"","Advance":0,"PaymentType":4,"paymentNote":"Online","misxItems_name":[{"AgencySysId":1,"AgentSysId":0,"MisxItems_name":"Flight","Description":"BOM-DEL-Spicejet SG-42563","ItemQty":1,"ItemRates":3300,"Total":3300,"DiscountType":1,"Discount":1,"TotalDiscount":0,"TotalAmount":3320,"MarkupType":"","Markup":20,"TotalMarkup":20,"SubTotal":3320,"ServiceFeeTotal":0,"GSTPercentage":"18","TotalGST":0,"SGST":0,"CGST":0,"IGST":0,"ItemsSACCode":""},{"AgencySysId":1,"AgentSysId":0,"MisxItems_name":"Flight","Description":"DEL-BOM-Indigo 6E-85692","ItemQty":1,"ItemRates":2300,"Total":2300,"DiscountType":1,"Discount":1,"TotalDiscount":0,"TotalAmount":2320,"MarkupType":"","Markup":20,"TotalMarkup":20,"SubTotal":2320,"ServiceFeeTotal":0,"GSTPercentage":"18","TotalGST":0,"SGST":0,"CGST":0,"IGST":0,"ItemsSACCode":""}]}}', 1);
                    // echo (json_encode($apiResponse));
                    // die('ddd');
                    $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                    $ErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                    $BookingData = isset($apiResponse['results']) ? $apiResponse['results'] : [];
                    $BookStatus = $ResponseStatus;
                    $Bookres = $apiResponse;
                } else if ($ICSourceSysId == 3) {
                    if ($BookingData && $CashBalance >= (float) ceil($PublishedFare)) {
                        $DataS = array(
                            'apidata' => [],
                            'BookingData' => $BookingData,
                            'customer' => $customer,
                            'memberCount' => $intMemberCount,
                            'JourneyType' => $JourneyType,
                            'interNationalSearch' => $interNationalSearch,
                            'searchID' => $post['strUrlData'],
                            'ICSourceSysId' => $ICSourceSysId,
                            'bookingHold' => $isHoldBooking,
                            'AgentMarkUp' => 0,
                            'gstData' => $gstData,
                            'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        );
                        // echo (json_encode($DataS));
                        // die('ddd');
                        if ($confirm == 1) {
                            $url = GTX_API_URL . '/flight/v3/holdissue';
                        } else {
                            $url = GTX_API_URL . '/flight/v3/book';
                        }
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                        // echo (json_encode($apiResponse));
                        // die('ddd');
                        $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                        $ErrorMessage = $BookErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                        $BookStatus = isset($apiResponse['results']['status']['success']) ? $apiResponse['results']['status']['success'] : false;
                        $Bookres = $apiResponse;
                        if ($ResponseStatus == 1) {
                            $url = GTX_API_URL . '/flight/v3/ticketing';
                            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                            if ($confirm == 0) {
                                $Bookres = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                            }
                            $ErrorMessage = isset($Bookres['message']) ? $Bookres['message'] : '';
                            $ErrorCode = isset($Bookres['ErrorCode']) ? $Bookres['ErrorCode'] : '';

                            foreach ($BookingData as $k => $value) {
                                if ($confirm == 1) {
                                    $response = isset($Bookres['postField'][$k]) ? $Bookres['postField'][$k] : [];
                                } else {
                                    $response = isset($Bookres['results'][$k]) ? $Bookres['results'][$k] : [];
                                }
                                $APIBookingresponse[] = $response;
                                $IsBookingStatus = isset($response['IsBookingStatus']) ? $response['IsBookingStatus'] : 0;
                                if ($IsBookingStatus == 1) {
                                    if ($k == 0 && $isHoldBooking == 0) {
                                        $InvoiceCreate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->InvoiceCreate($Invoicedata, $BookingData, $this->agencyDetails['SecurityKey'], $this->intLoggedinAgencyId);
//                                        echo "<pre>";print_r($InvoiceCreate);die;
                                    }
                                    $response['PublishedFare'] = $PublishedFare;
                                    $response['MasterTPSysId'] = $MasterTPSysId;
                                    $response['TPSysId'] = $TPSysId;
                                    $response['TrxId'] = $TrxId;
                                    $response['VersionId'] = $VersionId[$k];
                                    if($paymentModebyUser == 2){
                                        $response['IsPayLater'] = 1;
                                        $response['flexiPayment'] = 1;
                                        $response['flexiAmount'] = 0;
                                    }
                                    $URL = $this->baseUrl . "/gtxwebservices/flight-api/updatebooking";
                                    $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($response, $getData, $URL);
                                } else {
                                    $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 && $isHoldBooking == 0) {
                                $dataArray = array(
                                    'B2BAgencySysIdKey' => $B2CAgencySysIdKey,
                                    'B2CAgencySysIdKey' => $B2BAgencySysIdKey,
                                    'PaymentMode' => 'Wallet Refund',
                                    'Amount' => $B2BWalletbalance,
                                    'RefrenceNo' => $bookingId,
                                    'CreditDate' => date('Y-m-d'),
                                    'Remark' => 'Refund',
                                    'PlanType' => 7,
                                    '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 && $isHoldBooking == 0) {
                                $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;
                            // $response = array('success' => false, 'TrackId' => base64_encode($TPSysId), 'msg' => $message);
                            // echo json_encode($response);
                            // exit;
                        }

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

                        $objFlight->deleteFlightTempData($post['strUrlData']);
                        $objFlight->insertFlightTempData($tempData);
                        $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => $ErrorMessage, 'urlData' => $strUrlData, 'formAction' => "/flight-new/booking-confirmation/data/" . $TrackId . "?status=true");
                        echo json_encode($response);
                        exit;
                        // $DataS = array(
                        //     'apidata' => [],
                        //     'BookingData' => $BookingData,
                        //     'customer' => $customer,
                        //     'gstData' => $gstData,
                        //     'memberCount' => $intMemberCount,
                        //     'JourneyType' => $JourneyType,
                        //     'interNationalSearch' => $interNationalSearch,
                        //     'searchID' => $post['strUrlData'],
                        //     'ICSourceSysId' => $ICSourceSysId,
                        //     'bookingHold' => $isHoldBooking,
                        //     'AgentMarkUp' => 0,
                        //     'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        // );
                        // echo '<pre>';
                        // print_r(($DataS));
                        // $url = GTX_API_URL . '/flight/v3/ticketing';
                        // $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        // $Bookres = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                        // $ErrorMessage = isset($Bookres['message']) ? $Bookres['message'] : '';
                        // foreach ($BookingData as $k => $value) {
                        //     $response = isset($Bookres['results'][$k]) ? $Bookres['results'][$k] : [];
                        //     $APIBookingresponse[] = $response;
                        //     $IsBookingStatus = isset($response['IsBookingStatus']) ? $response['IsBookingStatus'] : 0;
                        //     if ($IsBookingStatus == 1) {
                        //         if ($k == 0) {
                        //             $InvoiceCreate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->InvoiceCreate($Invoicedata, $BookingData, $this->agencyDetails['SecurityKey'], $this->intLoggedinAgencyId);
                        //         }
                        //         $response['PublishedFare'] = $PublishedFare;
                        //         $response['MasterTPSysId'] = $MasterTPSysId;
                        //         $response['TPSysId'] = $TPSysId;
                        //         $response['TrxId'] = $TrxId;
                        //         $response['VersionId'] = $VersionId[$k];
                        //         // echo '<pre>';
                        //         // print_r(($response));
                        //         $URL = $this->baseUrl . "/gtxwebservices/flight-api/updatebooking";
                        //         $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($response, $getData, $URL);
                        //     } else {
                        //         $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 ($ICSourceSysId == 9) {
                    $ResponseStatus = true;
                    $ErrorMessage = 'Offline';
                    $BookStatus = true;
                    $Bookres = [];
                } else {
                    if ($BookingData && $CashBalance >= (float) ceil($PublishedFare)) {
                        $DataS = array(
                            'apidata' => [],
                            'BookingData' => $BookingData,
                            'customer' => $customer,
                            'memberCount' => $intMemberCount,
                            'JourneyType' => $JourneyType,
                            'interNationalSearch' => $interNationalSearch,
                            'searchID' => $post['strUrlData'],
                            'ICSourceSysId' => $ICSourceSysId,
                            'bookingHold' => $isHoldBooking,
                            'AgentMarkUp' => 0,
                            'gstData' => $gstData,
                            'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                        );
                        // echo (json_encode($DataS));
                        // die('ddd');
                        if ($confirm == 1) {
                            $url = GTX_API_URL . '/flight/v3/holdissue';
                        } else {
                            $url = GTX_API_URL . '/flight/v3/book';
                        }
                        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                        $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                        // echo (json_encode($apiResponse));
                        // echo '<pre>';
                        // print_r($apiResponse);
                        // die;
                        $ResponseStatus = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                        $ErrorMessage = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                        $InvoicedataApi = isset($apiResponse['Invoicedata']) ? $apiResponse['Invoicedata'] : '';
                        $BookStatus = isset($apiResponse['results']['status']['success']) ? $apiResponse['results']['status']['success'] : false;
                        $Bookres = $apiResponse;
                    }
                }
                if ($ResponseStatus == 1) {
                    // $InvoicedataApi['AgentSysId'] = $this->intLoggedinUserId;
                    // $InvoicedataApi['CustomerSysId'] = $CustomerSysIdGTX;
                    // $InvoicedataApi['TPSysId'] = $TPSysId;
                    // $InvoicedataApi['MasterTPSysId'] = $MasterTPSysId;
                    // $InvoicedataApi['ProposalID'] = $TPSysId . '/V1';
                    $requestDetail = [];
                    //$APIbookingId = isset($BookingData[0]['APIBookingId']) ? $BookingData[0]['APIBookingId'] : '';
                    // if ($ICSourceSysId == 7) {
                    //     $requestDetail = array(
                    //         'bookingId' => $APIbookingId
                    //     );
                    // }
                    $DataS = array(
                        'apidata' => $requestDetail,
                        'BookingData' => $BookingData,
                        'customer' => $customer,
                        'memberCount' => $intMemberCount,
                        'JourneyType' => $JourneyType,
                        'interNationalSearch' => $interNationalSearch,
                        'searchID' => $post['strUrlData'],
                        'ICSourceSysId' => $ICSourceSysId,
                        'bookingHold' => $isHoldBooking,
                        'AgentMarkUp' => 0,
                        'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0
                    );
//                    echo "<pre>";print_r($customer);die;
                    // die('ddd');
                    $url = GTX_API_URL . '/flight/v3/reprint';
                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
                    $APIBookingresponse = $apiResponse;
                     
                    $status = isset($apiResponse['status']) ? $apiResponse['status'] : false;
                    $message = isset($apiResponse['message']) ? $apiResponse['message'] : '';
                    $response = isset($apiResponse['results']) ? $apiResponse['results'] : [];

                    $OrderBookingStatus = isset($response['order']['status']) ? $response['order']['status'] : '';
                    $BookStatus = isset($response['status']['success']) ? $response['status']['success'] : $BookStatus;
                     
                    if ($status == 1 && $BookStatus == 1 && $OrderBookingStatus != 'ABORTED') {
                        $InvoiceCreate = [];
                        if ($isHoldBooking == 0) {
                            $InvoiceCreate = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->InvoiceCreate($Invoicedata, $BookingData, $this->agencyDetails['SecurityKey'], $this->intLoggedinAgencyId);
                        }
                        foreach ($BookingData as $k => $value) {
                            $postField = isset($apiResponse['postField'][$k]) ? $apiResponse['postField'][$k] : [];
                            $postField['PublishedFare'] = $PublishedFare;
                            $postField['MasterTPSysId'] = $MasterTPSysId;
                            $postField['TPSysId'] = $TPSysId;
                            $postField['TrxId'] = $TrxId;
                            $postField['VersionId'] = $VersionId[$k];
                            if($paymentModebyUser == 2){
                                $postField['IsPayLater'] = 1;
                                $postField['flexiPayment'] = 1;
                                $postField['flexiAmount'] = 0;
                            }
//                            echo "<pre>";print_r($postField);die;
                            //isHoldBooking
                            $URL = $this->baseUrl . "/gtxwebservices/flight-api/updatebooking";
                            $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($postField, $getData, $URL);
                            $GTXUpdateresponse = $result;
                        }
                    } else {
                        if ($IsB2BCustomer == 1 && $isHoldBooking == 0) {
                            $dataArray = array(
                                'B2BAgencySysIdKey' => $B2CAgencySysIdKey,
                                'B2CAgencySysIdKey' => $B2BAgencySysIdKey,
                                'PaymentMode' => 'Wallet Refund',
                                'Amount' => $B2BWalletbalance,
                                'RefrenceNo' => $bookingId,
                                'CreditDate' => date('Y-m-d'),
                                'Remark' => 'Refund',
                                'PlanType' => 7,
                                '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 && $isHoldBooking == 0) {
                            $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;
                        // $response = array('success' => false, 'TrackId' => base64_encode($TPSysId), 'msg' => $message);
                        // echo json_encode($response);
                        // exit;
                    }
                }

                $arrUrlData['Bookres'] = $Bookres;
                $arrUrlData['InvoiceCreate'] = $InvoiceCreate;
                $arrUrlData['GTXUpdateresponse'] = $GTXUpdateresponse;
                $arrUrlData['APIBookingresponse'] = $APIBookingresponse;
                $arrUrlData['walletTransactionId'] = $TransactionId;
                $arrUrlData['CreditIntoWallet'] = $CreditIntoWallet;
                $arrUrlData['message'] = $message;
                $tempData = array(
                    'TPSysId' => $intTPSysId,
                    'TraceId' => $post['strUrlData'],
                    'APIBookingData' => json_encode($arrUrlData),
                );
                //echo "tempData<pre>";print_r($tempData); die;
                $objFlight->deleteFlightTempData($post['strUrlData']);
                $objFlight->insertFlightTempData($tempData);
                $response = array('success' => true, 'TrackId' => base64_encode($TPSysId), 'msg' => $ErrorMessage, 'urlData' => $strUrlData, 'formAction' => "/flight-new/booking-confirmation/data/" . $TrackId . "?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 bookingConfirmationAction() {
        $param = $this->getRequest()->getParams();

        if ($this->getRequest()->isPost() && $this->_request->isXmlHttpRequest()) {
            /* Disable Layout  */
            $this->_helper->layout->disableLayout();
            $post = $this->getRequest()->getPost();
            $strTrxStatus = !empty($this->getRequest()->getParam('trxstatus')) ? $this->getRequest()->getParam('trxstatus') : $post['status'];
            $param = $this->getRequest()->getParams();
            $objFlight = new Travel_Model_TblFlight();
            if ($strTrxStatus == "success") {
                $strUrlData = $TrackId = $this->getRequest()->getParam('strUrlData');

                die('ddd');
            }
        } else {
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => base64_decode($param['data']), 'version' => null, 'IsApproved' => 0];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $FlightBookingData = $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $passengerData = $arrtravellerList = isset($apiResponse['customer']) ? $apiResponse['customer'] : [];
            $CustomerDetails = isset($apiResponse['CustomerDetails']) ? $apiResponse['CustomerDetails'] : [];

            // $objFlight = new Travel_Model_TblFlight();
            // $FlightTempData = $objFlight->GetFlightTempDataByTPSysId(base64_decode($param['data']));
            // $this->view->TPSysId = $TPSysId = ($FlightTempData['TPSysId'] > 0) ? $FlightTempData['TPSysId'] : 0;
            // $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            // echo "<pre>";
            // print_r(($apiResponse));
            // die;

            $BaseFare = 0;
            $Taxesfee = 0;
            $CommDiscount = $Discount = 0;
            $TotalPay = 0;
            $ServiceFee__ = 0;
            $AirlineTax = 0;
            $FuelSurcharge = 0;
            $GSTOnMarkUp_ = 0;
            $FixedMarkUp_ = 0;
            $CommissionEarned_ = 0;
            $TDSEarn_ = 0;
            $XRefBookingId = [];
            $AirlineRefPNR = [];
            $AirlineRefGDSPNR = [];
            if ($FlightBookingData) {
                foreach ($FlightBookingData as $key => $value) {
                    $XRefBookingId[] = trim($value['XRefBookingId']);

                    if (!empty(trim($value['AirlineRefPNR']))) {
                        $AirlineRefPNR[] = trim($value['AirlineRefPNR']);
                    }
                    if (!empty(trim($value['AirlineRefGDSPNR']))) {
                        $AirlineRefGDSPNR[] = trim($value['AirlineRefGDSPNR']);
                    }

                    foreach ($value['FareBreakdown'] as $FareBreakdown) {
                        $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                        $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                        $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                        $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                        $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                        $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                        $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                        $Discount += isset($FareBreakdown['Discount']) ? ($FareBreakdown['Discount']) : 0;
                        $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                        $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                        $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                        $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                        $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                        $AirlineTax += ($Tax);
                        $FuelSurcharge += ($YQ);
                        $GSTOnMarkUp_ += ($GSTOnMarkUp);
                        $FixedMarkUp_ += ($FixedMarkUp);
                        $CommissionEarned_ += ($CommissionEarned);
                        $TDSEarn_ += ($TDSEarn);
                    }
                }
            }
            $BagPrice = 0;
            $MealPrice = 0;
            $SeatPrice = 0;
            foreach ($passengerData as $kkkk => $ValCustomer) {
                $BagPrice += !empty($ValCustomer['BagPrice']) ? $ValCustomer['BagPrice'] : 0;
                $MealPrice += !empty($ValCustomer['MealPrice']) ? $ValCustomer['MealPrice'] : 0;
                $SeatPrice += !empty($ValCustomer['SeatPrice']) ? $ValCustomer['SeatPrice'] : 0;
            }
            $fare = [
                'Currency' => isset($FlightBookingData[0]['CurrencySymbol']) ? trim($FlightBookingData[0]['CurrencySymbol']) : 'INR',
                'BaseFare' => round($BaseFare, 2),
                'Taxesfee' => round($Taxesfee, 2),
                'CommDiscount' => round($CommDiscount+$Discount, 2),
                'CommissionEarned' => round($CommissionEarned_, 2),
                'TDSEarn' => round($TDSEarn_, 2),
                'TotalPay' => round($TotalPay - $CommDiscount - $Discount + $MealPrice + $BagPrice + $SeatPrice, 2),
                'AirlineTax' => round($AirlineTax, 2),
                'FuelSurcharge' => round($FuelSurcharge, 2),
                'FixedMarkUp' => round($FixedMarkUp_, 2),
                'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
                'MealPrice' => $MealPrice,
                'BagPrice' => $BagPrice,
                'SeatPrice' => $SeatPrice,
                'TotalSSR' => ($MealPrice + $BagPrice + $SeatPrice),
                'TotalProfit' => round(($TDSEarn_ + $CommissionEarned_ + $FixedMarkUp_ + $GSTOnMarkUp_ - $CommDiscount - $Discount), 2),
            ];
            $this->view->FlightBookingData = $FlightBookingData;
            $this->view->arrtravellerList = $passengerData;
            $this->view->fare = $fare;
            $this->view->CustomerDetails = $CustomerDetails;
            $this->view->TPSysId = $param['data'];
            $this->view->AirlineRefPNR = array_values(array_unique($AirlineRefPNR));
            $this->view->AirlineRefGDSPNR = array_values(array_unique($AirlineRefGDSPNR));
            $this->view->XRefBookingId = array_values(array_unique($XRefBookingId));
            $this->view->intTPSysId = base64_decode($param['data']);

            // echo '<pre>';
            // print_r(($fare));
            // echo '<pre>';
            // print_r(($FlightBookingData));
            // die;
        }
    }

    public function updateTicketAction() {
        $param = $this->getRequest()->getParams();

        $Id = $this->getRequest()->getParam("id");
        $code = $this->getRequest()->getParam("code");
        if (!empty($Id)) {
            $secureCode = Catabatic_ValidateCustomer::secureCode(trim($Id), 1);
            if ($secureCode != $code) {
                echo "Please check your request parameters";
                exit;
            }
        }

        if ($this->getRequest()->isPost() && $this->_request->isXmlHttpRequest()) {
            /* Disable Layout */
            $this->_helper->layout->disableLayout();
            $param = $this->getRequest()->getParams();
            $objFlight = new Travel_Model_TblFlight();
            $TblMarkup = new Markup_Model_Markup();
            $objPayment = new Payment_Model_Payment();
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => base64_decode($param['id']), 'version' => $param['version'], 'IsApproved' => 0];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $FlightBookingData = $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $CustomerDetails = isset($apiResponse['CustomerDetails']) ? $apiResponse['CustomerDetails'] : [];
            $SupportContact = isset($apiResponse['SupportContact']) ? $apiResponse['SupportContact'] : [];
            $passengerData = $arrtravellerList = isset($apiResponse['customer']) ? $apiResponse['customer'] : [];
            // echo "<pre>";
            // print_r(($apiResponse));
            // die;
            $intTPSysId = (isset($param['intTPSysId'])) ? $param['intTPSysId'] : 0;
            $actionID = (isset($param['actionID'])) ? $param['actionID'] : 0;
            $Salutation = (isset($param['passengerSalutation'])) ? $param['passengerSalutation'] : [];
            $FirstName = (isset($param['passengerFirstName'])) ? $param['passengerFirstName'] : [];
            $LastName = (isset($param['passengerLastName'])) ? $param['passengerLastName'] : [];
            $pnrDetails = (isset($param['pnrDetail'])) ? $param['pnrDetail'] : [];
            $ticketNumberDetails = (isset($param['ticketNumberDetails'])) ? $param['ticketNumberDetails'] : [];
            $ticketNumberInwardDetails = (isset($param['ticketNumberInwordDetails'])) ? $param['ticketNumberInwordDetails'] : [];
            $IsB2BProposal = isset($FlightBookingData[0]['IsB2BProposal']) ? $FlightBookingData[0]['IsB2BProposal'] : 0;
            $ICSourceSysId = isset($FlightBookingData[0]['ICSourceSysId']) ? $FlightBookingData[0]['ICSourceSysId'] : 0;
            $XRefBookingId = isset($FlightBookingData[0]['XRefBookingId']) ? $FlightBookingData[0]['XRefBookingId'] : 0;
            $SourceAirportCode = isset($FlightBookingData[0]['SourceAirportCode']) ? $FlightBookingData[0]['SourceAirportCode'] : '';
            $DestAirportCode = isset($FlightBookingData[0]['DestAirportCode']) ? $FlightBookingData[0]['DestAirportCode'] : '';
            $emailid = isset($FlightBookingData[0]['emailid']) ? $FlightBookingData[0]['emailid'] : '';
            $AgentEmailId = isset($FlightBookingData[0]['AgentEmailId']) ? $FlightBookingData[0]['AgentEmailId'] : '';
            $AgencySysId = $this->intLoggedinAgencyId;
            // $SupportContact = $TblMarkup->getAgencyUserDetail(array('AgencySysId' => $AgencySysId, 'ItemSourceType' => 2, 'PlanType' => 1, 'MarketType' => 2));
            $AgentSysId = $FlightBookingData[0]['AgentSysId'];
            $agentName = $CustomerDetails['name'];
            $AgencyEmailId = $FlightBookingData[0]['PrimaryEmail'];
            // echo "<pre>";
            // print_r(($FlightBookingData));
            // die;
            $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($this->intLoggedinAgencyId);

            $AgencyDisplayName = (isset($FlightBookingData[0]['DisplayName']) && !empty($FlightBookingData[0]['DisplayName'])) ? $FlightBookingData[0]['DisplayName'] : $FlightBookingData[0]['Title'];
            $IsB2bSiteurl = (isset($FlightBookingData[0]['IsB2bSiteurl']) && !empty($FlightBookingData[0]['IsB2bSiteurl'])) ? $FlightBookingData[0]['IsB2bSiteurl'] : '';
            $FromDate = trim($FlightBookingData[0]['LocalFromTime']);
            $AirlineName = trim($FlightBookingData[0]['AirLineTitle']);
            $FlightNumber = trim($FlightBookingData[0]['FlightNumber']);
            $CustomerSysId = trim($FlightBookingData[0]['CustomerSysId']);
            $CurrencyType = trim($FlightBookingData[0]['CurrencyType']);
            $customer = [];
            if ($passengerData) {
                foreach ($passengerData as $value) {
                    $AirVersionId = $value['VersionId'];
                    $customer[$AirVersionId][] = $value;
                }
            }
            if ($FlightBookingData) {
                if ($actionID == 1) {
                    $ARR_SALUTIONTBO = unserialize(ARR_SALUTIONTBO);
                    $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
                    $model = new Gtxwebservices_Model_Webservices();
                    foreach ($FlightBookingData as $k => $value) {
                        $AirVersionId = $value['AirVersionId'];
                        $segmentArray = [];
                        foreach ($value['Segments'] as $seg) {
                            $originAirportCode = $seg['OriginAirportCode'];
                            $destinationAirportCode = $seg['DestAirportCode'];
                            $segmentArray[] = $originAirportCode . '-' . $destinationAirportCode;
                        }
                        $customerpnr = [];
                        $finalpnr = [];
                        if ($customer[$AirVersionId]) {
                            foreach ($customer[$AirVersionId] as $pk => $pax) {
                                $Sectors = explode('@@', $pax['Sectors']);
                                $TicketNumber = [];
                                $TicketId = [];
                                foreach ($segmentArray as $sgvl) {
                                    $TicketNumber[] = isset($pnrDetails[$sgvl]) ? $pnrDetails[$sgvl] : '';
                                    $finalpnr[] = isset($pnrDetails[$sgvl]) ? $pnrDetails[$sgvl] : '';
                                    $TicketId[] = (isset($ticketNumberDetails[$sgvl][$pk]) && !empty($ticketNumberDetails[$sgvl][$pk])) ? $ticketNumberDetails[$sgvl][$pk] : '';
                                }
                                $FirstName_ = (isset($FirstName[$AirVersionId][$pk]) && !empty($FirstName[$AirVersionId][$pk])) ? $FirstName[$AirVersionId][$pk] : '';
                                $LastName_ = (isset($LastName[$AirVersionId][$pk]) && !empty($LastName[$AirVersionId][$pk])) ? $LastName[$AirVersionId][$pk] : '';
                                $Salutation_ = (isset($Salutation[$AirVersionId][$pk]) && !empty($Salutation[$AirVersionId][$pk])) ? $Salutation[$AirVersionId][$pk] : '';

                                if (empty($ARR_SALUTION[$Salutation_])) {
                                    $result = array('success' => false, 'message' => 'Please select all title.');
                                    echo json_encode($result);
                                    exit;
                                }
                                if (empty($FirstName_)) {
                                    $result = array('success' => false, 'message' => 'Please enter all first name.');
                                    echo json_encode($result);
                                    exit;
                                }
                                if (empty($LastName_)) {
                                    $result = array('success' => false, 'message' => 'Please enter all last name.');
                                    echo json_encode($result);
                                    exit;
                                }
                                if (empty(implode('-', $TicketNumber))) {
                                    $result = array('success' => false, 'message' => 'Please enter all PNR Number.');
                                    echo json_encode($result);
                                    exit;
                                }
                                $customerpnr[$pax['TPPaxSysId']]['Salutation'] = $ARR_SALUTION[$Salutation_];
                                $customerpnr[$pax['TPPaxSysId']]['FirstName'] = $FirstName_;
                                $customerpnr[$pax['TPPaxSysId']]['LastName'] = $LastName_;
                                $customerpnr[$pax['TPPaxSysId']]['PNR_Number'] = implode('-', $TicketNumber);
                                $customerpnr[$pax['TPPaxSysId']]['TicketId'] = implode('-', $TicketNumber);
                                $customerpnr[$pax['TPPaxSysId']]['TicketNumber'] = implode('-', $TicketId);
                                $customerpnr[$pax['TPPaxSysId']]['sectors'] = implode('@@', $segmentArray);
                            }
                        }

                        $PNRNew = array_values(array_unique($finalpnr));
                        $postFieldArray = array(
                            'MasterTPSysId' => $value['MasterTPSysId'],
                            'TPSysId' => $value['TPSysId'],
                            'VersionId' => $value['AirVersionId'],
                            'customerpnr' => $customerpnr,
                            'PNRNumber' => implode('-', $PNRNew),
                            'GDSPNRNumber' => '',
                            'ErrorCode' => 0,
                            'ErrorMessage' => '',
                            'IsBookingStatus' => 1,
                            'OnwardAutoTicket' => 1,
                            'IsManualUpdate' => true,
                            'sectorTitle' => trim($value['SourceAirportCode']) . '-' . trim($value['DestAirportCode']),
                            'BookingId' => !empty($value['XRefBookingId']) ? $value['XRefBookingId'] : '',
                            'APIBookingId' => !empty($value['APIBookingId']) ? $value['APIBookingId'] : '',
                        );
                        $result = $model->UPDATE_PNR_API($postFieldArray);
                        $updateResponse = json_decode($result, 1);
                        $Updatestatus = isset($updateResponse['status']) ? $updateResponse['status'] : false;
                        $Updatemessage = isset($updateResponse['message']) ? $updateResponse['message'] : '';
                        if ($Updatestatus != 1) {
                            $result = array('success' => false, 'message' => $Updatemessage);
                            echo json_encode($result);
                            exit;
                        }
                    }

                    $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
                    $PostData = ['TPSysId' => base64_decode($param['id']), 'version' => $param['version'], 'IsApproved' => 0];
                    $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
                    $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
                    $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
                    $CustomerDetails = isset($apiResponse['CustomerDetails']) ? $apiResponse['CustomerDetails'] : [];
                    $SupportContact = isset($apiResponse['SupportContact']) ? $apiResponse['SupportContact'] : [];
                    $arrtravellerList = isset($apiResponse['customer']) ? $apiResponse['customer'] : [];

                    $CurrentStatus = $bookingDataByAPI[0]['CurrentStatus'];
                    $PaymentStatus = $bookingDataByAPI[0]['PaymentStatus'];

                    if ($PaymentStatus == 130 && $CurrentStatus == 142) {
                        $params['bookingDataByAPI'] = $bookingDataByAPI;
                        $params['arrtravellerList'] = $arrtravellerList;
                        $params['getSupportContact'] = $SupportContact;
                        $params['intTPSysId'] = $intTPSysId;
                        $params['CustomerDetails'] = $CustomerDetails;
                        $params['withprice'] = 1;
                        $params['type'] = 'mailToCustomer';
                        $params['sendersEmailId'] = (isset($SupportContact['EmailId']) && !empty($SupportContact['EmailId'])) ? $SupportContact['EmailId'] : $AgencyEmailId;
                        $params['agencyDisplayName'] = $AgencyDisplayName;
                        $params['arrEmailStatisticsType'] = 1;
                        $params['AgencySysId'] = $AgencySysId;
                        $params['TPSysId'] = $intTPSysId;
                        $params['AgentSysId'] = $AgentSysId;

                        $html = new Zend_View();
                        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/booking-flight/');
                        $html->assign($params);
                        $bodyText = $html->render('e-ticket-mail.phtml');
                        $sendersEmailId = trim($params['sendersEmailId']);
                        $subject = 'Your Ticket Has Been Confirmed ' . ' (Ref: ' . $XRefBookingId . ')';
                        $emailData = array(
                            'fromEmail' => $params['sendersEmailId'],
                            'fromName' => $params['agencyDisplayName'],
                            'subject' => $subject,
                            'to' => array(trim($emailid)),
                            'bodyHtml' => $bodyText,
                            'bodyText' => ''
                        );

                        try {
                            $arrEmailStatistics = array(
                                "TPSysId" => $params['TPSysId'],
                                "TypeSysId" => 1, // 1 For Email 2 For SMS
                                "AgencySysId" => $params['AgencySysId'],
                                "AgentSysId" => $params['AgentSysId'],
                                "Title" => $bodyText,
                                "Source" => $params['arrEmailStatisticsType'], // 1 For Fresh Proposals
                                "Status" => 0,
                                "RefSysId" => "",
                                "RefSysStatus" => "",
                                "CreateDate" => date('Y-m-d H:i:s')
                            );
                            $emailstatus = Catabatic_ValidateCustomer::mailSentByElastice($emailData, $arrEmailStatistics, 0, 0, array($sendersEmailId));
                        } catch (Exception $err) {
                            $result = array('success' => false, 'message' => 'Exception!. Unable to send confirmation main please try after some time.');
                            echo json_encode($result);
                            exit;
                        }
                        $result = array('success' => true, 'message' => 'Booking Confirmed Successfully.');
                        echo json_encode($result);
                        exit;
                    } else {
                        $result = array('success' => false, 'message' => 'Unable to update please try after some time.');
                        echo json_encode($result);
                        exit;
                    }
                } elseif ($actionID == 2) {
                    $TotalCost = 0;
                    if ($ICSourceSysId == 8) {
                        foreach ($FlightBookingData as $k => $value) {
                            $Adult = $Child = $Infant = 0;
                            if ($customer[$AirVersionId]) {
                                foreach ($customer[$AirVersionId] as $pk => $pax) {
                                    if ($pax['paxType'] == '1') {
                                        $Adult++;
                                    } else if ($pax['paxType'] == '2') {
                                        $Child++;
                                    } else {
                                        $Infant++;
                                    }
                                }
                            }
                            $MasterTPSysId = $value['MasterTPSysId'];
                            $APIBookingId = $value['APIBookingId'];
                            $XRefBookingId = $value['XRefBookingId'];
                            $IsB2BProposal = (int) $value['IsB2BProposal'];
                            $SecurityKey = $this->agencyDetails['SecurityKey'];
                            $PYTHON_API_URL = PYTHON_API_URL;
                            $url = $PYTHON_API_URL . "flightinventory/booking-cancel-auto-ticket/?SecurityKey=" . $SecurityKey . "&BookingId=" . $APIBookingId . "&Adult=" . $Adult . "&Child=" . $Child . "&Infant=" . $Infant;
                            $resultset = $objPayment->getgtxapiinfo($url);
                            //$resultset = json_decode('{"count":1,"next":"","previous":"","results":{"Status":true,"refId":"30D459CD505D4B299638E076D00BD2C7","resultSet":{"AC":{"TotalInventory":1,"TotalInventoryCost":1610},"Infant":{"TotalInventory":0,"TotalInventoryCost":0}}}}', 1);
                            $datajson = array('url' => $url);
                            $CancelStatus = (isset($resultset['results']['Status']) && $resultset['results']['Status'] == 1) ? $resultset['results']['Status'] : false;
                            $CancelrefId = (isset($resultset['results']['refId']) && $resultset['results']['refId']) ? $resultset['results']['refId'] : '';
                            // echo json_encode($resultset);
                            if ($CancelStatus == 1 && $CancelrefId != '') {
                                $TotalCost += (float) $value['TotalCost'];
                                $dataModification = array(
                                    "ChangeRequestId" => $resultset['results']['refId'],
                                    "ChangeRequestStatus" => 1,
                                    "TPSysId" => $intTPSysId,
                                    "BookingId" => $XRefBookingId,
                                    "RequestType" => 8,
                                    "Remarks" => 'Cancel By Superadmin',
                                    "RequestData" => json_encode($datajson),
                                    "APIResponseData" => json_encode($resultset),
                                    "servicefee" => 0,
                                    "RefundMode" => 'Cash',
                                    "status" => 19,
                                    "refundedamount" => $value['TotalCost'],
                                    "amendmentcharges" => 0,
                                    "AgencySysId" => $this->intLoggedinAgencyId,
                                    "AgentSysId" => $this->intLoggedinUserId,
                                    "CreateDate" => date('Y-m-d H:i:s'),
                                    "UpdateDate" => date('Y-m-d H:i:s')
                                );
                                $objFlight->insertFlightModification($dataModification);

                                $updateTP['StatusType'] = 10;
                                $updateTP['querystatus'] = 143;
                                $updateTP['PaymentStatus'] = 35;
                                $updateTP['BookingStatus'] = 38;
                                $updateTP['ChangeRequestId'] = isset($resultset['results']['refId']) ? $resultset['results']['refId'] : '';
                                $updateTP['ChangeRequestStatus'] = 1;
                                $objFlight->updateBookingStatusTravelPlan($updateTP, $intTPSysId, $MasterTPSysId);
                                if ($customer[$AirVersionId]) {
                                    foreach ($customer[$AirVersionId] as $key => $paxVal) {
                                        $data1 = array(
                                            "ChangeRequestId" => isset($resultset['results']['refId']) ? $resultset['results']['refId'] : '',
                                            "ChangeRequestStatus" => 1,
                                            "ChangeRequestRes" => json_encode($resultset),
                                        );
                                        $objFlight->updateTravelPlanPax($data1, $paxVal['TPPaxSysId']);
                                    }
                                }
                            } else {
                                $result = array('success' => $resultset['results']['Status'], 'message' => $resultset['results']['Message']);
                                echo json_encode($result);
                                exit;
                            }
                        }

                        if ($IsB2BProposal == 1) {
                            $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($CustomerSysId);
                            $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;
                            $B2BWalletbalance = $TotalCost;

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

                            $dataArray = array(
                                'B2BAgencySysIdKey' => $B2CAgencySysIdKey,
                                'B2CAgencySysIdKey' => $B2BAgencySysIdKey,
                                'PaymentMode' => 'Wallet Refund',
                                'Amount' => $B2BWalletbalance,
                                'RefrenceNo' => $XRefBookingId,
                                'CreditDate' => date('Y-m-d'),
                                'Remark' => 'Refund Cancel Booking',
                                'PlanType' => 7,
                                'CurrencyType' => $CurrencyType,
                                'UserSysId' => $UserSysId,
                                'FlightTraceId' => $XRefBookingId,
                            );
                            $URL_CREDIT = $this->baseUrl . '/webservice/credit-balance/save-online-request/';
                            $CreditIntoWallet = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->CreditIntoWallet($dataArray, $URL_CREDIT, $AgencySysId__);
                            $refundstatus = isset($CreditIntoWallet['status']) ? $CreditIntoWallet['status'] : false;
                            $refundmessage = isset($CreditIntoWallet['message']) ? $CreditIntoWallet['message'] : '';
                            if ($refundstatus != 1) {
                                $result = array('success' => false, 'message' => $refundmessage . ' Unable to refund please contact with our support team.');
                                echo json_encode($result);
                                exit;
                            }
                        }

                        $params = array();
                        $params['sendersEmailId'] = (isset($SupportContact['EmailId']) && !empty($SupportContact['EmailId'])) ? $SupportContact['EmailId'] : $AgencyEmailId;
                        $params['FirstName'] = (isset($SupportContact['FirstName']) && !empty($SupportContact['FirstName'])) ? $SupportContact['FirstName'] : '';
                        $params['LastName'] = (isset($SupportContact['LastName']) && !empty($SupportContact['LastName'])) ? $SupportContact['LastName'] : '';
                        $params['countrycode'] = (isset($SupportContact['countrycode']) && !empty($SupportContact['countrycode'])) ? $SupportContact['countrycode'] : '';
                        $params['ContactNo1'] = (isset($SupportContact['ContactNo1']) && !empty($SupportContact['ContactNo1'])) ? $SupportContact['ContactNo1'] : '';
                        $params['agentName'] = $agentName;
                        $params['agencyDisplayName'] = $AgencyDisplayName;
                        $params['XRefBookingId'] = $XRefBookingId;
                        $params['Sector'] = '';
                        $params['TravelDate'] = $FromDate;
                        $params['AirlineName'] = $AirlineName;
                        $params['FlightNumber'] = $FlightNumber;
                        $params['newtravellerInfos'] = [];
                        $params['IsB2bSiteurl'] = $IsB2bSiteurl;
                        $params['AgencySysId'] = $AgencySysId;
                        $params['TPSysId'] = $intTPSysId;
                        $params['AgentSysId'] = $AgentSysId;
                        $params['arrEmailStatisticsType'] = 1;
                        $params['IsConfirm'] = 0;

                        $html = new Zend_View();
                        $html->setScriptPath(APPLICATION_PATH . '/views/emails/');
                        $html->assign($params);
                        $bodyText = $html->render('send_updateticket_to_booking_agent.phtml');

                        $subject = 'Booking Failed - ' . trim($SourceAirportCode) . ' - ' . trim($DestAirportCode) . ' (Ref: ' . $XRefBookingId . ')';

                        $sendersEmailId = trim($params['sendersEmailId']);
                        $emailData = array(
                            'fromEmail' => $params['sendersEmailId'],
                            'fromName' => $params['agencyDisplayName'],
                            'subject' => $subject,
                            'to' => array(trim($emailid)),
                            'bodyHtml' => $bodyText,
                            'bodyText' => ''
                        );
                        $emailData_sender = array(
                            'fromEmail' => $params['sendersEmailId'],
                            'fromName' => $params['agencyDisplayName'],
                            'subject' => $subject,
                            'to' => array($sendersEmailId),
                            'bodyHtml' => $bodyText,
                            'bodyText' => ''
                        );
                        try {
                            $arrEmailStatistics = array(
                                "TPSysId" => $params['TPSysId'],
                                "TypeSysId" => 1, // 1 For Email 2 For SMS
                                "AgencySysId" => $params['AgencySysId'],
                                "AgentSysId" => $params['AgentSysId'],
                                "Title" => $bodyText,
                                "Source" => $params['arrEmailStatisticsType'], // 1 For Fresh Proposals
                                "Status" => 0,
                                "RefSysId" => "",
                                "RefSysStatus" => "",
                                "CreateDate" => date('Y-m-d H:i:s')
                            );

                            $emailstatus = Catabatic_ValidateCustomer::mailSentByElastice($emailData, $arrEmailStatistics, 0, 0, array($sendersEmailId));
                            $emailstatus1 = Catabatic_ValidateCustomer::mailSentByElastice($emailData_sender, $arrEmailStatistics, 0, 0, array($sendersEmailId), array(trim($AgentEmailId)));
                            // echo "<pre>";
                            // print_r(($emailstatus));
                            // echo "<pre>";
                            // print_r(($emailstatus1));
                        } catch (Exception $err) { //print_r($mail);
                            $result = array('success' => false, 'message' => 'Exception!. Unable to update please try after some time.');
                            echo json_encode($result);
                            exit;
                        }
                        $result = array('success' => true, 'message' => 'Booking Cancelled Successfully.');
                        echo json_encode($result);
                        exit;
                    }
                }
            }
        } else {
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => base64_decode($param['id']), 'version' => $param['version'], 'IsApproved' => 0];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $FlightBookingData = $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $passengerData = $arrtravellerList = isset($apiResponse['customer']) ? $apiResponse['customer'] : [];
            $CustomerDetails = isset($apiResponse['CustomerDetails']) ? $apiResponse['CustomerDetails'] : [];
            $departureDates = date('d/m/Y', strtotime($FlightBookingData[0]['LocalFromTime']));
            $arrDepartureDates = explode("/", $departureDates);
            $this->view->departureDates = $departureDates = $arrDepartureDates[2] . "/" . $arrDepartureDates[1] . "/" . ($arrDepartureDates[0] - 1);
            $this->view->departureMonthInfant = $departureMonthInfant = $arrDepartureDates[1];
            $this->view->departureDayInfant = $departureDayInfant = ($arrDepartureDates[0] + 1);
            // echo "<pre>";
            // print_r(($departureMonthInfant));
            // echo "<pre>";
            // print_r(($apiResponse));
            // die;
            $BaseFare = 0;
            $Taxesfee = 0;
            $CommDiscount = 0;
            $TotalPay = 0;
            $ServiceFee__ = 0;
            $AirlineTax = 0;
            $FuelSurcharge = 0;
            $GSTOnMarkUp_ = 0;
            $FixedMarkUp_ = 0;
            $CommissionEarned_ = 0;
            $TDSEarn_ = 0;
            $XRefBookingId = [];
            $AirlineRefPNR = [];
            $AirlineRefGDSPNR = [];
            $APIBookingId = [];
            if ($FlightBookingData) {
                foreach ($FlightBookingData as $key => $value) {
                    $XRefBookingId[] = trim($value['XRefBookingId']);

                    if (!empty(trim($value['AirlineRefPNR']))) {
                        $AirlineRefPNR[] = trim($value['AirlineRefPNR']);
                    }
                    if (!empty(trim($value['AirlineRefGDSPNR']))) {
                        $AirlineRefGDSPNR[] = trim($value['AirlineRefGDSPNR']);
                    }
                    if (!empty(trim($value['APIBookingId']))) {
                        $APIBookingId[] = trim($value['APIBookingId']);
                    }

                    foreach ($value['FareBreakdown'] as $FareBreakdown) {
                        $BaseFare += isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                        $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                        $TDSEarn = isset($FareBreakdown['TDSEarn']) ? ($FareBreakdown['TDSEarn']) : 0;
                        $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                        $GSTOnMarkUp = isset($FareBreakdown['GSTOnMarkUp']) ? ($FareBreakdown['GSTOnMarkUp']) : 0;
                        $CommissionEarned = isset($FareBreakdown['CommissionEarned']) ? ($FareBreakdown['CommissionEarned']) : 0;
                        $CommDiscount += isset($FareBreakdown['CommDiscount']) ? ($FareBreakdown['CommDiscount']) : 0;
                        $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                        $YQ = isset($FareBreakdown['TaxBR']['YQ']) ? ($FareBreakdown['TaxBR']['YQ']) : 0;
                        $Taxesfee += ($FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                        $TotalPay += ($BaseFare_ + $FixedMarkUp + $GSTOnMarkUp + $CommissionEarned + $Tax + $TDSEarn);
                        $ServiceFee__ += ($FixedMarkUp + $GSTOnMarkUp);
                        $AirlineTax += ($Tax);
                        $FuelSurcharge += ($YQ);
                        $GSTOnMarkUp_ += ($GSTOnMarkUp);
                        $FixedMarkUp_ += ($FixedMarkUp);
                        $CommissionEarned_ += ($CommissionEarned);
                        $TDSEarn_ += ($TDSEarn);
                    }
                }
            }
            $BagPrice = 0;
            $MealPrice = 0;
            $SeatPrice = 0;
            foreach ($passengerData as $kkkk => $ValCustomer) {
                $BagPrice += !empty($ValCustomer['BagPrice']) ? $ValCustomer['BagPrice'] : 0;
                $MealPrice += !empty($ValCustomer['MealPrice']) ? $ValCustomer['MealPrice'] : 0;
                $SeatPrice += !empty($ValCustomer['SeatPrice']) ? $ValCustomer['SeatPrice'] : 0;
            }
            $fare = [
                'Currency' => isset($FlightBookingData[0]['FairRules']['Currency']) ? trim($FlightBookingData[0]['FairRules']['Currency']) : 'INR',
                'BaseFare' => round($BaseFare, 2),
                'Taxesfee' => round($Taxesfee, 2),
                'CommDiscount' => round($CommDiscount, 2),
                'CommissionEarned' => round($CommissionEarned_, 2),
                'TDSEarn' => round($TDSEarn_, 2),
                'TotalPay' => round($TotalPay + $MealPrice + $BagPrice + $SeatPrice, 2),
                'AirlineTax' => round($AirlineTax, 2),
                'FuelSurcharge' => round($FuelSurcharge, 2),
                'FixedMarkUp' => round($FixedMarkUp_, 2),
                'GSTOnMarkUp' => round($GSTOnMarkUp_, 2),
                'MealPrice' => $MealPrice,
                'BagPrice' => $BagPrice,
                'SeatPrice' => $SeatPrice,
                'TotalSSR' => ($MealPrice + $BagPrice + $SeatPrice),
                'TotalProfit' => round(($TDSEarn_ + $CommissionEarned_ + $FixedMarkUp_ + $GSTOnMarkUp_), 2),
            ];
            $this->view->FlightBookingData = $FlightBookingData;
            $this->view->arrtravellerList = $passengerData;
            $this->view->fare = $fare;
            $this->view->CustomerDetails = $CustomerDetails;
            $this->view->TPSysId = $param['id'];
            $this->view->AirlineRefPNR = array_values(array_unique($AirlineRefPNR));
            $this->view->AirlineRefGDSPNR = array_values(array_unique($AirlineRefGDSPNR));
            $this->view->XRefBookingId = array_values(array_unique($XRefBookingId));
            $this->view->APIBookingId = array_values(array_unique($APIBookingId));
            $this->view->intTPSysId = base64_decode($param['id']);

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

    public function memberguestdetailAction() {
        //if ($this->_request->isXmlHttpRequest()) {
        $param = $this->getRequest()->getParams();
        $mobile_number = trim($this->getRequest()->getParam('mobile_number'));
        $email_id = trim($this->getRequest()->getParam('email_id'));
        $AgencySysId = trim($this->getRequest()->getParam('AgencySysId'));
        $PlanType = trim($this->getRequest()->getParam('PlanType'));

        $ARR_SALUTION = unserialize(ARR_SALUTIONTBO);
        $ARR_SALUTION_CHILD = unserialize(ARR_SALUTIONTBO);

        $IsAgencyCusTExist = $this->_crmcustomerObj->ChkMobileWithResponseUpdate($mobile_number, $AgencySysId, null, $email_id);
        $IsB2BAgent = (isset($IsAgencyCusTExist['IsB2BAgent']) && $IsAgencyCusTExist['IsB2BAgent'] == 1) ? $IsAgencyCusTExist['IsB2BAgent'] : 0;
        $result = array();
        if (!empty($IsAgencyCusTExist)) {
            if ($IsB2BAgent == 1) {
                $result = array_values(array_merge([], $this->_crmcustomerObj->GetCustomerMembersById($AgencySysId, $IsAgencyCusTExist['CustomerSysId'])));
            } else {
                $result = array_values(array_merge([$IsAgencyCusTExist], $this->_crmcustomerObj->GetCustomerMembersById($AgencySysId, $IsAgencyCusTExist['CustomerSysId'])));
            }
        } else {
            $result = [$IsAgencyCusTExist];
        }

        // echo '<pre>';
        // print_r(($result));
        // die;
        $responseArray = [];
        if ($result) {
            foreach ($result as $key => $val) {
                $paxType = !empty($val['paxType']) ? trim($val['paxType']) : 0;
                $CustomerTitle = trim($val['Title']);
                if ($paxType == 1 || $paxType == 0) {
                    $CustomerTitle = $ARR_SALUTION[$CustomerTitle];
                    $paxTypeName = 'ADULT';
                } elseif ($paxType == 2) {
                    $CustomerTitle = $ARR_SALUTION_CHILD[$CustomerTitle];
                    $paxTypeName = 'CHILD';
                } else {
                    $CustomerTitle = $ARR_SALUTION_CHILD[$CustomerTitle];
                    $paxTypeName = 'INFANT';
                }
                $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'] != '1900-01-01 00:00:00.000000') ? date('d/m/Y', strtotime($DOB_['date'])) : '';
                } else {
                    $DOB = '';
                }
                if (!empty($PassportExpiry_['date']) && date('Y-m-d', strtotime($PassportExpiry_['date'])) != '1900-01-01') {
                    $PassportExpiry = ($PassportExpiry_['date'] != '1900-01-01 00:00:00.000000') ? 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'] != '1900-01-01 00:00:00.000000') ? date('d/m/Y', strtotime($PassportIssue_['date'])) : '';
                } else {
                    $PassportIssue = '';
                }
                $label = $CustomerTitle . '. ' . trim($val['FirstName']) . ' ' . trim($val['LastName']) . ' (' . $paxTypeName . ')';
                $responseArray[$key]['FirstName'] = trim($val['FirstName']);
                $responseArray[$key]['LastName'] = trim($val['LastName']);
                $responseArray[$key]['DOB'] = $DOB;
                $responseArray[$key]['PanCard'] = trim($val['PanCard']);
                $responseArray[$key]['Title'] = trim($val['Title']);
                $responseArray[$key]['Relation'] = trim($val['Relation']);
                $responseArray[$key]['paxType'] = trim($val['paxType']);
                $responseArray[$key]['PassportNo'] = trim($val['PassportNo']);
                $responseArray[$key]['PassportNationality'] = trim($val['PassportNationality']);
                $responseArray[$key]['PanCard'] = isset($val['PanCard']) ? trim($val['PanCard']) : '';
                $responseArray[$key]['PassportIssue'] = $PassportIssue;
                $responseArray[$key]['PassportExpiry'] = $PassportExpiry;
                $responseArray[$key]['CustomerTitle'] = ($CustomerTitle == 'Master') ? 'Mstr' : trim($CustomerTitle);
                ;
                $responseArray[$key]['paxTypeName'] = $paxTypeName;
                $responseArray[$key]['label'] = $label;
            }
        }
        echo json_encode($responseArray);
        exit;
        // echo '<pre>';
        // print_r(($responseArray));
        // die;
        //}
    }

    public function bookingUnholdAction() {

        $strUrlData = $FlightTraceId = $this->view->strUrlData = $this->view->SearchID = $this->getRequest()->getParam('data');
        $param = $this->getRequest()->getParams();
        if ($param && $this->getRequest()->isPost() && $this->getRequest()->isXmlHttpRequest()) {
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => base64_decode($param['TPSysId']), 'version' => null, 'IsApproved' => 0];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $FlightBookingData = $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $ICSourceSysId = isset($FlightBookingData[0]['ICSourceSysId']) ? trim($FlightBookingData[0]['ICSourceSysId']) : '';
            $JourneyType = isset($FlightBookingData[0]['JourneyType']) ? trim($FlightBookingData[0]['JourneyType']) : 1;
            $interNationalSearch = isset($FlightBookingData[0]['IsInternational']) ? trim($FlightBookingData[0]['IsInternational']) : 0;
            $XRefBookingId = isset($FlightBookingData[0]['XRefBookingId']) ? trim($FlightBookingData[0]['XRefBookingId']) : 0;
            $Confirmtoproceed = !empty($param['Confirmtoproceed']) ? (int) $param['Confirmtoproceed'] : 0;
            $unholdpnr = !empty($param['unholdpnr']) ? array_unique($param['unholdpnr']) : 0;
            if (empty($unholdpnr)) {
                $Return = array('success' => false, 'message' => 'Please select PNR');
                echo json_encode($Return);
                exit;
            }
            if ($Confirmtoproceed == 0) {
                $Return = array('success' => false, 'message' => 'Please confirm to proceed');
                echo json_encode($Return);
                exit;
            }
            if ($ICSourceSysId == 7 || $ICSourceSysId == 3) {
                $unholdRequest['bookingId'] = $FlightBookingData[0]['APIBookingId'];
                $unholdRequest['pnrs'] = $unholdpnr;
            }
            $DataS = array(
                'apidata' => $unholdRequest,
                'memberCount' => 0,
                'JourneyType' => $JourneyType,
                'interNationalSearch' => $interNationalSearch,
                'searchID' => $XRefBookingId,
                'ICSourceSysId' => $ICSourceSysId,
                'AgentMarkUp' => 0,
                'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
            );
            // echo $this->agencyDetails['SecurityKey'];
            // echo '<pre>';
            // print_r(json_encode($DataS));
            // die;
            $url = GTX_API_URL . '/flight/v3/unhold';
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $APIunholdResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
            //$APIunholdResponse = json_decode('{"status":true,"message":"SUCCESS","results":{"status":{"success":true,"httpStatus":200}},"postField":{"field":["BookingStatus","StatusType"],"StatusCode":[146,149]},"TransactionStatus":"","BookingId":""}', 1);

            $unholdStatus = ($APIunholdResponse['status']) ? $APIunholdResponse['status'] : false;
            $unholdmessage = ($APIunholdResponse['message']) ? $APIunholdResponse['message'] : '';
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];

            if ($unholdStatus == true) {
                if ($FlightBookingData) {
                    foreach ($FlightBookingData as $k => $value) {
                        $MasterTPSysId = $value['MasterTPSysId'];
                        $TPSysId = $value['TPSysId'];
                        $VersionId = $value['AirVersionId'];
                        $postFieldArray = array(
                            'MasterTPSysId' => $MasterTPSysId,
                            'TPSysId' => $TPSysId,
                            'VersionId' => isset($VersionId) ? $VersionId : 0,
                        );
                        $postField = isset($APIunholdResponse['postField']) ? $APIunholdResponse['postField'] : [];
                        if ($postField['field']) {
                            foreach ($postField['field'] as $keyp => $valueP) {
                                $postFieldArray['field'] = $valueP;
                                $postFieldArray['StatusCode'] = $postField['StatusCode'][$keyp];
                                $URL = $this->baseUrl . "/gtxwebservices/flight/update-api-payment-failed";
                                $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getHttpRequestArray($postFieldArray, $URL);
                            }
                        }
                    }
                }
                $Return = array('success' => true, 'message' => 'PNR Un Hold Successfully', 'FlightTraceId' => $FlightTraceId);
                echo json_encode($Return);
                exit;
            } else {
                $Return = array('success' => false, 'message' => $unholdmessage);
                echo json_encode($Return);
                exit;
            }
        }
    }

    public function farevalidateAction() {

        $strUrlData = $FlightTraceId = $this->view->strUrlData = $this->view->SearchID = $this->getRequest()->getParam('FlightTraceId');
        $param = $this->getRequest()->getParams();
        if ($param && $this->getRequest()->isPost() && $this->getRequest()->isXmlHttpRequest()) {
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => base64_decode($param['FlightTraceId']), 'version' => null, 'IsApproved' => 0];
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $FlightBookingData = $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
            $ICSourceSysId = isset($FlightBookingData[0]['ICSourceSysId']) ? trim($FlightBookingData[0]['ICSourceSysId']) : '';
            $JourneyType = isset($FlightBookingData[0]['JourneyType']) ? trim($FlightBookingData[0]['JourneyType']) : 1;
            $interNationalSearch = isset($FlightBookingData[0]['IsInternational']) ? trim($FlightBookingData[0]['IsInternational']) : 0;
            $XRefBookingId = isset($FlightBookingData[0]['XRefBookingId']) ? trim($FlightBookingData[0]['XRefBookingId']) : 0;

            if ($ICSourceSysId == 7) {
                $Request['bookingId'] = $FlightBookingData[0]['APIBookingId'];
            } else {
                $Return = array('success' => true, 'message' => 'Success', 'FlightTraceId' => $XRefBookingId);
                echo json_encode($Return);
                exit;
            }
            $DataS = array(
                'apidata' => $Request,
                'memberCount' => 0,
                'JourneyType' => $JourneyType,
                'interNationalSearch' => $interNationalSearch,
                'searchID' => $XRefBookingId,
                'ICSourceSysId' => $ICSourceSysId,
                'AgentMarkUp' => 0,
                'APIMode' => ($this->intLoggedinAgencyId == 1) ? 1 : 0,
            );

            $url = GTX_API_URL . '/flight/v3/apifarevalidate';
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $APIunholdResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($DataS, $getData, $url);
            $unholdStatus = ($APIunholdResponse['status']) ? $APIunholdResponse['status'] : false;
            $unholdmessage = ($APIunholdResponse['message']) ? $APIunholdResponse['message'] : '';
            if ($unholdStatus == 1) {
                $Return = array('success' => true, 'message' => 'Success', 'FlightTraceId' => $XRefBookingId);
                echo json_encode($Return);
                exit;
            } else {
                $Return = array('success' => false, 'message' => $unholdmessage);
                echo json_encode($Return);
                exit;
            }
        }
    }

    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 checkArrayKeyExist($arr) {
        $newArr = [];
        foreach ($arr as $key => $value) {
            if (strlen($arr[$key])) {
                $newArr[$key] = $value;
            }
        }
        return array_values(array_unique($newArr));
    }

    public function selectedformailAction() {
        ini_set('memory_limit', '3072M');
        ini_set('post_max_size', '64M');
        $this->_helper->layout->disableLayout();
        $post = json_decode(file_get_contents('php://input'), true);
        $PriceIdArr = ($post['PriceIdArr']);
        $allitem = isset($post['allitem']) ? ($post['allitem']) : [];
        $SearchTraceId = isset($allitem[0]['SearchTraceId']) ? $allitem[0]['SearchTraceId'] : '';
        $JourneyType = isset($allitem[0]['JourneyType']) ? $allitem[0]['JourneyType'] : 1;
        if (isset($allitem[0]['SegPro'][0]['IsInternational'])) {
            $IsInternational = isset($allitem[0]['SegPro'][0]['IsInternational']) ? $allitem[0]['SegPro'][0]['IsInternational'] : 0;
        } else {
            $IsInternational = isset($allitem[0]['IsInternational']) ? $allitem[0]['IsInternational'] : 0;
        }

        $FinalArray__ = [];
        if ($allitem) {
            foreach ($allitem as $element) {
                $dataKey = rand();
                if ($element['FairRules']) {
                    foreach ($element['FairRules'] as $fareval) {
                        if (in_array($fareval['PriceID'], $PriceIdArr)) {
                            $FinalArray__[$fareval['PriceID']] = $element;
                            $FinalArray__[$fareval['PriceID']]['dataKey'] = $dataKey;
                            $FinalArray__[$fareval['PriceID']]['FairRules'] = [$fareval];
                        }
                    }
                }
            }
        }
        $post['FinalArray'] = $FinalArray__;
        $FinalArray = ($post['FinalArray']);
        $FlightData = [];

        if ($FinalArray) {
            foreach ($FinalArray as $val) {
                $SourceAirportCode = $val['SourceAirportCode'];
                $DestAirportCode = $val['DestAirportCode'];
                if ($val['TripType'] == 2 && $val['IsInternational'] == 1) {
                    $FlightData[$val['origin']['JourneyType']][] = $val;
                } else {
                    if ($JourneyType == 3 && $IsInternational == '') {
                        $SourceAirportCode = $val['SourceAirportCode'];
                        $DestAirportCode = $val['DestAirportCode'];
                        //echo '<pre>';print_r($val);echo '</pre>';
                        $FlightData[$SourceAirportCode . '-' . $DestAirportCode][] = $val;
                    } else {
                        //$FlightData[$val['JourneyType']][] = $val;
                        $FlightData[$SourceAirportCode . '-' . $DestAirportCode][] = $val;
                    }
                }
            }
        }
        $response = array('success' => true, 'FlightData' => array_values($FlightData), 'IsInternational' => $IsInternational, 'JourneyType' => $JourneyType, 'SearchTraceId' => $SearchTraceId);
        echo json_encode($response);
        exit;
    }

    public function shareonmailAction() {
        ini_set('memory_limit', '3072M');
        ini_set('post_max_size', '64M');
        $this->_helper->layout->disableLayout();
        $post = json_decode(file_get_contents('php://input'), true);
//        echo "<pre>";print_r($post);die;
        $Outbound = ($post['item']);
        $selectedDataformail = $post['selectedDataformail'];
        $discountvalue = ($post['discountvalue']);
        $addMarkup = ($post['addMarkup']);
        $mobilenumber = ($post['mobilenumber']);
        $countrycode = ($post['countrycode']);
        $emailId = $customeremail = ($post['emailId']);
        $leadId = ($post['leadId']);
        $ccemail = (isset($post['ccemail']) && !empty($post['ccemail'])) ? $post['ccemail'] : '';
        $mailToCC = explode(',', $ccemail);
        $customername = ($post['customername']);
        $remarks = ($post['remarks']);
        $CustomerSysId = $customerRcord = ($post['CustomerSysId']);
        $customerSysIdSel = ($post['customerSysIdSel']);
        $senderEmailID = $sendersEmailId = trim($post['senderEmailID']);
        $SearchTraceId = ($post['SearchTraceId']);
        $agentsysID = ($post['aId']);
        $agencySysID = $this->intLoggedinAgencyId;
        $getAgencyDetail = $this->_crmcustomerObj->GetAgencyDetailById($agencySysID);
        $arrAgentDetail = $this->_crmcusttravelplan->getAgentDetails($this->intLoggedinUserId);
        $objFlight = new Travel_Model_TblFlight();
        $objAirport = new Travel_Model_TblAirport();
        $FlightTempData = $objFlight->GetFlightTempData($SearchTraceId);
        $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
        $sessionFlightSearchParams = $arrUrlData['sessionFlightSearchParams'];
        $route = $tripType = $JourneyType = $sessionFlightSearchParams['route'];
        $sourceCityText = ($route == 3) ? $sessionFlightSearchParams['sourceCityText'][0] : $sessionFlightSearchParams['sourceCityText'];
        $destinationCityText = ($route == 3) ? $sessionFlightSearchParams['destinationCityText'][0] : $sessionFlightSearchParams['destinationCityText'];
        $Origincity = $sessionFlightSearchParams['from'];
        $DestinationCity = $sessionFlightSearchParams['to'];
        $IsInterNational = $sessionFlightSearchParams['interNationalSearch'];
        $fromName = (isset($getAgencyDetail['DisplayName']) && !empty($getAgencyDetail['DisplayName'])) ? trim($getAgencyDetail['DisplayName']) : trim(trim($getAgencyDetail['Title']));
        $emailId = trim($emailId);
        $mailCustmail = array(trim($emailId));
        $emailSendId = $sendersEmailId = !empty($sendersEmailId) ? $sendersEmailId : trim($arrAgentDetail['EmailId']);
        $PrimaryEmailWhatsApp = trim($arrAgentDetail['EmailId']);
        $bookingAllowed = !empty($post['bookingAllowed']) ? $post['bookingAllowed'] : 0;
        $IsSendMail = !empty($post['IsSendMail']) ? $post['IsSendMail'] : 0;
        $IsHideRefundable = !empty($post['IsHideRefundable']) ? $post['IsHideRefundable'] : 0;
        $IsOwnApi = isset($this->agencyDetails['IsCheckWallet']) ? $this->agencyDetails['IsCheckWallet'] : false;
        // echo "<pre>getflightData";
        // print_r(($selectedDataformail));
        // die;
        $this->CurrencyRate = $sessionFlightSearchParams['CurrencyRate'];
        $this->CurrencyTitle = $sessionFlightSearchParams['CurrencyTitle'];
        $this->CurrencyId = $sessionFlightSearchParams['CurrencyId'];

        $crmcusttravelplan = new Travel_Model_CRM_CustomerTravelPlan();
        $currencyTypeArr = $crmcusttravelplan->GetCurrencyByCurrencyType($this->CurrencyId);
        $CurrencyIcon = (!empty($currencyTypeArr['Icon']) && trim($currencyTypeArr['Symbol']) == 'GBP') ? '£' : trim($currencyTypeArr['Symbol']);

        $intCountryCode = ($route == 3) ? $sessionFlightSearchParams['intCountryCode'][0] : $sessionFlightSearchParams['intCountryCode'];
        $B2BType = (int) $sessionFlightSearchParams['B2BType'];
        $CustomerSysId = $sessionFlightSearchParams['CustomerSysId'];
        $AgencySysId = isset($sessionFlightSearchParams['AgencySysId']) ? $sessionFlightSearchParams['AgencySysId'] : '';

        $Salutation = isset($this->agencyDetails['Salutation']) ? $this->agencyDetails['Salutation'] : '';
        $showTitle = isset($this->agencyDetails['showTitle']) ? $this->agencyDetails['showTitle'] : false;

        $getMarkupB2B = $this->getMarkupB2B($intCountryCode, $CustomerSysId, $B2BType);
        
        $getMarkup = $getMarkupB2B;
        $TaxPercentage = 0;
        if($this->agencyDetails['TaxLabelId'] > 0){
            $TaxPercentage = isset($getMarkup['arrApiServiceTax'][0]['TaxPercentage']) ? (float) $getMarkup['arrApiServiceTax'][0]['TaxPercentage'] : 0;
        }
        
        $index = 0;
        $getflightData = [];
        $FlightData = [];
        $TripType = 1;
        if ($selectedDataformail) {
            foreach ($selectedDataformail as $key => $values) {
                foreach ($values as $val) {
                    //As per gaurav sir
                    $markup = isset($addMarkup[$index]) ? $addMarkup[$index] : 0;
                    $discount = isset($discountvalue[$index]) ? $discountvalue[$index] : 0;
                    // $markupgst = ($markup - $discount);
                    $arrServiceTaxOnNetPayable = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->calculateServiceTax($markup, $TaxPercentage);

                    $MarkupArrayServiceTax = (!empty($arrServiceTaxOnNetPayable['serviceTaxAmount']) && $arrServiceTaxOnNetPayable['serviceTaxAmount'] > 0) ? $arrServiceTaxOnNetPayable['serviceTaxAmount'] : 0;

                    $val['ExtraMarkup'] = (float) $markup;
                    $val['ExtraMarkupOnGST'] = (float) $MarkupArrayServiceTax;
                    $val['DiscountValue'] = (float) $discount;
                    $val['DiscountCoupon'] = ($discount > 0) ? 1 : 0;
                    if($val['JourneyType'] == 3 && $val['ICSourceSysId'] == 7 && (int)$val['IsInternational'] == 0){
                        $val['TripType'] = $TripType;
                    }
                    $getflightData[] = $val;
                    $FlightData[($key + 1)][] = $val;
                    $index++;
                }
                $TripType++;
            }
        }
        //echo "<pre>";print_r($getflightData);die;
        $departure_dates_string = $sessionFlightSearchParams['departure_dates'];
        if ($route == 3) {
            $departure_dates_string = $sessionFlightSearchParams['departure_dates'][0];
        }

        $editLeadId = $sessionFlightSearchParams['editLeadId'];
        $oneway_origin_text = isset($sessionFlightSearchParams['oneway_origin_text']) ? $sessionFlightSearchParams['oneway_origin_text'] : $sessionFlightSearchParams['sourceCityAirportCode'];
        $oneway_destination_text = isset($sessionFlightSearchParams['oneway_destination_text']) ? $sessionFlightSearchParams['oneway_destination_text'] : $sessionFlightSearchParams['destinationCityAirportCode'];
        $sourceCityId = $sessionFlightSearchParams['sourceCityId'];
        $destinationCityId = $sessionFlightSearchParams['destinationCityId'];
        if ($route == 3) {
            if (is_array($oneway_origin_text)) {
                $oneway_origin_text = $oneway_origin_text[0];
            }
            if (is_array($oneway_destination_text)) {
                $oneway_destination_text = $oneway_destination_text[0];
            }
            if (is_array($sourceCityId)) {
                $sourceCityId = $sourceCityId[0];
            }
            if (is_array($destinationCityId)) {
                $destinationCityId = $destinationCityId[0];
            }
        }

        $flight_class = $sessionFlightSearchParams['flight_class'];
        $return_dates_string = $sessionFlightSearchParams['return_dates'];
        $adultCount = $adults = ($sessionFlightSearchParams['adults']);
        $childCount = $child = ($sessionFlightSearchParams['child']);
        $infantCount = $infant = ($sessionFlightSearchParams['infant']);
        $intMemberCount = ($adultCount + $childCount + $infantCount);
        $adultDetails = ($sessionFlightSearchParams['adults']) ? $sessionFlightSearchParams['adults'] : '';
        $childDetails = ($sessionFlightSearchParams['child'] > 0) ? ', ' . $sessionFlightSearchParams['child'] . ' Child(s)' : '';
        $InfantDetails = ($sessionFlightSearchParams['infant'] > 0) ? ', ' . $sessionFlightSearchParams['infant'] . ' Infant(s)' : '';
        $whatsappmessageFlightWhatAppAPI = $whatsappmessageFlight = '';
        $NoofPax = '%0a*No. of Pax:* ' . $adultDetails . ' Adult(s)' . $childDetails . $InfantDetails;
        $NoofPaxwp = '<p><strong>No. of Pax:</strong> ' . $adultDetails . ' Adult(s)' . $childDetails . $InfantDetails .'</p>';
        $navarrow = ($tripType == 1) ? "→" : "⇄";
        if ($route == 3) {
            $navarrow = "→";
        }
//         echo '<pre>';print_r($FlightData);die;
        foreach ($FlightData as $getflightKey => $flightDatas) {
            $FareClass = $flightDatas[0]['FairRules'][0]['FareClass'];
            $FareClass_ = ($FareClass) ? '%0a*Booking Class:* ' . $FareClass . '%0a' : '';
            $FareClass_wp = ($FareClass) ? '<p><strong>Booking Class:</strong> ' . $FareClass . '</p' : '';
            $finalHtml = $finalHtmlwp = '';
            $kk = 0;
            if ($getflightKey == 1) {
                $TravelDate = ($departure_dates_string) ? '%0a*Travel Date:* ' . $departure_dates_string . '%0a' : '';
                $TravelDatewp = ($departure_dates_string) ? '<p><strong>Travel Date:</strong> ' . $departure_dates_string . '</p>' : '';
            } else {
                $TravelDate = ($return_dates_string) ? '%0a*Travel Date:* ' . $return_dates_string . '%0a' : '';
                $TravelDatewp = ($return_dates_string) ? '<p><strong>Travel Date:</strong> ' . $return_dates_string . '</p>' : '';
            } 
            
             
            foreach ($flightDatas as $dKey => $fVal) {
                if (count($flightDatas) > 1) {
                    $finalHtml .= '%0a*' . ($dKey + 1) . '.* ';
                    $finalHtmlwp .= '<strong>' . ($dKey + 1) . '.</strong> ';
                } else {
                    $finalHtml .= '%0a';
                }

                $Baggage = [];
                if ($fVal['Segments']) {
                    foreach ($fVal['Segments'] as $value) {
                        $Baggage[] = $value['originAirportCode'] . '-' . $value['destinationAirportCode'] . ' → Checkin ' . $value['CheckinBaggage'] . ' | Cabin ' . $value['CabinBaggage'];
                    }
                }
                $imploadeAdd = implode('%0a', $Baggage);
                $imploadeAddwp = implode('<br>', $Baggage);
                $routeDetailMulti =  $routeOnlyMulti = '';
                if($route == 3 && $IsInterNational == 1 && isset($fVal['FD'])){
                    if ($fVal['FD']) {
                        foreach ($fVal['FD'] as $fdvalue) {
                                $FromUTCTimeM = date('d M y H:i', strtotime($fdvalue['FromUTCTime']));
                                $ToUTCTimeM = date('d M y H:i', strtotime($fdvalue['ToUTCTime']));
                                $FlightNumberM = trim($fdvalue['FlightNumber']);
                                $IsRefundableTxtM = ($IsHideRefundable == 0) ? trim($fdvalue['IsRefundableTxt']) : '';
                                $routeDetailMulti .= ' %0a*' . trim($fdvalue['AirlineName']) . ' (' . trim($FlightNumberM) . ') :*' . ' ' . $IsRefundableTxtM . ' ' ;
                                $routeDetailMulti .= '' . trim($fdvalue['SourceAirportCode']) . ' ' . $navarrow . ' ' . trim($fdvalue['DestAirportCode']) . ' on ' . $FromUTCTimeM . ' - ' . $ToUTCTimeM;
                                if($routeOnlyMulti != ''){
                                    $routeOnlyMulti .= ', ';
                                }
                                $routeOnlyMulti .= '' . trim($fdvalue['SourceAirportCode']) . ' ' . $navarrow . ' ' . trim($fdvalue['DestAirportCode']);
                        }
                    }
                }else if($route == 3 && isset($fVal['SegPro'])){
                    foreach ($fVal['SegPro'] as $fdvalue) {
                            $FromUTCTimeM = date('d M y H:i', strtotime($fdvalue['FromUTCTime']));
                            $ToUTCTimeM = date('d M y H:i', strtotime($fdvalue['ToUTCTime']));
                            $FlightNumberM = trim($fdvalue['FlightNumber']);
                            $IsRefundableTxtM = ($IsHideRefundable == 0) ? trim($fdvalue['IsRefundableTxt']) : '';
                            $routeDetailMulti .= ' %0a*' . trim($fdvalue['AirlineName']) . ' (' . trim($FlightNumberM) . ') :*' . ' ' . $IsRefundableTxtM . ' ' ;
                            $routeDetailMulti .= '' . trim($fdvalue['SourceAirportCode']) . ' ' . $navarrow . ' ' . trim($fdvalue['DestAirportCode']) . ' on ' . $FromUTCTimeM . ' - ' . $ToUTCTimeM;
                            if($routeOnlyMulti != ''){
                            $routeOnlyMulti .= ', ';
                            }
                            $routeOnlyMulti .= '' . trim($fdvalue['SourceAirportCode']) . ' ' . $navarrow . ' ' . trim($fdvalue['DestAirportCode']);
                    }
                }else if(isset($fVal['origin']['FromUTCTime'])){
                    $FromUTCTime = date('d M y H:i', strtotime($fVal['origin']['FromUTCTime']));
                    $ToUTCTime = date('d M y H:i', strtotime($fVal['origin']['ToUTCTime']));
                }else{
                    $FromUTCTime = date('d M y H:i', strtotime($fVal['FromUTCTime']));
                    $ToUTCTime = date('d M y H:i', strtotime($fVal['ToUTCTime']));
                } 
                //echo $routeDetailMulti;die;
                if ($tripType == 2 && $IsInterNational == 1) {
                    $IsRefundableTxt = ($IsHideRefundable == 0) ? $fVal['origin']['IsRefundableTxt'] : '';
                    $duration = $fVal['origin']['FlightDuration'];
                    $FlightNumber = trim($fVal['origin']['FlightNumber']) . ', ' . trim($fVal['destination']['FlightNumber']);
                    $SourceAirportCode = trim($fVal['origin']['SourceAirportCode']);
                    $DestAirportCode = trim($fVal['destination']['SourceAirportCode']);
                } else {
                    $IsRefundableTxt = ($IsHideRefundable == 0) ? $fVal['IsRefundableTxt'] : '';
                    $duration = $fVal['FlightDuration'];
                    $FlightNumber = trim($fVal['FlightNumber']);
                    $SourceAirportCode = trim($fVal['SourceAirportCode']);
                    $DestAirportCode = trim($fVal['DestAirportCode']);
                }
                 
                $ExtraMarkup__ = $fVal['ExtraMarkup'];
                $ExtraMarkupOnGST__ = $fVal['ExtraMarkupOnGST'];
                $DiscountValue__ = $fVal['DiscountValue'];
                if($routeDetailMulti != ''){
                    $routeDetail = $routeDetailMulti;
                }else{
                    $routeDetail = '' . trim($SourceAirportCode) . ' ' . $navarrow . ' ' . trim($DestAirportCode) . ' on ' . $FromUTCTime . ' - ' . $ToUTCTime;
                    if(trim($FlightNumber) != ''){
                        $finalHtml .= '*' . trim($fVal['AirlineName']) . ' (' . trim($FlightNumber) . ') :*' . ' ' . $IsRefundableTxt . ' ' ;
                        $finalHtmlwp .= '<p><strong>' . trim($fVal['AirlineName']) . ' (' . trim($FlightNumber) . ') :</strong>' . ' ' . $IsRefundableTxt . ' ' ;
                    }
                }
                
                $finalHtml .= $routeDetail . ' ' . $duration . '%0a' . $imploadeAdd . '%0a%0a*Total Cost:*  ' . trim($CurrencyIcon) . ' ' . number_format(($fVal['FairRules'][0]['PublishedFare'] + $ExtraMarkup__ + $ExtraMarkupOnGST__ - $DiscountValue__) / $intMemberCount, 2) . '/- Per person %0a';
                $finalHtmlwp .= $routeDetail . ' ' . $duration . '</p><p>' . $imploadeAddwp . '</p><p><strong>Total Cost:</strong>  ' . trim($CurrencyIcon) . ' ' . number_format(($fVal['FairRules'][0]['PublishedFare'] + $ExtraMarkup__ + $ExtraMarkupOnGST__ - $DiscountValue__) / $intMemberCount, 2) . '/- Per person </p>';
                $kk++;
            }
             
            
            $SourceAirportCodeN = isset($flightDatas[0]['SourceAirportCode']) ? $flightDatas[0]['SourceAirportCode'] : (isset($flightDatas[0]['origin']['SourceAirportCode']) ? $flightDatas[0]['origin']['SourceAirportCode'] : '');
            if(empty($SourceAirportCodeN) && $route == 3 && isset($flightDatas[0]['FD'])){
                $SourceAirportCodeN = $flightDatas[0]['FD'][0]['SourceAirportCode'];
            }
            if(empty($SourceAirportCodeN) && $route == 3 && isset($flightDatas[0]['SegPro'])){
                $SourceAirportCodeN = $flightDatas[0]['SegPro'][0]['SourceAirportCode'];
            }
             
             
            $objAirport->strAirportCode = $SourceAirportCodeN;
            
            $arrSourceCity = $objAirport->getAirportList(); 
            $SourcePlaceName = isset($arrSourceCity[0]['CityName']) ? $arrSourceCity[0]['CityName'] : '';
            
            $DestAirportCodeN = isset($flightDatas[0]['DestAirportCode']) ? $flightDatas[0]['DestAirportCode'] : (isset($flightDatas[0]['origin']['DestAirportCode']) ? $flightDatas[0]['origin']['DestAirportCode'] : '');
            if(empty($DestAirportCodeN) && $route == 3 && isset($flightDatas[0]['FD'])){
                $flightDatasR = array_reverse($flightDatas[0]['FD']);
                $DestAirportCodeN = $flightDatasR[0]['DestAirportCode'];
            }
            if(empty($DestAirportCodeN) && $route == 3 && isset($flightDatas[0]['SegPro'])){
                $flightDatasR = array_reverse($flightDatas[0]['SegPro']);
                $DestAirportCodeN = $flightDatasR[0]['DestAirportCode'];
            }
            
            $objAirport->strAirportCode =  $DestAirportCodeN;
            $arrDestinationCity = $objAirport->getAirportList();
            $DestPlaceName = isset($arrDestinationCity[0]['CityName']) ? $arrDestinationCity[0]['CityName'] : '';
            $OrigincityTitle = $SourcePlaceName . ' (' . trim($flightDatas[0]['SourceAirportCode']) . ')';
            $DestinationCityTitle = $DestPlaceName . ' (' . trim($flightDatas[0]['DestAirportCode']) . ')';

            if ($getflightKey == 1) {
                $SourcePlaceNameW = $flightDatas[0]['SourcePlaceName'];
                $DestPlaceNameW = $flightDatas[0]['DestPlaceName'];
            } else {
                $SourcePlaceNameW = $flightDatas[0]['DestPlaceName'];
                $DestPlaceNameW = $flightDatas[0]['SourcePlaceName'];
            } 
            if($SourcePlaceName == ''){
                $SourcePlaceName = $SourceAirportCodeN;
            }
            if($DestPlaceName == ''){
                $DestPlaceName = $DestAirportCodeN;
            }
            $SourceDestPlaceName  = "*$SourcePlaceName* *$navarrow* *$DestPlaceName*"; 
            if($routeOnlyMulti != ''){
                $SourceDestPlaceName = $routeOnlyMulti;
            }
            $whatsappmessageFlight .= "%0a%0a*------* $SourceDestPlaceName *------*%0a $NoofPax $TravelDate $FareClass_ $finalHtml ";
            
            $whatsappmessageFlightClip .= "<p><strong>------ $SourcePlaceName $navarrow $DestPlaceName ------ </strong></p><p> $NoofPaxwp $TravelDatewp $FareClass_wp $finalHtmlwp </p>";
            $whatsappmessageFlightWhatAppAPI .= " $FareClass_ $finalHtml ";
        }
        
        if (trim($remarks) != '') {
            $whatsappmessageFlight .= "%0a*Remark:* $remarks";
            $whatsappmessageFlightClip .= "<p><strong>Remark:</strong> $remarks</p>";
            $whatsappmessageFlightWhatAppAPI .= "%0a*Remark:* $remarks";
        }
//         $response = array('success' => true, 'whatsapp' => $whatsappmessageFlight, 'contactno' => $countrycode . $mobilenumber);
//         echo json_encode($response);
//         exit;


        $roomjson = array();
        $childcount = $child;
        $roomjson[1]['route'] = $route;
        $roomjson[1]['Adult'] = $adults;
        $roomjson[1]['Child'] = $child;
        $roomjson[1]['Infant'] = $infant;
        $roomjson[1]['ChildAge_1'] = $infant;
        $roomjson[1]['departuredate'] = ($route == 3) ? $sessionFlightSearchParams['departure_dates'] : $departure_dates_string;
        $roomjson[1]['returndate'] = ($route == 2) ? $return_dates_string : null;
        $roomjson[1]['fromaircode'] = $oneway_origin_text;
        $roomjson[1]['toaircode'] = $oneway_destination_text;
        $roomjson[1]['airclass'] = $flight_class;
        $RoomInfoJson = json_encode($roomjson);

        $leadID = trim($editLeadId);

        $SearchTraceId = $TraceId = isset($getflightData[0]['SearchTraceId']) ? $getflightData[0]['SearchTraceId'] : '';

        $FLData = [];
        $BaggageArr = [];
        $MealArr = [];
        $segment_ssr = [];
        $baggageByPax = [];
        $Sectors = [];
        $BaseFare = 0;
        $PublishedFare = 0;
        $AgencyMarkUpINT_ = 0;
        $AgencyMarkUpGSTINT_ = 0;
        $CommissionEarnedAPI = 0;
        if ($getflightData) {
            foreach ($getflightData as $k => $value) {

                $ExtraMarkup = isset($value['ExtraMarkup']) ? $value['ExtraMarkup'] : 0;
                $ExtraMarkupOnGST = isset($value['ExtraMarkupOnGST']) ? $value['ExtraMarkupOnGST'] : 0;
                $value['FairRules'] = isset($value['FairRules'][0]) ? $value['FairRules'][0] : [];
                $BagPrice = 0;
                $MealPrice = 0;
                $SeatPrice = 0;
                $FareBreakdown_ = [];
                $GrossAmount = 0;
                $AgentMarkUp = 0;
                $TotalCommDiscount = 0;
                foreach ($value['FairRules']['FareBreakdown'] as $valueB) {
                    // echo '<pre>';print_r($valueB);
                    $baggageByPax[$valueB['PassengerType']]['Baggage'] = $valueB['Baggage'];
                    $baggageByPax[$valueB['PassengerType']]['CabinBaggage'] = $valueB['CabinBaggage'];
                    $FareBreakdown_[] = array(
                        "Currency" => $valueB['Currency'],
                        "PassengerCount" => $valueB['PassengerCount'],
                        "PassengerType" => $valueB['PassengerType'],
                        "BaseFare" => $valueB['BaseFare'],
                        "Tax" => isset($valueB['Tax']) ? ($valueB['Tax']) : (($valueB['TaxIN'])),
                        "OfferedFare" => ($valueB['OfferedFare']) ? $valueB['OfferedFare'] : 0,
                        "TotalFare" => $valueB['PublishedFare'],
                        "PublishedFare" => $valueB['PublishedFare'],
                        "TDSEarn" => $valueB['TDSEarn'],
                        "MF" => isset($valueB['TaxBR']['MF']) ? $valueB['TaxBR']['MF'] : $valueB['MF'],
                        "YQ" => isset($valueB['TaxBR']['YQ']) ? $valueB['TaxBR']['YQ'] : 0,
                        "AGST" => isset($valueB['TaxBR']['AGST']) ? $valueB['TaxBR']['AGST'] : $valueB['AGST'],
                        "MFT" => isset($valueB['TaxBR']['MFT']) ? $valueB['TaxBR']['MFT'] : $valueB['MFT'],
                        "OT" => isset($valueB['TaxBR']['OT']) ? $valueB['TaxBR']['OT'] : (($valueB['OT'])),
                        "YR" => isset($valueB['TaxBR']['YR']) ? $valueB['TaxBR']['YR'] : $valueB['YR'],
                        "CommissionEarned" => $valueB['CommissionEarned'],
                        "FixedMarkUp" => ($valueB['FixedMarkUp']) ? $valueB['FixedMarkUp'] : 0,
                        "GSTOnMarkUp" => ($valueB['GSTOnMarkUp']) ? $valueB['GSTOnMarkUp'] : 0,
                        "couponVal" => isset($valueB['couponVal']) ? $valueB['couponVal'] : 0,
                        "CommDiscount" => $valueB['CommDiscount'],
                        "AgentMarkUp" => isset($valueB['AgentMarkUp']) ? (($valueB['AgentMarkUp'])) : 0
                    );
                }
                $couponApply = isset($value['FairRules']['couponApply']) ? $value['FairRules']['couponApply'] : 0;
                $couponVal = 0;
                if ($couponApply == 1) {
                    $couponVal = isset($value['FairRules']['couponVal']) ? $value['FairRules']['couponVal'] : 0;
                }
                if($BaseFare == 0){
                    $BaseFare = (($value['FairRules']['BaseFare'] + $value['FairRules']['Tax']) - $couponVal);
                    $PublishedFare = ($value['FairRules']['PublishedFare'] - $couponVal + $ExtraMarkup + $ExtraMarkupOnGST);
                    $AgencyMarkUpINT_ = $value['FairRules']['FixedMarkUp'] + $ExtraMarkup;
                    $AgencyMarkUpGSTINT_ = $value['FairRules']['GSTOnMarkUp'] + $ExtraMarkupOnGST;
                    $CommissionEarnedAPI = ($value['FairRules']['CommissionEarned'] + $value['FairRules']['TDSEarn']);
                }
                

                $fareRuless = array(
                    "Currency" => $value['FairRules']['Currency'],
                    "BaseFare" => $value['FairRules']['BaseFare'],
                    "Tax" => isset($value['FairRules']['Tax']) ? (($value['FairRules']['Tax'])) : 0,
                    "PublishedFare" => ($value['FairRules']['PublishedFare']) ? $value['FairRules']['PublishedFare'] : 0,
                    "OfferedFare" => ($value['FairRules']['OfferedFare']) ? $value['FairRules']['OfferedFare'] : 0,
                    "CommissionEarned" => ($value['FairRules']['CommissionEarned']) ? (($value['FairRules']['CommissionEarned'])) : 0,
                    "FixedMarkUp" => ($value['FairRules']['FixedMarkUp']) ? $value['FairRules']['FixedMarkUp'] : 0,
                    "GSTOnMarkUp" => ($value['FairRules']['GSTOnMarkUp']) ? $value['FairRules']['GSTOnMarkUp'] : 0,
                    "CommDiscount" => ($value['FairRules']['CommDiscount']) ? (($value['FairRules']['CommDiscount'])) : 0,
                    "couponVal" => isset($value['FairRules']['couponVal']) ? (($value['FairRules']['couponVal'])) : 0,
                    "TDSEarn" => ($value['FairRules']['TDSEarn']) ? (($value['FairRules']['TDSEarn'])) : 0,
                    "fareIdentifier" => isset($value['FairRules']['fareIdentifier']) ? $value['FairRules']['fareIdentifier'] : '',
                    "Refundable" => isset($value['FairRules']['Refundable']) ? $value['FairRules']['Refundable'] : '',
                    "classOfBooking" => isset($value['FairRules']['classOfBooking']) ? $value['FairRules']['classOfBooking'] : '',
                    "AgentMarkUp" => 0,
                    "BagPrice" => isset($BagPrice) ? $BagPrice : 0,
                    "MealPrice" => isset($MealPrice) ? $MealPrice : 0,
                    "SeatPrice" => isset($SeatPrice) ? $SeatPrice : 0,
                    'ExtraMarkup' => $ExtraMarkup,
                    'ExtraMarkupOnGST' => $ExtraMarkupOnGST,
                    "FareBreakdown" => $FareBreakdown_
                );
                $segment_ = [];
                if ($value['Segments']) {
                    foreach ($value['Segments'] as $seg) {

                        if (isset($seg['BAGGAGE'])) {
                            foreach ($seg['BAGGAGE'] as $b => $bag) {
                                $BaggageArr[] = $bag;
                            }
                        }
                        if (isset($seg['MEAL'])) {
                            foreach ($seg['MEAL'] as $m => $meals) {
                                $MealArr[] = $meals;
                            }
                        }
                        $Sectors[] = $seg['originAirportCode'] . '-' . $seg['destinationAirportCode'];
                        $segment_[] = $segment_ssr[$seg['segmentid']] = array(
                            "id" => intval($seg['segmentid']),
                            "flight_booking_id" => '',
                            "TraceId" => $value['SearchTraceId'],
                            "segmentid" => intval($seg['segmentid']),
                            "segmentids" => isset($seg['segmentids']) ? intval($seg['segmentids']) : 0,
                            "isReturnSegment" => ($tripType == 3) ? (int)$seg['TripIndicator'] : $seg['isReturnSegment'],
                            "arrivingnextday" => $seg['arrivingnextday'],
                            "originAirportName" => $seg['originAirportName'],
                            "destinationAirportName" => $seg['destinationAirportName'],
                            "originCityName" => $seg['originCityName'],
                            "originCountryName" => $seg['originCountryName'],
                            "destinationCityName" => $seg['destinationCityName'],
                            "destinationCountryName" => $seg['destinationCountryName'],
                            "destinationAirportCode" => $seg['destinationAirportCode'],
                            "destinationArrTime" => date('Y-m-d H:i', strtotime($seg['destinationArrTime'])),
                            "SegFlightNumber" => $seg['SegFlightNumber'],
                            "AirlineCode" => $seg['AirlineCode'],
                            "AirlineName" => $seg['AirlineName'],
                            "FareClass" => $seg['FareClass'],
                            "cabinClass" => ($seg['cabinClass']) ? $seg['cabinClass'] : $value['FlightClass'],
                            "originAirportCode" => $seg['originAirportCode'],
                            "originDepTime" => date('Y-m-d H:i', strtotime($seg['originDepTime'])),
                            "CheckinBaggage" => !empty($seg['CheckinBaggage']) ? $seg['CheckinBaggage'] : $value['FairRules']['CheckinBaggage'],
                            "CabinBaggage" => !empty($seg['CabinBaggage']) ? $seg['CabinBaggage'] : $value['FairRules']['CabinBaggage'],
                            "IsBaggage" => isset($seg['IsBaggage']) ? $seg['IsBaggage'] : false,
                            "IsMealIncludes" => isset($seg['IsMealIncludes']) ? $seg['IsMealIncludes'] : false,
                            "Duration" => $seg['Duration'],
                            "GroundTime" => $seg['GroundTime'],
                            "NoOfSeatAvailable" => $seg['NoOfSeatAvailable'],
                            "FlightDuration" => $seg['FlightDuration'],
                            "LAYOVERDuration" => $seg['LAYOVERDuration'],
                            "LAYOVERCity" => $seg['LAYOVERCity'],
                            "DepTerminal" => $seg['DepTerminal'],
                            "ArrTerminal" => $seg['ArrTerminal'],
                            "filePath" => isset($seg['filePath']) ? $seg['filePath'] : '',
                            "SourceAirportCode" => $seg['originAirportCode'],
                            "DestAirportCode" => $seg['destinationAirportCode'],
                            "strArrivalDtTime" => $seg['strArrivalDtTime'],
                            "strDepartureDtTime" => $seg['strDepartureDtTime'],
                            "TravelDate" => $seg['originDepTime'],
                            "BagPrice" => 0,
                            "MealPrice" => 0,
                            "SeatPrice" => 0
                        );
                    }
                }
                //echo $tripType."<pre>";print_r($value);die;
                if ($tripType == 2 && $IsInterNational == 1) {
                    $value['FromUTCTime'] = $value['origin']['FromUTCTime'];
                    $value['ToUTCTime'] = $value['origin']['ToUTCTime'];
                    $value['SourceAirportCode'] = $value['origin']['SourceAirportCode'];
                    $value['DestAirportCode'] = $value['origin']['DestAirportCode'];
                    $value['IsRefundable'] = $value['origin']['IsRefundable'];
                    $value['FlightNumber'] = $value['origin']['FlightNumber'];
                    $value['AirlineName'] = $value['origin']['AirlineName'];
                    $value['IsLCC'] = $value['origin']['IsLCC'];
                } else if ($tripType == 3) {
                    if(isset($value['FD'][0])){
                        $value['FromUTCTime'] = $value['FD'][0]['FromUTCTime'];
                        $value['ToUTCTime'] = $value['FD'][0]['ToUTCTime'];
                        $value['SourceAirportCode'] = $value['FD'][0]['SourceAirportCode'];
                        $value['DestAirportCode'] = $value['FD'][0]['DestAirportCode'];
                        $value['FlightNumber'] = $value['FD'][0]['FlightNumber'];
                        $value['AirlineName'] = $value['FD'][0]['AirlineName'];
                        $value['IsLCC'] = $value['FD'][0]['IsLCC'];
                    }else if(isset($value['SegPro'][0])){
                        $value['FromUTCTime'] = $value['SegPro'][0]['FromUTCTime'];
                        $value['ToUTCTime'] = $value['SegPro'][0]['ToUTCTime'];
                        $value['SourceAirportCode'] = $value['SegPro'][0]['SourceAirportCode'];
                        $value['DestAirportCode'] = $value['SegPro'][0]['DestAirportCode'];
                        $value['FlightNumber'] = $value['SegPro'][0]['FlightNumber'];
                        $value['AirlineName'] = $value['SegPro'][0]['AirlineName'];
                        $value['IsLCC'] = $value['SegPro'][0]['IsLCC'];
                    }
                }

                $FLData[$k]['FlightNumber'] = $value['FlightNumber'];
                $FLData[$k]['AirlineName'] = $value['AirlineName'];
                $FLData[$k]['SourceAirportCode'] = $value['SourceAirportCode'];
                $FLData[$k]['DestAirportCode'] = $value['DestAirportCode'];
                $FLData[$k]['SupplierSysId'] = isset($value['SupplierSysId']) ? $value['SupplierSysId'] : 0;
                $FLData[$k]['BookingId'] = isset($value['SearchTraceId']) ? $value['SearchTraceId'] : '';
                $FLData[$k]['APIBookingId'] = isset($value['APIBookingId']) ? $value['APIBookingId'] : '';
                $FLData[$k]['IsLCC'] = $value['IsLCC'];
                $FLData[$k]['LocalFromTime'] = date('Y-m-d H:i', strtotime($value['FromUTCTime']));
                $FLData[$k]['LocalToTime'] = date('Y-m-d H:i', strtotime($value['ToUTCTime']));
                $FLData[$k]['ICSourceSysId'] = $value['ICSourceSysId'];
                $FLData[$k]['apiTraceId'] = $value['SearchTraceId'];
                $FLData[$k]['ApiResultIndex'] = $value['FairRules']['PriceID'];
                $FLData[$k]['JourneyType'] = $value['JourneyType'];
                $FLData[$k]['TripType'] = intval($value['TripType']);
                $FLData[$k]['IsRefundable'] = ($value['IsRefundable']) ? $value['IsRefundable'] : false;
                $FLData[$k]['IsInternational'] = $IsInterNational;

                $FLData[$k]['FairRules'] = $fareRuless;
                $FLData[$k]['Segments'] = $segment_;
                // $FLData[$k]['FARERULE'] = isset($FARERULE[$k]) ? $FARERULE[$k] : [];
            }
        }
//         echo '<pre>FLData';
//         print_r($FLData);

        $UserSysId = $sessionFlightSearchParams['UserSysId'];
        $MasterAgencySysId = $sessionFlightSearchParams['MasterAgencySysId'];
        $FlightBookingDataRiya = array(
            "FlightBookingData" => $FLData,
            "customer" => [],
            "roominfojson" => $roomjson,
            "Cities" => $oneway_origin_text . '-' . $oneway_destination_text,
            "IsHotelFromApi" => 1,
            "ICSourceSysId" => $FLData[0]['ICSourceSysId'],
            'AgencySysId' => $MasterAgencySysId,
            'AgentSysId' => $UserSysId,
            "SourcePlaces" => $oneway_origin_text,
            "DestinationPlaces" => $oneway_destination_text,
            "SourcePlaceSysId" => $sourceCityId,
            "DestinationPlacesSysId" => $destinationCityId,
            "BaseAmount" => $BaseFare,
            "PublishedFare" => $PublishedFare,
            "AgencyMarkUp" => $AgencyMarkUpINT_,
            "AgencyMarkUpGST" => $AgencyMarkUpGSTINT_,
            "AgentCommisionEarned" => $CommissionEarnedAPI,
            "AgentCommisionEarnedGST" => 0,
            "adults" => $adultCount,
            "childs" => $childCount,
            "infants" => $infantCount,
            "route" => $JourneyType,
            "email" => $emailId,
            "mobile" => $mobilenumber,
            "editLeadId" => $editLeadId,
            "CustomerSysId" => $CustomerSysId,
            'IsB2BQuery' => $B2BType,
            'B2BAgentSysId' => $UserSysId,
            'B2BAgencySysId' => $AgencySysId,
            'leadsource' => 'Agency',
            'IsB2BProposal' => $B2BType,
            'ExchangeCurrencyRate' => $this->CurrencyRate,
            'APIMode' => 0,
            'IsNewMigration' => 3,
            'IsOnlyProposal' => 1,
        );
//         echo "<pre>getflightData";
//         print_r(($FlightBookingDataRiya));
//         die;
        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        $URL = $this->baseUrl . '/gtxwebservices/flight-api';
        $GENERATE_FLIGHT_QUERY = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($FlightBookingDataRiya, $getData, $URL);
        $GTXQueryStatus = isset($GENERATE_FLIGHT_QUERY['status']) ? $GENERATE_FLIGHT_QUERY['status'] : false;
        $TPSysId = isset($GENERATE_FLIGHT_QUERY['arrIds']['TPSysId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['TPSysId'] : 0;
//         echo "<pre>GENERATE_FLIGHT_QUERY";
//         print_r(($GENERATE_FLIGHT_QUERY));
//         die;

        $sessionFlightSearchParams['bookingAllowed'] = $bookingAllowed;
        $arrUrlData['sessionFlightSearchParams'] = $sessionFlightSearchParams;
        $arrUrlData['GENERATE_FLIGHT_QUERY'] = $GENERATE_FLIGHT_QUERY;
        $tempData = array(
            'TraceId' => $SearchTraceId,
            'TPSysId' => $TPSysId,
            'APIBookingData' => json_encode($arrUrlData),
        );
        //echo "<pre> tempData".$SearchTraceId;
        // print_r(($tempData));
        $objFlight->deleteFlightTempData($SearchTraceId);
        $objFlight->insertFlightTempData($tempData);

        $bookingUrl = $originalurl = $this->view->baseUrl('flight-proposal-new/view-flight-proposal/searchID/' . ($SearchTraceId) . '/TPSys/' . $TPSysId . '/cust/1');
        if ($arrAgentDetail['IsB2CSite'] == 1) {
            $whatsLink = "detail/index/view/id/" . base64_encode($bookingUrl);
            $bookingUrl = $arrAgentDetail['Url'] . $whatsLink;
        } else if (($arrAgentDetail['IsB2CSite'] == 2) && ($arrAgentDetail['IsSiteType'] == 1)) {
            $whatsLink = "hellogtx/index.html?id=" . base64_encode($bookingUrl);
            $bookingUrl = $arrAgentDetail['Url'] . $whatsLink;
        } else if (($arrAgentDetail['IsB2CSite'] == 2) && ($arrAgentDetail['IsSiteType'] == 0)) {
            $whatsLink = "hellogtx/gtx.php?id=" . base64_encode($bookingUrl);
            $bookingUrl = $arrAgentDetail['Url'] . $whatsLink;
        }


        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'];
            }
        }
        $agencyDisplayName = $getAgencyDetail['DisplayName'];
        $sessionLogin_user = new Zend_Session_Namespace('sessionLogin_user');
        $firstname = $sessionLogin_user->FirstName ? $sessionLogin_user->FirstName . ' ' . $sessionLogin_user->LastName : 'Agent';
        $primarycontact = $sessionLogin_user->ContactNo1 ? ' ' . str_replace("+", "", trim($this->agencyDetails['countrycode'])) . $sessionLogin_user->ContactNo1 : 'N/A';
        $primarycontactwp = $sessionLogin_user->ContactNo1 ? ' ' . str_replace("+", "", trim($this->agencyDetails['countrycode'])) . $sessionLogin_user->ContactNo1 : 'N/A';

        $roundToOrigin = ($tripType == 2) ? 'to ' . $sourceCityText . ' (' . $Origincity . ')' : '';
        if ($bookingAllowed == 0) {
            $whatsappmessage = "*$Salutation $customername*,%0a%0aThanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlight  %0a%0aYou can call $firstname at $primarycontact or email at $PrimaryEmailWhatsApp or whatsapp me here.%0a%0aRegards %0a%0a$firstname, %0a$agencyDisplayName";
            $whatsappmessageClipBoard = "<strong>$Salutation $customername</strong>, <p>Thanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlightClip  <p>You can call $firstname at $primarycontactwp or email at $PrimaryEmailWhatsApp or whatsapp me here.</p><p>Regards </p><p>$firstname, </p><p>$agencyDisplayName</p>";
        } else {
            if ($IsOwnApi == 1) {
                $whatsappmessage = "*$Salutation $customername*,%0a%0aThanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlight  %0a%0aTo view flight details and *book online* click on the below link:%0a$bookingUrl %0a%0aYou can also call $firstname at $primarycontact or email at $PrimaryEmailWhatsApp or whatsapp me here.%0a%0aRegards %0a%0a$firstname, %0a$agencyDisplayName";
                $whatsappmessageClipBoard = "<strong>$Salutation $customername</strong>, <p>Thanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlightClip  </p><p>To view flight details and <strong>book online</strong> click on the below link: </p> <p><a href=".$bookingUrl." target='_blank'> $bookingUrl</a> </p><p>You can also call $firstname at $primarycontactwp or email at $PrimaryEmailWhatsApp or whatsapp me here.</p> <p>Regards </p><p>$firstname, <br>$agencyDisplayName";
            } else {
                $whatsappmessage = "*$Salutation $customername*,%0a%0aThanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlight  %0a%0aTo view flight details click on the below link:%0a$bookingUrl %0a%0aYou can also call $firstname at $primarycontact or email at $PrimaryEmailWhatsApp or whatsapp me here.%0a%0aRegards %0a%0a$firstname, %0a$agencyDisplayName";
                $whatsappmessageClipBoard = "<strong>$Salutation $customername</strong>,<p>Thanks for your flight query for $sourceCityText to $destinationCityText $roundToOrigin.$whatsappmessageFlight  </p><p>To view flight details click on the below link:</p><p><a href=".$bookingUrl." target='_blank'> $bookingUrl</a> </p><p>You can also call $firstname at $primarycontactwp or email at $PrimaryEmailWhatsApp or whatsapp me here.</p><p>Regards </p><p>$firstname, <br>$agencyDisplayName";
            }

            if ($route == 3) {
                $whatsappmessage = "*$Salutation $customername*,%0a%0aThanks for your flight query for multicity $whatsappmessageFlight  %0a%0aTo view flight details and *book online* click on the below link:%0a$bookingUrl %0a%0aYou can also call $firstname at $primarycontact or email at $PrimaryEmailWhatsApp or whatsapp me here.%0a%0aRegards %0a%0a$firstname, %0a$agencyDisplayName";
                $whatsappmessageClipBoard = "<strong>$Salutation $customername</strong>, <p>Thanks for your flight query for multicity $whatsappmessageFlight  </p><p>To view flight details and <strong>book online</strong> click on the below link: </p> <p><a href=".$bookingUrl." target='_blank'> $bookingUrl</a> </p> <p>You can also call $firstname at $primarycontactwp or email at $PrimaryEmailWhatsApp or whatsapp me here.</p><p>Regards </p><p>$firstname, <br>$agencyDisplayName";
            }
        }
        // echo "<pre>FlightData";
        // print_r(($FlightData));
        // $FARERULE = (isset($arrUrlData['FARERULE']) && !empty($arrUrlData['FARERULE'])) ? $arrUrlData['FARERULE'] : '';
        // $html = new Zend_View();
        // $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight-new/');
        // $html->assign(array('FlightBooking' => $getflightData, 'remarks' => $remarks, 'bookingUrl' => $bookingUrl, 'FlightData' => $FlightData, 'addMarkup' => $addMarkup, 'queryID' => $leadID, 'proposalId' => $leadID, 'bookingAllowed' => $bookingAllowed, 'TraceId' => $TraceId, 'sessionFlightSearchParams' => $sessionFlightSearchParams, 'customername' => $customername, 'arrAgentDetail' => $arrAgentDetail, 'getAgencyData' => $getAgencyDetail, 'agencySysID' => $this->intLoggedinAgencyId, 'CurrencyRate' => $this->CurrencyRate, 'CurrencyTitle' => $this->CurrencyTitle, 'baseUrl' => $this->baseUrl, 'IsHideRefundable' => $IsHideRefundable, 'IsOwnApi' => $IsOwnApi));
        // echo $bodyText = $html->render('shareonmail.phtml');
        // die;

        $currencyTypeArr = $crmcusttravelplan->GetCurrencyByCurrencyType($this->CurrencyId);
        // $CurrencyIcon = !empty($currencyTypeArr['Icon']) ? trim($currencyTypeArr['Icon']) : trim($currencyTypeArr['Symbol']);
        $CurrencyIcon = (!empty($currencyTypeArr['Icon']) && trim($currencyTypeArr['Symbol']) == 'GBP') ? '£' : trim($currencyTypeArr['Symbol']);
        $html = new Zend_View();
        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight/');
        $html->assign(array(
            'FlightBooking' => $getflightData,
            'remarks' => $remarks,
            'bookingUrl' => $bookingUrl,
            'FlightData' => $FlightData,
            'addMarkup' => $addMarkup,
            'queryID' => $leadID,
            'proposalId' => $leadID,
            'bookingAllowed' => $bookingAllowed,
            'TraceId' => $TraceId,
            'sessionFlightSearchParams' => $sessionFlightSearchParams,
            'customername' => $customername,
            'arrAgentDetail' => $arrAgentDetail,
            'getAgencyData' => $getAgencyDetail,
            'agencySysID' => $this->intLoggedinAgencyId,
            'CurrencyRate' => $this->CurrencyRate,
            'CurrencyTitle' => $this->CurrencyTitle,
            'baseUrl' => $this->baseUrl,
            'IsHideRefundable' => $IsHideRefundable,
            'IsOwnApi' => $IsOwnApi,
            'Salutation' => $Salutation,
            'showTitle' => $showTitle,
            'CurrencyIcon' => $CurrencyIcon
        ));

        $bodyText = $html->render('shareonmail.phtml');
        $subject = ucfirst(trim($customername)) . " your " . $sourceCityText . '' . " to " . $destinationCityText . '' . " flight details from " . trim($getAgencyDetail['DisplayName']);
        if ($route == 3) {
            $subject = ucfirst(trim($customername)) . " your multicity flight details from " . trim($getAgencyDetail['DisplayName']);
        }
        // echo $bodyText;die;
        $emailData = array(
            'fromEmail' => trim($emailSendId),
            'fromName' => trim($fromName),
            'subject' => $subject,
            'to' => explode(',', trim($emailId)),
            'bodyHtml' => $bodyText,
            'bodyText' => ''
        );

        $arrEmailStatisticsType = array_keys(unserialize(ARR_EMAIL_STATISTICS_TYPE));
        if (($sendersEmailId) && ($IsSendMail == 1)) {
            $emailDataToSender = array(
                'fromEmail' => trim($emailSendId),
                'fromName' => trim($fromName),
                'subject' => $subject,
                'to' => explode(',', $sendersEmailId),
                'bodyHtml' => $bodyText,
                'bodyText' => ''
            );
            $arrEmailStatistics = array(
                "TPSysId" => isset($TPSysId) ? $TPSysId : '0', //$lastID,
                "TypeSysId" => 1, // 1 For Email 2 For SMS
                "AgencySysId" => $this->intLoggedinAgencyId,
                "AgentSysId" => $this->intLoggedinUserId,
                "Title" => $bodyText,
                "Source" => $arrEmailStatisticsType[0], // 1 For Fresh Proposals
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => date('Y-m-d H:s:i')
            );
            //$this->mailSentByElastice($emailDataToSender, $arrEmailStatistics, 1, 0);
        }

        if (!empty($mailToCC) && ($IsSendMail == 1)) {
            $emailDataToCC = array(
                'fromEmail' => trim($emailSendId),
                'fromName' => trim($fromName),
                'subject' => $subject,
                'to' => $mailToCC,
                'bodyHtml' => $bodyText,
                'bodyText' => ''
            );
            $arrEmailStatistics = array(
                "TPSysId" => isset($TPSysId) ? $TPSysId : '0', //$lastID,
                "TypeSysId" => 1, // 1 For Email 2 For SMS
                "AgencySysId" => $this->intLoggedinAgencyId,
                "AgentSysId" => $this->intLoggedinUserId,
                "Title" => $bodyText,
                "Source" => $arrEmailStatisticsType[0], // 1 For Fresh Proposals
                "Status" => 0,
                "RefSysId" => "",
                "RefSysStatus" => "",
                "CreateDate" => date('Y-m-d H:s:i')
            );
            //$this->mailSentByElastice($emailDataToCC, $arrEmailStatistics, 1, 0);
        }
        $arrEmailStatistics = array(
            "TPSysId" => isset($TPSysId) ? $TPSysId : '0', //$lastID,
            "TypeSysId" => 1, // 1 For Email 2 For SMS
            "AgencySysId" => $this->intLoggedinAgencyId,
            "AgentSysId" => $this->intLoggedinUserId,
            "Title" => $bodyText,
            "Source" => $arrEmailStatisticsType[0], // 1 For Fresh Proposals
            "Status" => 0,
            "RefSysId" => "",
            "RefSysStatus" => "",
            "CreateDate" => date('Y-m-d H:s:i')
        );

        $arrEmailStatisticsAgent = $arrEmailStatistics;
        $arrEmailStatisticsAgent["Source"] = $arrEmailStatisticsType[2];
        if ($IsSendMail == 1) {
            if (!empty($mailToCC)) {
                if (!empty($sendersEmailId)) {
                    $ccmail = array_merge($mailToCC, [$sendersEmailId]);
                } else {
                    $ccmail = $mailToCC;
                }
                $dddd = $this->mailSentByElastice($emailData, $arrEmailStatistics, 1, $CustomerSysId, $ccmail);
            } else {
                $dddd = $this->mailSentByElastice($emailData, $arrEmailStatistics, 1, $CustomerSysId, [$sendersEmailId]);
            }
        }
//        echo "<pre>";print_r($dddd);die;
        if (($getAgencyDetail['IsWhatsApp'] == 1) && trim($countrycode) != '') {
            $agencyDisplayName = trim($getAgencyDetail['DisplayName']);
            $AgentName = trim($arrAgentDetail['FirstName']) . ' ' . trim($arrAgentDetail['LastName']);
            $primarycontact = trim($arrAgentDetail['ContactNo1']);
            $SecurityKey = $getAgencyDetail['SecurityKey'];
            //$objCustomerTravPlan = new Travel_Model_CRM_CustomerTravelPlan();
            $adults = $sessionFlightSearchParams->params['adults'];
            $child = $sessionFlightSearchParams->params['child'];
            $infant = $sessionFlightSearchParams->params['infant'];
            $TotalPax = (int) ($adults + $child + $infant);
            if ($route == 1) {
                $TripTypetxt = 'One Way';
            } elseif ($route == 2) {
                $TripTypetxt = 'Round trip';
            } elseif ($route == 3) {
                $TripTypetxt = 'Multicity';
            }
            $FlightDetails = "";
            foreach ($FlightData as $JourneyType => $Dataval) {
                $SourceAirportCode = $Dataval[0]['SourceAirportCode'];
                $DestAirportCode = $Dataval[0]['DestAirportCode'];
                $IsInternational = $Dataval[0]['IsInternational'];
                $TripType = $Dataval[0]['TripType'];
                $FareClass = $Dataval[0]['FairRules'][0]['FareClass'];
                if ($JourneyType == 1) {
                    $Sector = "Onward ($SourceAirportCode - $DestAirportCode) $FareClass";
                } else if ($JourneyType == 2 && $IsInternational == '') {
                    $Sector = "Return ($SourceAirportCode - $DestAirportCode) $FareClass";
                } else {
                    if ($strFlightRoute == 3) {
                        if ($IsInternational == 1) {
                            $Sector = "Onward $FareClass";
                        } else {
                            $Sector = "Onward ($SourceAirportCode - $DestAirportCode) $FareClass";
                        }
                    } else if ($JourneyType == 2 && $IsInternational == 1) {
                        $Sector = "";
                    } else {
                        $Sector = "$SourceAirportCode ⇄ $DestAirportCode";
                    }
                }

                if ($Dataval) {
                    $d = 1;
                    foreach ($Dataval as $kkkk => $Data) {
                        $ExtraMarkup = isset($Data['ExtraMarkup']) ? (float) $Data['ExtraMarkup'] : 0;
                        $ExtraMarkupOnGST = isset($Data['ExtraMarkupOnGST']) ? (float) $Data['ExtraMarkupOnGST'] : 0;
                        $DiscountValue = isset($Data['DiscountValue']) ? (float) $Data['DiscountValue'] : 0;
                        $PublishedFare = isset($Data['FairRules'][0]['PublishedFare']) ? (float) $Data['FairRules'][0]['PublishedFare'] : 0;
                        $FlightData_ = isset($Data['FlightData']) ? $Data['FlightData'] : [];

                        $FInalFare = number_format((($PublishedFare + $ExtraMarkup + $ExtraMarkupOnGST - $DiscountValue) / $intMemberCount), 2);
                        $FlightDetails .= "Flight $d:-";
                        $FlightDetails .= " " . $Data['origin']['AirlineName'] . " (" . $Data['origin']['FlightNumber'] . ")   " . $Data['origin']['SourceAirportCode'] . " Non-stop" . $Data['origin']['DestAirportCode'];
                        $FlightDetails .= " Price:" . $CurrencyIcon . " (" . $FInalFare . ") /- Per Person";
                        $d++;
                    }
                }
            }
            $Sector = $SourcePlaceName . ' ' . $navarrow . ' ' . $DestPlaceName;
            $whatsappData = array(
                'SecurityKey' => $SecurityKey,
                'CustomerName' => $customername,
                'CustomerMobile' => trim($countrycode) . '' . trim($mobilenumber),
                'AgencyName' => $agencyDisplayName,
                'TripType' => $TripTypetxt,
                'Sector' => $Sector,
                'FlightDetails' => str_replace('%0a', '\n', $whatsappmessageFlightWhatAppAPI),
                'bookinglink' => $whatsLink,
                'TravelDate' => $departure_dates_string,
                'Travellers' => $intMemberCount,
                'AgentName' => $AgentName,
                'AgentContactNo' => $primarycontact,
            );

            $dsdsdsdsd = $this->_crmcusttravelplan->sendFlightProposalMessage($whatsappData);
        }
        $response = array('success' => true, 'whatsapp' => $whatsappmessage, 'contactno' => $countrycode . $mobilenumber, 'whatsappClipBoard' => $whatsappmessageClipBoard);
        echo json_encode($response);
        exit;
        // echo "<pre>";
        // print_r(($whatsappmessage));
        // print_r(($FlightData));
        // print_r(($post));
        // die('wwwww');
    }

    public function getMarkupB2B($intCountryCode, $CustomerSysId, $B2BType) {
        if ($intCountryCode) {
            $arrAgentDetail = $this->_crmcusttravelplan->getAgentDetails($this->intLoggedinUserId);

            if ($B2BType) {
                $crmcustomerObj = new Travel_Model_CRM_Customer();
                $customerDetails = $this->_crmcustomerObj->GetAgencyCustomerById($CustomerSysId);
                $AgencySysId__ = isset($customerDetails['AgencySysId']) ? $customerDetails['AgencySysId'] : 0;
                $B2bAgencyDetailById = $crmcustomerObj->GetAgencyDetailById($AgencySysId__);
                $B2CAgencySysIdKey = $arrAgentDetail['SecurityKey'];
                $B2BAgencySysIdKey = $B2bAgencyDetailById['SecurityKey'];
                $apiDataIV = array(
                    "B2BAgencySysIdKey" => $B2BAgencySysIdKey,
                    "B2CAgencySysIdKey" => $B2CAgencySysIdKey,
                    "MasterAgencySysId" => $this->intLoggedinAgencyId,
                    "PlanType" => 1,
                );
            } else {
                $apiDataIV = array(
                    'B2CAgencySysIdKey' => $this->agencyDetails['SecurityKey'],
                    'PlanType' => 1,
                    'IsB2C' => 1,
                    'MasterAgencySysId' => $this->intLoggedinAgencyId,
                    'IsB2CLoggedIn' => 0,
                );
            }
            $model = new Gtxwebservices_Model_Webservices();
            $result = json_decode($model->getMarkupAndServiceTaxNew($apiDataIV), true);
            if (!empty(($intCountryCode)) && ($intCountryCode) != "IN") {
                $intAirType = 2;
            } else {
                $intAirType = 1;
            }
            $arrAgencyMarkups = [];
            if ($result['data']) {
                foreach ($result['data'] as $k => $vl) {
                    $ItemSourceType = $vl['ItemSourceType'];
                    if ($intAirType == $ItemSourceType) {
                        $arrAgencyMarkups[$k] = $vl;
                        $arrAgencyMarkups[$k]['CommssionType'] = 2;
                        $arrAgencyMarkups[$k]['CommssionVal'] = $vl['Commission'];
                        $arrAgencyMarkups[$k]['StdMarkUpPer'] = $vl['MarkUpValue'];
                    }
                }
            }
            $TaxSetting = [];
            if ($result['TaxSetting']) {
                foreach ($result['TaxSetting'] as $ks => $val) {
                    $TaxSetting[$k] = $val;
                    $TaxSetting[$k]['Percentage'] = $val['TaxPercentage'];
                }
            }
            return ['arrAgencyMarkups' => $arrAgencyMarkups, 'arrApiServiceTax' => array_values($TaxSetting)];
        }
    }

    public function offlineFlightBookAction() {
        $param = $this->getRequest()->getParams();
        $paramArray = $this->getRequest()->getParams();
        $fareRules = isset($paramArray['fareRules']) ? $paramArray['fareRules'] : '';
        $journeytype = isset($param['journeytype']) ? $param['journeytype'] : 1;
        $isquery = isset($param['isquery']) ? $param['isquery'] : 0;
        $ispackage = isset($param['ispackage']) ? $param['ispackage'] : '';

        $cancellationPolicy = isset($paramArray['cancellationPolicy']) ? $paramArray['cancellationPolicy'] : '';
        $internalRemarks = isset($paramArray['internalRemarks']) ? $paramArray['internalRemarks'] : '';
        if (isset($paramArray["data"])) {
            parse_str(urldecode(base64_decode($paramArray["data"])), $param);
        }
        $objFlight = new Travel_Model_TblFlight();
        $objTblSupplier = new Travel_Model_TblSupplier();
        $crmcustomerObj = new Travel_Model_CRM_Customer();

        $uid = $this->getRequest()->getParam("uid");
        $intTPSysId = base64_decode($this->getRequest()->getParam("id"));
        $index = ($this->getRequest()->getParam("index")) ? $this->getRequest()->getParam("index") : '';
        $keySector = ($this->getRequest()->getParam("keySector")) ? json_decode($this->getRequest()->getParam("keySector"), 1) : '';
        $indexround = ($this->getRequest()->getParam("indexround")) ? $this->getRequest()->getParam("indexround") : '';
        $versionId = ($this->getRequest()->getParam("version"));
        $CurrentUrl = $this->baseUrl . "/flight-new/offline-flight-book/id/" . base64_encode($intTPSysId);

        if ($ispackage == 1) {
            $CurrentUrl = $CurrentUrl . '/ispackage/' . $ispackage;
        }
        if ($isquery == 1) {
            $CurrentUrl = $CurrentUrl . '/isquery/' . $isquery;
        }
        $this->view->ids = $intTPSysIdEncode = base64_encode($intTPSysId);
        $this->view->CurrentUrl = $CurrentUrl;
        $this->view->index = $index;
        $this->view->indexround = $indexround;
        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        $B2B = [];
        $FareBreakdownarr = [];
        $interNationalSearch = 0;
        $B2BAgencySysId = 0;
        $MasterTPSysId = 0;
        $TotalPax = 0;
        $Adult = 0;
        $Child = 0;
        $Infant = 0;
        $FareBreak = [];
        $Segments = [];
        $ChooseMoreOptions = array();
        if ($isquery == 1) {
            // $arrCustomerInvoiceData = $objFlight->GetAgencyCustomerDetailsForBookingQuery($intTPSysId); 
            $GetTravelPlanType = $this->_crmcusttravelplan->GetTravelPlanType($intTPSysId, 'Query');
            $CustomerSysId = isset($GetTravelPlanType['CustomerSysId']) ? $GetTravelPlanType['CustomerSysId'] : 0;
            $IsB2BProposal = isset($GetTravelPlanType['IsB2BProposal']) ? $GetTravelPlanType['IsB2BProposal'] : 0;
            $B2BAgencySysId = isset($GetTravelPlanType['CustomerAgencySysId']) ? $GetTravelPlanType['CustomerAgencySysId'] : 0;
            $RoomInfoJson = isset($GetTravelPlanType['RoomInfoJson']) ? json_decode($GetTravelPlanType['RoomInfoJson'], 1) : [];
            $toaircode = '';
            $fromaircode = '';
            $departuredate = date('d/m/Y');
            $returndate = date('d/m/Y');
            if ($RoomInfoJson) {
                foreach ($RoomInfoJson as $value) { 
                    
                    $journeytype = ($journeytype > 1) ? $journeytype : $value['route'];
                    $Adult += isset($value['Adult']) ? $value['Adult'] : 1;
                    $Child += isset($value['Child']) ? $value['Child'] : 0;
                    $Infant += isset($value['Infant']) ? $value['Infant'] : 0;
                    $departuredate = isset($value['departuredate']) ? $value['departuredate'] : '';
                    $returndate = isset($value['returndate']) ? $value['returndate'] : '';
                    $fromaircode = isset($value['fromaircode']) ? $value['fromaircode'] : '';
                    $toaircode = isset($value['toaircode']) ? $value['toaircode'] : '';
                }
                $TotalPax = $Adult + $Child + $Infant;
                //echo "<pre>";print_r($departuredate);die;
                if($journeytype == 3){
                    
                    
                    for ($i = 0; $i < $journeytype; $i++) {
                        $fromaircodeM = isset($fromaircode[$i]) ? $fromaircode[$i] : '';
                        $toaircodeM = isset($toaircode[$i]) ? $toaircode[$i] : '';
                        $departuredateM = isset($departuredate[$i]) ? $departuredate[$i] : '';
                        $departuredateM_ = Zend_Controller_Action_HelperBroker::getStaticHelper("DateFormat")->cal2Db($departuredateM, 'd/m/y');
                        if(!empty($fromaircodeM)){
                        $Segments[$i] = [[
                            "OriginAirportCode" => $fromaircodeM,
                            "DestAirportCode" => $toaircodeM,
                            "originDepTime" => $departuredateM_ . date(' H:i'),
                            "destinationArrTime" => $departuredateM_ . date(' H:i'),
                        ]]; 
                        
                            $ChooseMoreOptions[$fromaircodeM.'-'.$toaircodeM] = []; 
                        } 
                        
                    }
                      
                    $fromaircode = isset($fromaircode[0]) ? $fromaircode[0] : '';
                    $toaircode = isset($toaircode[0]) ? $toaircode[0] : '';
                }else{
                    $departuredate_ = Zend_Controller_Action_HelperBroker::getStaticHelper("DateFormat")->cal2Db($departuredate, 'd/m/y');
                    $returndate_ = Zend_Controller_Action_HelperBroker::getStaticHelper("DateFormat")->cal2Db($returndate, 'd/m/y');
                    for ($i = 0; $i < $journeytype; $i++) {
                        $Segments[$i] = [[
                            "OriginAirportCode" => ($i == 0) ? $fromaircode : $toaircode,
                            "DestAirportCode" => ($i == 0) ? $toaircode : $fromaircode,
                            "originDepTime" => ($i == 0) ? $departuredate_ . date(' H:i') : $returndate_ . date(' H:i'),
                            "destinationArrTime" => ($i == 0) ? $departuredate_ . date(' H:i') : $returndate_ . date(' H:i'),
                        ]]; 
                        if($i == 0){
                            $ChooseMoreOptions[$fromaircode.'-'.$toaircode] = []; 
                        }else{
                            $ChooseMoreOptions[$toaircode.'-'.$fromaircode] = []; 
                        }
                        
                    }
                }
                
                //echo "<pre>";print_r($Segments);die;
            }

//             echo "<pre>";
//             print_r(($ChooseMoreOptions));
//             echo "<pre>";
//              
//             die;
            $bookingDataByAPI = [];
        } else {
            $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
            $PostData = ['TPSysId' => $intTPSysId, 'version' => 0, 'IsApproved' => 0];
            // if ($ispackage == 1) {
            //     $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetailsoffline/";
            // } else {
            $URL = $this->baseUrl . "/gtxwebservices/flight-api/bookingdetails/";
            //}
            $apiResponse = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($PostData, $getData, $URL);
            $bookingDataByAPI = isset($apiResponse['FlightBookingData']) ? $apiResponse['FlightBookingData'] : [];
         
            $FareBreakdownarr = isset($apiResponse['FareBreakdownarr']) ? $apiResponse['FareBreakdownarr'] : [];
            $GetTravelPlanType = $this->_crmcusttravelplan->GetTravelPlanType($intTPSysId);
            
            $CustomerSysId = isset($GetTravelPlanType['CustomerSysId']) ? $GetTravelPlanType['CustomerSysId'] : 0;
            $IsB2BProposal = isset($GetTravelPlanType['IsB2BProposal']) ? $GetTravelPlanType['IsB2BProposal'] : 0;
            $B2BAgencySysId = isset($GetTravelPlanType['CustomerAgencySysId']) ? $GetTravelPlanType['CustomerAgencySysId'] : 0;
            $RoomInfoJson = isset($GetTravelPlanType['RoomInfoJson']) ? json_decode($GetTravelPlanType['RoomInfoJson'], 1) : [];
            if ($RoomInfoJson) {
                foreach ($RoomInfoJson as $value) {
                     
                    $Adult += isset($value['Adult']) ? $value['Adult'] : 1;
                    $Child += isset($value['Child']) ? $value['Child'] : 0;
                    $Infant += isset($value['Infant']) ? $value['Infant'] : 0;
                     
                }
                $TotalPax = $Adult + $Child + $Infant;
            }
            
            if (!empty($bookingDataByAPI)) {
                $journeytype = ($bookingDataByAPI[0]['JourneyType']);
                $interNationalSearch = ($bookingDataByAPI[0]['IsInternational']);
            }
        }
        $EconomyMask = isset($GetTravelPlanType['EconomyMask']) ? $GetTravelPlanType['EconomyMask'] : 0;
        $PackSpecType = isset($GetTravelPlanType['PackSpecType']) ? $GetTravelPlanType['PackSpecType'] : 0;
        if($EconomyMask == 7 && $PackSpecType == 4){
            $this->_redirect('/booking-flight/offline-flight-book/id/'.$intTPSysIdEncode.'/uid/'.$uid.'/type/');
        }
        
        $agency = array(
            'PlanType' => 1,
            'MPType' => !empty($B2B) ? 2 : 1,
            'interNationalSearch' => $interNationalSearch,
            'B2B' => $B2B,
        );
        $AGENCYDETAILS = $this->baseUrl . "/gtxwebservices/agency";
        $AgencyMarkTax = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($agency, $getData, $AGENCYDETAILS);
        if ($CustomerSysId > 0) {
            $getCustomerDetail = $crmcustomerObj->GetCustomerWithDetails($CustomerSysId);
            if ($isquery == 0) {
                $arrtravellerList = $objFlight->GetCustomerListForFlightBooking($intTPSysId, null, null, 0);
            }
        } else {
            $getCustomerDetail = array();
            $arrtravellerList = array();
        }
        // echo '<pre>';
        // print_r($arrtravellerList);
        // die;
        $paxTypetraveller = [];
        $paxTypetravellers = [];
        if ($arrtravellerList) {
            foreach ($arrtravellerList as $key => $valuepax) {

                $MemberSysId = isset($valuepax['MemberSysId']) ? trim($valuepax['MemberSysId']) : 0;
                $FirstName = isset($valuepax['FirstName']) ? trim($valuepax['FirstName']) : '';
                $LastName = isset($valuepax['LastName']) ? trim($valuepax['LastName']) : '';
                $PaxType = isset($valuepax['paxType']) ? trim($valuepax['paxType']) : '';
                $Salutation = isset($valuepax['Salutation']) ? trim($valuepax['Salutation']) : '';
                $Title = isset($valuepax['Title']) ? trim($valuepax['Title']) : '';
                $passexp = isset($valuepax['passportnoexpiry']) ? (array) $valuepax['passportnoexpiry'] : '';
                $DOBSD = isset($valuepax['DOB']) ? (array) $valuepax['DOB'] : '';
                if (!empty($passexp['date']) && $passexp['date'] != '1900-01-01 00:00:00.000000') {
                    $passengerpassexp = date('d/m/Y', strtotime($passexp['date']));
                } else {
                    $passengerpassexp = '';
                }
                if (!empty($DOBSD['date']) && $DOBSD['date'] != '1900-01-01 00:00:00.000000') {
                    $passengerDob = date('d/m/Y', strtotime($DOBSD['date']));
                } else {
                    $passengerDob = '';
                }

                $paxType = (isset($valuepax['paxType']) && trim($valuepax['paxType']) > 0) ? trim($valuepax['paxType']) : 1;
                $SelectedMeal = !empty($valuepax['SelectedMeal']) ? json_decode($valuepax['SelectedMeal'], 1) : [];
                $SelectedSeat = !empty($valuepax['SelectedSeat']) ? json_decode($valuepax['SelectedSeat'], 1) : [];
                $SelectedBag = !empty($valuepax['SelectedBag']) ? json_decode($valuepax['SelectedBag'], 1) : [];
                // echo "<pre>";
                // print_r(($valuepax));
                // echo "</pre>";
                $paxTypetravellers[$paxType][$key] = $valuepax;

                $titleNew = !empty($Title) ? $Title : 0;
                if ($ispackage == 1 && ($PaxType == 2 || $PaxType == 3) && $titleNew == '1') {
                    $paxTypetravellers[$paxType][$key]['Title'] = 4;
                } else if ($ispackage == 1 && ($PaxType == 2 || $PaxType == 3) && $titleNew == '3') {
                    $paxTypetravellers[$paxType][$key]['Title'] = 5;
                } else {
                    $paxTypetravellers[$paxType][$key]['Title'] = $titleNew;
                }

                $paxTypetravellers[$paxType][$key]['SelectedMeal'] = $SelectedMeal;
                $paxTypetravellers[$paxType][$key]['SelectedSeat'] = $SelectedSeat;
                $paxTypetravellers[$paxType][$key]['SelectedBag'] = $SelectedBag;
                if ($key == 0 && $getCustomerDetail['CustomerSysId'] == $valuepax['CustomerSysId'] && !empty($getCustomerDetail)) {
                    $paxTypetravellers[$paxType][$key]['FirstName'] = !empty($FirstName) ? $FirstName : $getCustomerDetail['FirstName'];
                    $paxTypetravellers[$paxType][$key]['LastName'] = !empty($LastName) ? $LastName : $getCustomerDetail['LastName'];
                    $titleNew = !empty($Title) ? $Title : $getCustomerDetail['Salutation'];
                    if ($ispackage == 1 && ($PaxType == 2 || $PaxType == 3) && $titleNew == '1') {
                        $paxTypetravellers[$paxType][$key]['Title'] = 4;
                    } else if ($ispackage == 1 && ($PaxType == 2 || $PaxType == 3) && $titleNew == '3') {
                        $paxTypetravellers[$paxType][$key]['Title'] = 5;
                    } else {
                        $paxTypetravellers[$paxType][$key]['Title'] = $titleNew;
                    }
                    //$paxTypetravellers[$paxType][$key]['Title'] = !empty($Title) ? $Title : $getCustomerDetail['Salutation'];
                    $paxTypetravellers[$paxType][$key]['Salutation'] = $Salutation; // $getCustomerDetail['Salutation'];
                    $paxTypetravellers[$paxType][$key]['DOB'] = !empty($passengerDob) ? $valuepax['DOB'] : $getCustomerDetail['DOB'];
                    $paxTypetravellers[$paxType][$key]['passportnoexpiry'] = !empty($passengerpassexp) ? $valuepax['passportnoexpiry'] : $getCustomerDetail['passportnoexpiry'];
                    $paxTypetravellers[$paxType][$key]['passporIssue'] = $getCustomerDetail['passporIssue'];
                }
            }
            // echo "<pre>";
                    // print_r(($valuepax));
                    // die;
            if ($paxTypetravellers) {
                foreach ($paxTypetravellers as $keyType => $val) {
                    
                    $paxTypetraveller[$keyType] = array_values($val);
                }
            }
        } else {
            if ($FareBreakdownarr) {
                foreach ($FareBreakdownarr as $valbrk) {
                    $PassengerCount = $valbrk['PassengerCount'];
                    $PassengerType = $valbrk['PassengerType'];
                    $paxtypebr = [];
                    for ($i = 0; $i < $PassengerCount; $i++) {
                        $paxtypebr[$i] = $i;
                    }
                    $paxTypetraveller[$PassengerType] = $paxtypebr;
                }
            } else {

                $paxTypetravellers[1][0]['FirstName'] = $getCustomerDetail['FirstName'];
                $paxTypetravellers[1][0]['LastName'] = $getCustomerDetail['LastName'];
                $paxTypetravellers[1][0]['Title'] = $getCustomerDetail['Salutation'];
                $paxTypetravellers[1][0]['Salutation'] = $getCustomerDetail['Salutation'];
                $paxTypetravellers[1][0]['DOB'] = $getCustomerDetail['DOB'];
                $paxTypetravellers[1][0]['passportnoexpiry'] = $getCustomerDetail['passportnoexpiry'];
                $paxTypetravellers[1][0]['passporIssue'] = $getCustomerDetail['passporIssue'];
            }
        }

        
         
       
        $AirVersionIdFirst = !empty($index) ? $index : $bookingDataByAPI[0]['AirVersionId'];
        $moreFlightOption = [];
        $bookingDataByAPIInt = array();
        if (($journeytype == 1 || $journeytype == 2 || $journeytype == 3) && count($bookingDataByAPI) > 0) {
            if ($bookingDataByAPI) {
                
                foreach ($bookingDataByAPI as $key => $value) {
//                    echo 'asdasdasd<pre>';print_r($value);die;
                    $AirVersionId = !empty($value['AirVersionId']) ? $value['AirVersionId'] : 0;
                    $TripType = $value['TripType'];
                    $APIBookingId = $value['APIBookingId'];
                    $AirLineTitle = $value['AirLineTitle'];
                    $LocalFromTime = $value['LocalFromTime'];
                    $FlightNumber = $value['FlightNumber'];
                    if(($journeytype == 2 ) && $value['IsInternational'] == 1 && ($value['ICSourceSysId'] == 7 || $value['ICSourceSysId'] == 3)){
                        $SegmentsArray = array();
                        if(isset($value['Segments'])){
                            foreach ($value['Segments'] as $sgkey => $sgvalue) {
                                $SegmentsArray[$sgvalue['TripIndicator']][] = $sgvalue;
                            }
                        }
                        
                        $incTrp = 1;
                        
                        foreach ($SegmentsArray as $sgakey1 => $sgavalue1) {
                            $valueInt = $value; 
                            $SegmentsN = array();
                            $AirLineTitle1 = $sgavalue1[0]['AirlineName'];
                            $FlightNumber1 = $sgavalue1[0]['FlightNumber'];
                            $LocalFromTime1 = $sgavalue1[0]['originDepTime'];
                            $moreFlightOption[$incTrp][] = [
                                'AirVersionId' => $AirVersionId,
                                'TripType' => $TripType,
                                'Label' => trim($AirLineTitle1) . ' ' . trim($FlightNumber1) . ' - ' . date('d-m-Y H:i', strtotime($LocalFromTime1))
                            ];
                            if($AirVersionIdFirst == $AirVersionId){
                                foreach ($sgavalue1 as $sgakey => $sgavalue) {
                                
                                    $valueInt['AirlineName'] = $AirLineTitle1;
                                    $valueInt['AirLineCode'] = $sgavalue['AirlineCode'];
                                    $valueInt['AirLineTitle'] = $AirLineTitle1;
                                    $valueInt['FlightNumber'] = $FlightNumber1;
                                    $valueInt['SourceAirportCode'] = $sgavalue['OriginAirportCode'];
                                    $valueInt['DestAirportCode'] = $sgavalue['DestAirportCode'];
                                    $SegmentsN[] = $sgavalue; 
                                }
                                $valueInt['Segments'] = $SegmentsN;
                                if($incTrp > 1){
                                    $valueInt['FareBreakdown'] = array();
                                    $valueInt['FairRules'] = array();
                                }
                                $bookingDataByAPIInt[$incTrp-1] = $valueInt;
                            }
                            $incTrp++;
                        }
                    }else if(($journeytype == 3 ) && $value['IsInternational'] == 1 && $value['ICSourceSysId'] == 7){
                        $TripIndicatorInc = $TripIndicatorPre = 0;
                        foreach ($value['Segments'] as $sgakey1 => $sgavalue1) {
                            $TripIndicator = $sgavalue1['TripIndicator']; 
                            if($TripIndicator == 0){
                                $TripIndicatorInc++; 
                                $SegmentsN = array();
                                $AirLineTitle1 = $sgavalue1['AirlineName'];
                                $FlightNumber1 = $sgavalue1['FlightNumber'];
                                $LocalFromTime1 = $sgavalue1['originDepTime'];
                                $moreFlightOption[$TripIndicatorInc][] = [
                                    'AirVersionId' => $AirVersionId,
                                    'TripType' => $TripType,
                                    'Label' => trim($AirLineTitle1) . ' ' . trim($FlightNumber1) . ' - ' . date('d-m-Y H:i', strtotime($LocalFromTime1))
                                ];
                            
                            } 
                            
                        }
                    }else if(($journeytype == 3 ) && $value['ICSourceSysId'] == 3){
                        $TripIndicatorInc = $TripIndicatorPre = 0;
//                        echo 'asdasdasd<pre>';print_r($value);die;
                        foreach ($value['Segments'] as $sgakey1 => $sgavalue1) {
                            $TripIndicator = $sgavalue1['TripIndicator']; 
                            if($TripIndicator == $TripIndicatorPre){
                                $TripIndicatorInc = $TripIndicator; 
                                $SegmentsN = array();
                                $AirLineTitle1 = $sgavalue1['AirlineName'];
                                $FlightNumber1 = $sgavalue1['FlightNumber'];
                                $LocalFromTime1 = $sgavalue1['originDepTime'];
                                $moreFlightOption[$TripIndicatorInc][] = [
                                    'AirVersionId' => $AirVersionId,
                                    'TripType' => $TripType,
                                    'Label' => trim($AirLineTitle1) . ' ' . trim($FlightNumber1) . ' - ' . date('d-m-Y H:i', strtotime($LocalFromTime1))
                                ];
                            
                            } 
                            $TripIndicatorPre = $sgavalue1['TripIndicator'];
                            
                        } 
                    }else{ 
                        $moreFlightOption[$TripType][] = [
                            'AirVersionId' => $AirVersionId,
                            'TripType' => $TripType,
                            'Label' => trim($AirLineTitle) . ' ' . trim($FlightNumber) . ' - ' . date('d-m-Y H:i', strtotime($LocalFromTime))
                        ];
                    }
                }  
            }
            
            $MultiTJDomestic = ($journeytype == 3 && $bookingDataByAPI[0]['IsInternational'] == 0 && $value['ICSourceSysId'] == 7) ? 1 : 0;
            $MultiTJDomesticIntOffline = ($journeytype == 3 && ($value['ICSourceSysId'] == 9 || $value['ICSourceSysId'] == 2)) ? 1 : 0;
//            echo 'asdasdasd<pre>';print_r($value); die;
            if(($journeytype == 2) && $bookingDataByAPI[0]['IsInternational'] == 1 && $value['ICSourceSysId'] == 7){
                $bookingDataByAPI = $bookingDataByAPIInt;
            }else if($MultiTJDomestic != 1 && $MultiTJDomesticIntOffline != 1){
               
                if (!empty($index)) {
                    $AirVersionId = $index;
                } else {
                    $AirVersionId = $bookingDataByAPI[0]['AirVersionId'];
                }

                $result = array_filter($bookingDataByAPI, function ($item) use ($AirVersionId) {
                    return $item['AirVersionId'] == $AirVersionId && $item['TripType'] == 1;
                });
                $result2 = [];
                if ($journeytype == 2) {
                    if (!empty($indexround)) {
                        $AirVersionId = $indexround;
                    } else {
                        $AirVersionId = isset($moreFlightOption[$journeytype][0]['AirVersionId']) ? $moreFlightOption[$journeytype][0]['AirVersionId'] : 0;
                    }
                    $result2 = array_filter($bookingDataByAPI, function ($item) use ($AirVersionId) {
                        return $item['AirVersionId'] == $AirVersionId && $item['TripType'] == 2;
                    });
                } 
                $bookingDataByAPI = array_merge(array_values($result), array_values($result2));
            }
            
        }
            
        
                    
        $TripIndicatorR = 0;
        $TripTypePre = 0;
        if ($bookingDataByAPI) { 
            $Segments = array();
            $TripCount = count($bookingDataByAPI);
            foreach ($bookingDataByAPI as $key => $value) {
                $TJDeomestic = (($value['ICSourceSysId'] == 7) && (int)$value['IsInternational'] != 1) ? 1 : 0;
                $TJDeomesticIntOffline = ($value['ICSourceSysId'] == 9 || $value['ICSourceSysId'] == 2) ? 1 : 0;

                $ExtraMarkup = isset($value['ExtraMarkup']) ? ($value['ExtraMarkup']) : 0;
                $ExtraMarkupPP = 0;
                
                if($TotalPax > 0 && $ExtraMarkup > 0){
                    $ExtraMarkupPP = $ExtraMarkup / $TotalPax;
                }
                $AirlineRefPNR = !empty($value['AirlineRefPNR']) ? $value['AirlineRefPNR'] : '';
                $AirlineRefGDSPNR = !empty($value['AirlineRefGDSPNR']) ? $value['AirlineRefGDSPNR'] : '';
                $TPIntSysId = !empty($value['TPIntSysId']) ? $value['TPIntSysId'] : 0;
                $IsRefundable = !empty($value['IsRefundable']) ? $value['IsRefundable'] : 0;
                $AirVersionId = !empty($value['AirVersionId']) ? $value['AirVersionId'] : 0;
                $TripType = !empty($value['TripType']) ? $value['TripType'] : 0;
                if($journeytype == 3 && ($TJDeomestic == 1 || $TJDeomesticIntOffline == 1) && $TripTypePre == $TripType){
                    
                }else{
                    foreach ($value['FareBreakdown'] as $keyBr => $FareBreakdown) {

                        $PassengerCount = isset($FareBreakdown['PassengerCount']) ? ($FareBreakdown['PassengerCount']) : 1;
                        $FixedMarkUp = isset($FareBreakdown['FixedMarkUp']) ? ($FareBreakdown['FixedMarkUp']) : 0;
                        $PassengerType = isset($FareBreakdown['PassengerType']) ? ($FareBreakdown['PassengerType']) : 1;
                        $BaseFare_ = isset($FareBreakdown['BaseFare']) ? ($FareBreakdown['BaseFare']) : 0;
                        $Tax = isset($FareBreakdown['Tax']) ? ($FareBreakdown['Tax']) : 0;
                        // $FareBreak[$PassengerType] = [
                        //     'basefare' => (($BaseFare_ + $Tax) / $PassengerCount),
                        //     'markup' => ($FixedMarkUp / $PassengerCount),
                        // ];
                        $FareBreak[$PassengerType]['basefare'] += ((($BaseFare_ + $Tax) / $PassengerCount));
                        $FareBreak[$PassengerType]['markup'] += (($FixedMarkUp / $PassengerCount) + ($ExtraMarkupPP > 0 ? $ExtraMarkupPP : 0));
                        $FareBreak[$PassengerType]['PassengerCount'] = $PassengerCount;
                    }
                }
                
                

                $Segme = $SegmeM = [];
                $TripIndicatorInc = 0;
                if ($value['Segments']) {
                    
                    $ChooseMoreOptionsA = array();
                    if($journeytype == 3){ 
                        foreach ($value['Segments'] as $k => $ValSeg) {  
                            $TripIndicator = (int)$ValSeg['TripIndicator'];
                            if (trim($ValSeg['OriginAirportCode']) == '') {
                                $ValSeg['OriginAirportCode'] = $value['SourceAirportCode'];
                            }
                            if (trim($ValSeg['DestAirportCode']) == '') {
                                $ValSeg['DestAirportCode'] = $value['DestAirportCode'];
                            }
                            if (trim($ValSeg['FlightNumber']) == '') {
                                $ValSeg['FlightNumber'] = $value['FlightNumber'];
                            }
                            if (trim($ValSeg['AirlineName']) == '') {
                                $ValSeg['AirlineName'] = $value['AirLineTitle'];
                            }
                            if (trim($ValSeg['AirlineCode']) == '') {
                                $ValSeg['AirlineCode'] = $value['AirLineCode'];
                            }

                            if (trim($ValSeg['originDepTime']) == '') {
                                $ValSeg['originDepTime'] = $value['LocalFromTime'];
                            }
                            if (trim($ValSeg['destinationArrTime']) == '') {
                                $ValSeg['destinationArrTime'] = $value['LocalToTime'];
                            }
                            $Segme = $ValSeg;
                            $Segme['IsRefundable'] = $IsRefundable;
                            $Segme['TPIntSysId'] = $TPIntSysId;
                            $Segme['AirVersionId'] = $AirVersionId;
                            $Segme['gdspnrnumber'] = $AirlineRefGDSPNR;
                            $Segme['pnrnumber'] = $AirlineRefPNR;
                            $Segme['bookingId'] = $APIBookingId;
                            if($value['ICSourceSysId'] == 7 || $value['ICSourceSysId'] == 9 || $value['ICSourceSysId'] == 2){
                                if($value['IsInternational'] == 1 && $value['ICSourceSysId'] != 9 && $value['ICSourceSysId'] != 2){
                                    if($TripIndicator == 0){
                                        $TripIndicatorInc++;
                                    }
                                    $Segments[$TripIndicatorInc-1][] = $Segme;
                                    $OriginAirportCodeNN = $ValSeg['OriginAirportCode'];
                                    $DestAirportCodeNN = $ValSeg['DestAirportCode'];
                                    $ChooseMoreOptionsA[$TripIndicatorInc-1][] = $OriginAirportCodeNN;
                                    $ChooseMoreOptionsA[$TripIndicatorInc-1][] = $DestAirportCodeNN;
                                }else{  
                                     
                                    if($TripTypePre == ($TripType-1)){
                                        $Segments[$TripType-1][] = $Segme;
                                        $OriginAirportCodeNN = $ValSeg['OriginAirportCode'];
                                        $DestAirportCodeNN = $ValSeg['DestAirportCode'];
                                        $ChooseMoreOptionsA[$TripType-1][] = $OriginAirportCodeNN;
                                        $ChooseMoreOptionsA[$TripType-1][] = $DestAirportCodeNN;
                                    }
                                }
                            }else if($value['ICSourceSysId'] == 3){
                                 
                                $Segments[$TripIndicator-1][] = $Segme;
                                $OriginAirportCodeNN = $ValSeg['OriginAirportCode'];
                                $DestAirportCodeNN = $ValSeg['DestAirportCode'];
                                $ChooseMoreOptionsA[$TripIndicator-1][] = $OriginAirportCodeNN;
                                $ChooseMoreOptionsA[$TripIndicator-1][] = $DestAirportCodeNN;
                            }else{
                                $Segments[$TripIndicatorInc][] = $Segme;
                                $OriginAirportCodeNN = $ValSeg['OriginAirportCode'];
                                $DestAirportCodeNN = $ValSeg['DestAirportCode'];
                                $ChooseMoreOptionsA[$TripIndicatorInc][] = $OriginAirportCodeNN;
                                $ChooseMoreOptionsA[$TripIndicatorInc][] = $DestAirportCodeNN;
                                if($TripIndicator > $TripIndicatorPre){
                                    $TripIndicatorInc++;
                                }
                                $TripIndicatorPre = $TripIndicator;
                            }
                        }
//                         echo 'asdasdasd<pre>';print_r($ChooseMoreOptionsA);die;
                        foreach($ChooseMoreOptionsA as $cmKey => $cmValue){
                            $firstVal = $cmValue[0];
                            $lastVal = end($cmValue);
                            $ChooseMoreOptions[$firstVal.'-'.$lastVal] = [];   
                        }
                    }else{
                        
                        if($value['ICSourceSysId'] == 3 && $value['IsInternational'] != 1){
                            $TripIndicator++; 
                        } 
                        
                        foreach ($value['Segments'] as $k => $ValSeg) {
                            if (trim($ValSeg['OriginAirportCode']) == '') {
                                $ValSeg['OriginAirportCode'] = $value['SourceAirportCode'];
                            }
                            if (trim($ValSeg['DestAirportCode']) == '') {
                                $ValSeg['DestAirportCode'] = $value['DestAirportCode'];
                            }
                            if (trim($ValSeg['FlightNumber']) == '') {
                                $ValSeg['FlightNumber'] = $value['FlightNumber'];
                            }
                            if (trim($ValSeg['AirlineName']) == '') {
                                $ValSeg['AirlineName'] = $value['AirLineTitle'];
                            }
                            if (trim($ValSeg['AirlineCode']) == '') {
                                $ValSeg['AirlineCode'] = $value['AirLineCode'];
                            }

                            if (trim($ValSeg['originDepTime']) == '') {
                                $ValSeg['originDepTime'] = $value['LocalFromTime'];
                            }
                            if (trim($ValSeg['destinationArrTime']) == '') {
                                $ValSeg['destinationArrTime'] = $value['LocalToTime'];
                            }
                            if($value['ICSourceSysId'] == 3){
                                if($value['IsInternational'] == 1){
                                    $TripIndicatorR = $ValSeg['TripIndicator']; 
                                }else{
                                    
                                    $TripIndicatorR = $TripIndicator-1;
                                }
                                
                            }
                            $Segme = $ValSeg;
                            $Segme['IsRefundable'] = $IsRefundable;
                            $Segme['TPIntSysId'] = $TPIntSysId;
                            $Segme['AirVersionId'] = $AirVersionId;
                            $Segme['gdspnrnumber'] = $AirlineRefGDSPNR;
                            $Segme['pnrnumber'] = $AirlineRefPNR;
                            $Segme['bookingId'] = $APIBookingId;
                            
                            $OriginAirportCodeNN = $ValSeg['OriginAirportCode'];
                            $DestAirportCodeNN = $ValSeg['DestAirportCode'];
                            
                            if($value['ICSourceSysId'] == 3){
                                $ChooseMoreOptionsA[$TripIndicatorR][] = $OriginAirportCodeNN;
                                $ChooseMoreOptionsA[$TripIndicatorR][] = $DestAirportCodeNN;
                                 
                                $Segments[$TripIndicatorR][] = $Segme;
                                 
                            }else{
                                $ChooseMoreOptionsA[] = $OriginAirportCodeNN;
                                $ChooseMoreOptionsA[] = $DestAirportCodeNN;
                                $SegmeM[$k] = $Segme;
                                
                            }
                            
                        }
                         
                        $ChooseMoreOptions1 = $ChooseMoreOptionsA[0];
                        $ChooseMoreOptionsAR = array_reverse($ChooseMoreOptionsA);
                        $ChooseMoreOptions2 = $ChooseMoreOptionsAR[0];
                        
                        if($value['ICSourceSysId'] != 3){
                            $ChooseMoreOptions[$ChooseMoreOptions1.'-'.$ChooseMoreOptions2] = array();
                            $Segments[] = $SegmeM; 
                        }else{
                            foreach($ChooseMoreOptionsA as $cmKey => $cmValue){
                                $firstVal = $cmValue[0];
                                $lastVal = end($cmValue);
                                $ChooseMoreOptions[$firstVal.'-'.$lastVal] = [];   
                            }
                        }
                        
                         
                    }
                    
                } else {
                    $Segme = [
                        "IsRefundable" => $IsRefundable,
                        "TPIntSysId" => $TPIntSysId,
                        "AirVersionId" => $AirVersionId,
                        "gdspnrnumber" => $AirlineRefGDSPNR,
                        "pnrnumber" => $AirlineRefPNR,
                        "bookingId" => $APIBookingId
                    ];
                    $Segments[] = [$Segme];
                }
                $TripTypePre = $TripType;
            }
            
            $supplier_id = isset($bookingDataByAPI[0]['SupplierSysId']) ? $bookingDataByAPI[0]['SupplierSysId'] : 0;
            $JourneyType_ = isset($bookingDataByAPI[0]['JourneyType']) ? $bookingDataByAPI[0]['JourneyType'] : 1;

            $journeytype = ($journeytype > 0) ? $journeytype : $JourneyType_;
            $supplierData = $objTblSupplier->getSupplierList($supplier_id);
            $this->view->supplier_name = isset($supplierData['SupplierName']) ? $supplierData['SupplierName'] : '';
        }

        $LocalFromTime = isset($bookingDataByAPI[0]['LocalFromTime']) ? date('d/m/Y', strtotime($bookingDataByAPI[0]['LocalFromTime'])) : $departuredate;
        $LocalToTime = isset($bookingDataByAPI[0]['LocalToTime']) ? date('d/m/Y', strtotime($bookingDataByAPI[0]['LocalToTime'])) : $returndate;
        $supplier_id = isset($bookingDataByAPI[0]['SupplierSysId']) ? $bookingDataByAPI[0]['SupplierSysId'] : 0;

//         echo '<pre>';
//         print_r($Segments);
//         die;
//         echo '<pre>moreFlightOption';
//         print_r($ChooseMoreOptions);die;

        $TblCurrency = new Travel_Model_TblCurrency();
        $this->view->Currency = $Currency = $TblCurrency->getCurrencyTypes();
        $this->view->TrxCurrency = $TrxCurrency = $this->agencyDetails['TrxCurrency'];
        $this->view->getTaxSettingDetail = isset($AgencyMarkTax['TaxSetting']) ? [$AgencyMarkTax['TaxSetting']] : [];
        $this->view->ispackage = $ispackage;
        $this->view->getCustomerDetail = $getCustomerDetail;
        $this->view->LocalFromTime = $LocalFromTime;
        $this->view->LocalToTime = $LocalToTime;
        $this->view->supplier_id = $supplier_id;
        $this->view->route = $journeytype;
        $this->view->isquery = $isquery;
        if ($IsB2BProposal == 1) {
            $this->view->AgencySysId = $B2BAgencySysId;
        } else {
            $this->view->AgencySysId = ($this->intLoggedinAgencyId);
        }
        $SLItem = (isset($Segments) && count($Segments) > 0) ? $Segments : [];
        
        if ($journeytype == 1 && empty($ChooseMoreOptions)) {
            $ChooseMoreOptions = [
                'Onward' => [],
            ];
        } elseif ($journeytype == 2 && empty($ChooseMoreOptions)) {
            $ChooseMoreOptions = [
                'Onward' => [],
                'Return' => [],
            ];
        } elseif ($journeytype == 3 && empty($ChooseMoreOptions)) {
            
            $ChooseMoreOptions = [
                'Onward 1' => [],
                'Onward 2' => [],
                'Onward 3' => [],
                 
            ];
        }

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

        $PaxFareDetaials = [];
        $adultCount = (isset($paxTypetraveller[1]) && !empty($paxTypetraveller[1])) ? count($paxTypetraveller[1]) : $Adult;
        $childCount = (isset($paxTypetraveller[2]) && !empty($paxTypetraveller[2])) ? count($paxTypetraveller[2]) : $Child;
        $infantCount = (isset($paxTypetraveller[3]) && !empty($paxTypetraveller[3])) ? count($paxTypetraveller[3]) : $Infant;
        $SSRData = [];
        $ICSourceSysId = 9;
        $AdultSeatPrice = 0;
        $AdultMealPrice = 0;
        $AdultBaggPrice = 0;
        if ($adultCount > 0) {
            $intPaxCount = 1;
            
            for ($i = 1; $i <= $adultCount; $i++) {
                $SelectedSeat = (isset($paxTypetraveller[1][$i - 1]['SelectedSeat']) && !empty($paxTypetraveller[1][$i - 1]['SelectedSeat'])) ? ($paxTypetraveller[1][$i - 1]['SelectedSeat']) : [];
                $SelectedBag = (isset($paxTypetraveller[1][$i - 1]['SelectedBag']) && !empty($paxTypetraveller[1][$i - 1]['SelectedBag'])) ? ($paxTypetraveller[1][$i - 1]['SelectedBag']) : [];
                $SelectedMeal = (isset($paxTypetraveller[1][$i - 1]['SelectedMeal']) && !empty($paxTypetraveller[1][$i - 1]['SelectedMeal'])) ? ($paxTypetraveller[1][$i - 1]['SelectedMeal']) : [];

                if ($SelectedSeat) {
                    foreach ($SelectedSeat as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $i;
                        }

                        $SSRData[$kSec][1]['seat'][] = $SSrData;
                    }
                }
                if ($SelectedMeal) {
                    foreach ($SelectedMeal as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $i;
                        }
                        $SSRData[$kSec][1]['meal'][] = $SSrData;
                    }
                }
                if ($SelectedBag) {
                    foreach ($SelectedBag as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $i;
                        }
                        $SSRData[$kSec][1]['bagg'][] = $SSrData;
                    }
                }
                $AdultSeatPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedSeat)
                );
                $AdultMealPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedMeal)
                );
                $AdultBaggPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedBag)
                );

                $MemberSysIdKey = $MemberSysId = (isset($paxTypetraveller[1][$i - 1]['MemberSysId']) && !empty($paxTypetraveller[1][$i - 1]['MemberSysId'])) ? ($paxTypetraveller[1][$i - 1]['MemberSysId']) : ($paxTypetraveller[1][$i - 1]['CustomerSysId']);
                // $MemberSysId = (isset($paxTypetraveller[1][$i - 1]['MemberSysId']) && !empty($paxTypetraveller[1][$i - 1]['MemberSysId'])) ? ($paxTypetraveller[1][$i - 1]['MemberSysId']) : 0;
                
                if($MemberSysId == 0){
                    $MemberSysIdKey = $i;
                }
                $memberDetails[$MemberSysIdKey]['index'] = $i;
                $memberDetails[$MemberSysIdKey]['PaxCount'] = $intPaxCount;
                $memberDetails[$MemberSysIdKey]['PaxType'] = 1;
                $memberDetails[$MemberSysIdKey]['pax'] = 'ADULT';
                $memberDetails[$MemberSysIdKey]['AgeR'] = '12 yrs+';
                $memberDetails[$MemberSysIdKey]['Sectors'] = (isset($paxTypetraveller[1][$i - 1]['Sectors']) && !empty($paxTypetraveller[1][$i - 1]['Sectors'])) ? explode('@@', $paxTypetraveller[1][$i - 1]['Sectors']) : '';
                $memberDetails[$MemberSysIdKey]['VersionId'] = 0;
                $memberDetails[$MemberSysIdKey]['TPPaxSysId'] = 0;
                $memberDetails[$MemberSysIdKey]['cid'] = (isset($MemberSysId) && !empty($MemberSysId)) ? ($MemberSysId) : 0;
                $memberDetails[$MemberSysIdKey]['fname'] = (isset($paxTypetraveller[1][$i - 1]['FirstName']) && !empty($paxTypetraveller[1][$i - 1]['FirstName'])) ? trim($paxTypetraveller[1][$i - 1]['FirstName']) : '';
                $memberDetails[$MemberSysIdKey]['lname'] = (isset($paxTypetraveller[1][$i - 1]['LastName']) && !empty($paxTypetraveller[1][$i - 1]['LastName'])) ? trim($paxTypetraveller[1][$i - 1]['LastName']) : '';
                $memberDetails[$MemberSysIdKey]['Relation'] = (isset($paxTypetraveller[1][$i - 1]['Salutation'])) ? trim($paxTypetraveller[1][$i - 1]['Salutation']) : '9';
                $memberDetails[$MemberSysIdKey]['name'] = '';
                $memberDetails[$MemberSysIdKey]['title'] = (isset($paxTypetraveller[1][$i - 1]['Title']) && !empty($paxTypetraveller[1][$i - 1]['Title'])) ? ($paxTypetraveller[1][$i - 1]['Title']) : '';
                $memberDetails[$MemberSysIdKey]['dob'] = (isset($paxTypetraveller[1][$i - 1]['DOB']) && !empty($paxTypetraveller[1][$i - 1]['DOB'])) ? ($paxTypetraveller[1][$i - 1]['DOB']) : '';
                $memberDetails[$MemberSysIdKey]['FFAirlineCode'] = '';
                $memberDetails[$MemberSysIdKey]['FFNumber'] = '';
                $memberDetails[$MemberSysIdKey]['passno'] = (isset($paxTypetraveller[1][$i - 1]['passportno']) && !empty($paxTypetraveller[1][$i - 1]['passportno'])) ? trim($paxTypetraveller[1][$i - 1]['passportno']) : '';
                $memberDetails[$MemberSysIdKey]['passisse'] = '';
                $memberDetails[$MemberSysIdKey]['passexp'] = (isset($paxTypetraveller[1][$i - 1]['passportnoexpiry']) && !empty($paxTypetraveller[1][$i - 1]['passportnoexpiry'])) ? ($paxTypetraveller[1][$i - 1]['passportnoexpiry']) : '';
                $memberDetails[$MemberSysIdKey]['city'] = '';
                $memberDetails[$MemberSysIdKey]['address'] = '';
                $memberDetails[$MemberSysIdKey]['passnational'] = ''; //Relation; 
                $memberDetails[$MemberSysIdKey]['isdobr'] = false;
                $memberDetails[$MemberSysIdKey]['IsPassM'] = false;
                $memberDetails[$MemberSysIdKey]['IsDocIdM'] = false;
                $memberDetails[$MemberSysIdKey]['addonns'] = true;
                $memberDetails[$MemberSysIdKey]['selectedBad'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['selectedMeal'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['docid'] = '';
                $memberDetails[$MemberSysIdKey]['checked'] = ($i == 1) ? true : false;
                $memberDetails[$MemberSysIdKey]['ICSourceSysId'] = $ICSourceSysId;
                $intPaxCount++;
            }
             
            $PaxFareDetaials[0] = [
                "PaxType" => 1,
                "pax" => 'ADULT',
                "AgeR" => '+12 YRS',
                // "PaxCount" => $adultCount,
                "PaxCount" => (isset($FareBreak[1]['PassengerCount']) && !empty($FareBreak[1]['PassengerCount'])) ? ($FareBreak[1]['PassengerCount']) : $adultCount,
                "basefare" => (isset($FareBreak[1]['basefare']) && !empty($FareBreak[1]['basefare'])) ? ($FareBreak[1]['basefare']) : 0,
                "markup" => (isset($FareBreak[1]['markup']) && !empty($FareBreak[1]['markup'])) ? ($FareBreak[1]['markup']) : 0,
                "total" => 0,
                "totalssr" => ($AdultSeatPrice + $AdultBaggPrice + $AdultMealPrice),
                "GstType" => isset($AgencyMarkTax['TaxSetting']['TaxPercentage']) ? $AgencyMarkTax['TaxSetting']['TaxPercentage'] : 0,
                "TotalGST" => 0,
                "supplier_name" => "",
                "supplier_id" => 0,
                "ExtraMarkup" => 0,
                "DiscountValue" => 0
            ];
        }

        $ChildSeatPrice = 0;
        $ChildMealPrice = 0;
        $ChildBaggPrice = 0;
        if ($childCount > 0) {
            $intPaxCount = 1;
            for ($kk = $i; $kk <= ($childCount + $adultCount); $kk++) {

                $SelectedSeat = (isset($paxTypetraveller[2][$intPaxCount - 1]['SelectedSeat']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['SelectedSeat'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['SelectedSeat']) : [];
                $SelectedBag = (isset($paxTypetraveller[2][$intPaxCount - 1]['SelectedBag']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['SelectedBag'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['SelectedBag']) : [];
                $SelectedMeal = (isset($paxTypetraveller[2][$intPaxCount - 1]['SelectedMeal']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['SelectedMeal'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['SelectedMeal']) : [];

                if ($SelectedSeat) {
                    foreach ($SelectedSeat as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $kk;
                        }
                        $SSRData[$kSec][2]['seat'][] = $SSrData;
                    }
                }
                if ($SelectedMeal) {
                    foreach ($SelectedMeal as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $kk;
                        }
                        $SSRData[$kSec][2]['meal'][] = $SSrData;
                    }
                }
                if ($SelectedBag) {
                    foreach ($SelectedBag as $kSec => $SSRVal) {
                        $SSrData = isset($SSRVal[0]) ? $SSRVal[0] : [];
                        if (!empty($SSrData)) {
                            $SSrData['index'] = $kk;
                        }
                        $SSRData[$kSec][2]['bagg'][] = $SSrData;
                    }
                }
                $ChildSeatPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedSeat)
                );
                $ChildMealPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedMeal)
                );
                $ChildBaggPrice += array_sum(
                        array_map(function ($segmentVal) {
                            return array_sum(array_column($segmentVal, 'Price'));
                        }, $SelectedBag)
                );
                $MemberSysIdKey = $MemberSysId = (isset($paxTypetraveller[2][$intPaxCount - 1]['MemberSysId']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['MemberSysId'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['MemberSysId']) : ($paxTypetraveller[2][$intPaxCount - 1]['CustomerSysId']);
                
                if($MemberSysId == 0){
                    $MemberSysIdKey = $kk;
                }
                $memberDetails[$MemberSysIdKey]['index'] = $kk;
                $memberDetails[$MemberSysIdKey]['PaxCount'] = $intPaxCount;
                $memberDetails[$MemberSysIdKey]['PaxType'] = 2;
                $memberDetails[$MemberSysIdKey]['pax'] = 'CHILD';
                $memberDetails[$MemberSysIdKey]['AgeR'] = '2-12 Yrs';
                $memberDetails[$MemberSysIdKey]['Sectors'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['Sectors']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['Sectors'])) ? explode('@@', $paxTypetraveller[2][$intPaxCount - 1]['Sectors']) : '';
                $memberDetails[$MemberSysIdKey]['VersionId'] = 0;
                $memberDetails[$MemberSysIdKey]['TPPaxSysId'] = 0;
                $memberDetails[$MemberSysIdKey]['cid'] = (isset($MemberSysId) && !empty($MemberSysId)) ? ($MemberSysId) : 0;
                $memberDetails[$MemberSysIdKey]['fname'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['FirstName']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['FirstName'])) ? trim($paxTypetraveller[2][$intPaxCount - 1]['FirstName']) : '';
                $memberDetails[$MemberSysIdKey]['lname'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['LastName']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['LastName'])) ? trim($paxTypetraveller[2][$intPaxCount - 1]['LastName']) : '';
                $memberDetails[$MemberSysIdKey]['Relation'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['Salutation']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['Salutation'])) ? trim($paxTypetraveller[2][$intPaxCount - 1]['Salutation']) : '9';
                $memberDetails[$MemberSysIdKey]['name'] = '';

                $memberDetails[$MemberSysIdKey]['title'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['Title']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['Title'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['Title']) : '';
                $memberDetails[$MemberSysIdKey]['dob'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['DOB']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['DOB'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['DOB']) : '';
                $memberDetails[$MemberSysIdKey]['FFAirlineCode'] = '';
                $memberDetails[$MemberSysIdKey]['FFNumber'] = '';
                $memberDetails[$MemberSysIdKey]['passno'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['passportno']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['passportno'])) ? trim($paxTypetraveller[2][$intPaxCount - 1]['passportno']) : '';
                $memberDetails[$MemberSysIdKey]['passisse'] = '';
                $memberDetails[$MemberSysIdKey]['passexp'] = (isset($paxTypetraveller[2][$intPaxCount - 1]['passportnoexpiry']) && !empty($paxTypetraveller[2][$intPaxCount - 1]['passportnoexpiry'])) ? ($paxTypetraveller[2][$intPaxCount - 1]['passportnoexpiry']) : '';

                $memberDetails[$MemberSysIdKey]['city'] = '';
                $memberDetails[$MemberSysIdKey]['address'] = '';
                $memberDetails[$MemberSysIdKey]['passnational'] = ''; //$ISOcountryCode; title
                $memberDetails[$MemberSysIdKey]['isdobr'] = true;
                $memberDetails[$MemberSysIdKey]['IsPassM'] = false;
                $memberDetails[$MemberSysIdKey]['addonns'] = true;
                $memberDetails[$MemberSysIdKey]['selectedBad'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['selectedMeal'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['checked'] = false;
                $memberDetails[$MemberSysIdKey]['ICSourceSysId'] = $ICSourceSysId;
                $intPaxCount++;
            }
            $PaxFareDetaials[1] = [
                "PaxType" => 2,
                "pax" => 'CHILD',
                "AgeR" => '2-11 YRS',
                // "PaxCount" => $childCount,
                "PaxCount" => (isset($FareBreak[2]['PassengerCount']) && !empty($FareBreak[2]['PassengerCount'])) ? ($FareBreak[2]['PassengerCount']) : $childCount,
                "basefare" => (isset($FareBreak[2]['basefare']) && !empty($FareBreak[2]['basefare'])) ? ($FareBreak[2]['basefare']) : 0,
                "markup" => (isset($FareBreak[2]['markup']) && !empty($FareBreak[2]['markup'])) ? ($FareBreak[2]['markup']) : 0,
                "total" => 0,
                "totalssr" => ($ChildSeatPrice + $ChildBaggPrice + $ChildMealPrice),
                "GstType" => isset($AgencyMarkTax['TaxSetting']['TaxPercentage']) ? $AgencyMarkTax['TaxSetting']['TaxPercentage'] : 0,
                "TotalGST" => 0,
                "supplier_name" => "",
                "supplier_id" => 0,
                "ExtraMarkup" => 0,
                "DiscountValue" => 0
            ];
        }
        // echo "<pre>";
        // print_r(json_encode($paxTypetraveller));
        // echo "</pre>";
        // echo "<pre>";
        // print_r(($SSRData));
        // echo "</pre>";
        // die;
        if ($infantCount > 0) {
            $intPaxCount = 1;
            if (isset($kk)) {
                $kk = $kk;
            } else {
                $kk = $i;
            }
            for ($kkk = $kk; $kkk <= ($adultCount + $childCount + $infantCount); $kkk++) {
                $MemberSysIdKey = $MemberSysId = (isset($paxTypetraveller[3][$intPaxCount - 1]['MemberSysId']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['MemberSysId'])) ? ($paxTypetraveller[3][$intPaxCount - 1]['MemberSysId']) : ($paxTypetraveller[3][$intPaxCount - 1]['CustomerSysId']);
                if($MemberSysId == 0){
                    $MemberSysIdKey = $kkk;
                }
                
                $memberDetails[$MemberSysIdKey]['index'] = $kkk;
                $memberDetails[$MemberSysIdKey]['PaxCount'] = $intPaxCount;
                $memberDetails[$MemberSysIdKey]['PaxType'] = 3;
                $memberDetails[$MemberSysIdKey]['pax'] = 'INFANT';
                $memberDetails[$MemberSysIdKey]['AgeR'] = '< 2 Yrs';

                $memberDetails[$MemberSysIdKey]['Sectors'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['Sectors']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['Sectors'])) ? explode('@@', $paxTypetraveller[3][$intPaxCount - 1]['Sectors']) : '';
                $memberDetails[$MemberSysIdKey]['VersionId'] = 0;
                $memberDetails[$MemberSysIdKey]['TPPaxSysId'] = 0;
                $memberDetails[$MemberSysIdKey]['cid'] = (isset($MemberSysId) && !empty($MemberSysId)) ? ($MemberSysId) : 0;
                $memberDetails[$MemberSysIdKey]['fname'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['FirstName']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['FirstName'])) ? trim($paxTypetraveller[3][$intPaxCount - 1]['FirstName']) : '';
                $memberDetails[$MemberSysIdKey]['lname'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['LastName']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['LastName'])) ? trim($paxTypetraveller[3][$intPaxCount - 1]['LastName']) : '';
                $memberDetails[$MemberSysIdKey]['Relation'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['Salutation']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['Salutation'])) ? trim($paxTypetraveller[3][$intPaxCount - 1]['Salutation']) : '9';

                $memberDetails[$MemberSysIdKey]['title'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['Title']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['Title'])) ? ($paxTypetraveller[3][$intPaxCount - 1]['Title']) : '';
                $memberDetails[$MemberSysIdKey]['dob'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['DOB']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['DOB'])) ? ($paxTypetraveller[3][$intPaxCount - 1]['DOB']) : '';
                $memberDetails[$MemberSysIdKey]['FFAirlineCode'] = '';
                $memberDetails[$MemberSysIdKey]['FFNumber'] = '';
                $memberDetails[$MemberSysIdKey]['passno'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['passportno']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['passportno'])) ? trim($paxTypetraveller[3][$intPaxCount - 1]['passportno']) : '';
                $memberDetails[$MemberSysIdKey]['passisse'] = '';
                $memberDetails[$MemberSysIdKey]['passexp'] = (isset($paxTypetraveller[3][$intPaxCount - 1]['passportnoexpiry']) && !empty($paxTypetraveller[3][$intPaxCount - 1]['passportnoexpiry'])) ? ($paxTypetraveller[3][$intPaxCount - 1]['passportnoexpiry']) : '';

                $memberDetails[$MemberSysIdKey]['address'] = '';
                $memberDetails[$MemberSysIdKey]['city'] = '';
                $memberDetails[$MemberSysIdKey]['passnational'] = ''; //$ISOcountryCode;
                $memberDetails[$MemberSysIdKey]['isdobr'] = true;
                $memberDetails[$MemberSysIdKey]['IsPassM'] = false;
                $memberDetails[$MemberSysIdKey]['addonns'] = false;
                $memberDetails[$MemberSysIdKey]['selectedBad'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['selectedMeal'] = 'NA@NA@@0';
                $memberDetails[$MemberSysIdKey]['checked'] = false;
                $memberDetails[$MemberSysIdKey]['ICSourceSysId'] = 0;
                $intPaxCount++;
            }

            $PaxFareDetaials[2] = [
                "PaxType" => 3,
                "pax" => 'INFANT',
                "AgeR" => '0-2 YRS',
                // "PaxCount" => $infantCount,
                "PaxCount" => (isset($FareBreak[3]['PassengerCount']) && !empty($FareBreak[3]['PassengerCount'])) ? ($FareBreak[3]['PassengerCount']) : $infantCount,
                "basefare" => (isset($FareBreak[3]['basefare']) && !empty($FareBreak[3]['basefare'])) ? ($FareBreak[3]['basefare']) : 0,
                "markup" => (isset($FareBreak[3]['markup']) && !empty($FareBreak[3]['markup'])) ? ($FareBreak[3]['markup']) : 0,
                "total" => 0,
                "totalssr" => 0,
                "GstType" => isset($AgencyMarkTax['TaxSetting']['TaxPercentage']) ? $AgencyMarkTax['TaxSetting']['TaxPercentage'] : 0,
                "TotalGST" => 0,
                "supplier_name" => "",
                "supplier_id" => 0,
                "ExtraMarkup" => 0,
                "DiscountValue" => 0
            ];
        }
//        
//         echo '<pre>ChooseMoreOptions';
//         print_r($ChooseMoreOptions);
//         echo '<pre>moreFlightOption';
//         print_r($moreFlightOption);
//         echo '<pre>SLItem';
//         print_r($SLItem);
//         die;
        $this->view->ChooseMoreOptions = $ChooseMoreOptions;
        $this->view->SLItem = $SLItem;
        $this->view->PaxFareDetaials = $PaxFareDetaials;
        $this->view->memberDetails = $memberDetails;
        $this->view->SSRData = $SSRData;
        $this->view->ICSourceSysId = $ICSourceSysId;
        $this->view->moreFlightOption = $moreFlightOption;

        $this->view->TPSysId = ($intTPSysId);
        $this->view->MasterTPSysId = ($MasterTPSysId);
        $this->view->interNationalSearch = $interNationalSearch;
    }

    public function saveOfflineInventoryAction() {
        $objFlight = new Travel_Model_TblFlight();
        $param = $this->getRequest()->getParams();
        $fareRules = $param['fareRules'];
        $currencytype = $param['currencytype'];
        $submitter = isset($param['submitter']) ? $param['submitter'] : '';
        
        $paramArray = $this->getRequest()->getParams();
        $fareRules = isset($paramArray['fareRules']) ? $paramArray['fareRules'] : '';
        $isquery = isset($param['isquery']) ? $param['isquery'] : '';
        $ispackage = isset($param['ispackage']) ? $param['ispackage'] : '';

        $cancellationPolicy = isset($param['cancellationPolicy']) ? $param['cancellationPolicy'] : '';
        $internalRemarks = isset($param['internalRemarks']) ? $param['internalRemarks'] : '';
        if (isset($paramArray["data"])) {
            parse_str(urldecode(base64_decode($paramArray["data"])), $param);
        }
//        echo "<pre>";print_r($param);die;
        $param['fareRules'] = $fareRules;
        $param['cancellationPolicy'] = $cancellationPolicy;
        $param['internalRemarks'] = $internalRemarks;
        $TPSysId = $param['TPSysId'];
        $isquery = isset($param['isquery']) ? $param['isquery'] : '';
        $ispackage = isset($param['ispackage']) ? $param['ispackage'] : '';
        $memberDetails = isset($param['memberDetails']) ? json_decode($param['memberDetails'], 1) : [];

        $sessionFlightSearchParams = [];
        $FlightTempData = $objFlight->GetFlightTempDataByTPSysId($TPSysId);
        if ($FlightTempData) {
            $arrUrlData = json_decode($FlightTempData['APIBookingData'], true);
            $sessionFlightSearchParams = isset($arrUrlData['sessionFlightSearchParams']) ? $arrUrlData['sessionFlightSearchParams'] : [];
        }
//         echo '<pre>';
//         print_r($arrUrlData);
//         die;
        $ProposalID = 0;
        $GetCustomerSelectedFlightAir = array();
        $RoomInfoJsonM = '';
        if ($isquery == 1) {
            $GetTravelPlanType = $this->_crmcusttravelplan->GetTravelPlanType($TPSysId, 'Query');
            $CustomerSysId = isset($GetTravelPlanType['CustomerSysId']) ? $GetTravelPlanType['CustomerSysId'] : 0;
            $IsB2BProposal = isset($GetTravelPlanType['IsB2BProposal']) ? $GetTravelPlanType['IsB2BProposal'] : 0;
            $AgentSysId = isset($GetTravelPlanType['AgentSysId']) ? $GetTravelPlanType['AgentSysId'] : 0;
            $AgencySysId = isset($GetTravelPlanType['AgencySysId']) ? $GetTravelPlanType['AgencySysId'] : 0;
            $editLeadId = isset($GetTravelPlanType['query_id']) ? $GetTravelPlanType['query_id'] : 0;
            $RoomInfoJsonM = isset($GetTravelPlanType['RoomInfoJson']) ? $GetTravelPlanType['RoomInfoJson'] : '';
        } else {
            $ProposalID = $TPSysId;
            $GetTravelPlanType = $this->_crmcusttravelplan->GetTravelPlanType($TPSysId);
            $CustomerSysId = isset($GetTravelPlanType['CustomerSysId']) ? $GetTravelPlanType['CustomerSysId'] : 0;
            $IsB2BProposal = isset($GetTravelPlanType['IsB2BProposal']) ? $GetTravelPlanType['IsB2BProposal'] : 0;
            $AgentSysId = isset($GetTravelPlanType['AgentSysId']) ? $GetTravelPlanType['AgentSysId'] : 0;
            $AgencySysId = isset($GetTravelPlanType['AgencySysId']) ? $GetTravelPlanType['AgencySysId'] : 0;
            $editLeadId = isset($GetTravelPlanType['query_id']) ? $GetTravelPlanType['query_id'] : 0;
            $RoomInfoJsonM = isset($GetTravelPlanType['RoomInfoJson']) ? $GetTravelPlanType['RoomInfoJson'] : '';
            if($ispackage == 1){
                $GetCustomerSelectedFlight = $this->_crmcusttravelplan->getFlightDetailForCustomer($TPSysId);
                foreach($GetCustomerSelectedFlight as $key => $value){
                    $GetCustomerSelectedFlightAir[$value['VersionId']] = $value;
                } 
            }
            
            
        }


        $email_id = $param['email_id'];
        $mobileNumber = $param['mobile_number'];
        $route = $JourneyType = $param['flightType'];
        $TravelDate = $param['TravelDate'];
        $cabinclass = $param['cabinclass'];
        $currency = $param['currency'];
        $currencytype = $param['currencytype'];
        $IsLcc = $param['IsLcc'];
        $seatnumber = isset($param['seatnumber']) ? $param['seatnumber'] : [];
        $seatprice = isset($param['seatprice']) ? $param['seatprice'] : [];

        $mealdetails = isset($param['mealdetails']) ? $param['mealdetails'] : [];
        $mealprice = isset($param['mealprice']) ? $param['mealprice'] : [];
        $IsMeal = isset($param['IsMeal']) ? $param['IsMeal'] : 0;
        $baggagedetails = isset($param['baggagedetails']) ? $param['baggagedetails'] : [];
        $baggageprice = isset($param['baggageprice']) ? $param['baggageprice'] : [];

        $paxcount = isset($param['paxcount']) ? $param['paxcount'] : [];
        $adultCount = isset($paxcount[0]) ? $paxcount[0] : 1;
        $childCount = isset($paxcount[1]) ? $paxcount[1] : 0;
        $infantCount = isset($paxcount[2]) ? $paxcount[2] : 0;
        $getSelectedAddon = [];

        
        $memberData = [];
        if ($memberDetails) {
            $i = 1;
            foreach ($memberDetails as $flkey => $value) {

                $firstName = $fname = $param['passenger-firstname-' . $i];
                $lastName = $param['passenger-lastname-' . $i];
                $relation = $param['relation-' . $i];
                $salutation = $param['passenger-salutation-' . $i];
                $cityName = ($param['passenger-city-name-0']) ? $param['passenger-city-name-0'] : '';
                $CitySysId = ($param['passenger-city-1']) ? $param['passenger-city-1'] : 0;
                $passengerCountry = ($param['passenger-country-0']) ? $param['passenger-country-0'] : 0;
                $passengerAddress = ($param['passenger-address-0']) ? $param['passenger-address-0'] : '';

                $passengerDob = isset($param['passenger-dob-' . $i]) ? $param['passenger-dob-' . $i] : '';
                $nationality = isset($param['passenger-nationality-' . $i]) ? $param['passenger-nationality-' . $i] : '';
                $passengerPassportNo = isset($param['passenger-PassportNo-' . $i]) ? $param['passenger-PassportNo-' . $i] : '';
                $PassportExpiry = isset($param['passenger-PassportExpiry-' . $i]) ? $param['passenger-PassportExpiry-' . $i] : '';
                $passporIssue = isset($param['passenger-passporIssue-' . $i]) ? $param['passenger-passporIssue-' . $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');
                $passengerticket = isset($param['passenger-ticket-' . $i]) ? $param['passenger-ticket-' . $i] : '';
                
                if (empty($salutation)) {
                    $response = array('success' => false, 'message' => 'Please select Salutation.', 'index' => 'passenger-salutation-' . $i);
                    echo json_encode($response);
                    exit;
                }
                if (empty($firstName)) {
                    $response = array('success' => false, 'message' => 'Please enter first name.', 'index' => 'passenger-firstname-' . $i);
                    echo json_encode($response);
                    exit;
                }

                if (empty($lastName)) {
                    $response = array('success' => false, 'message' => 'Please enter last name.', 'index' => 'passenger-lastname-' . $i);
                    echo json_encode($response);
                    exit;
                }


                $memberData[$i] = $value;
                $memberData[$i]['Sectors'] = !empty($value['Sectors']) ? $value['Sectors'] : [];
                $memberData[$i]['relation'] = $relation;
                $memberData[$i]['title'] = $salutation;
                $memberData[$i]['passno'] = $passengerPassportNo;
                $memberData[$i]['passisse'] = $passporIssue;
                $memberData[$i]['passexp'] = $PassportExpiry;
                $memberData[$i]['passnational'] = $nationality;
                $memberData[$i]['fname'] = $firstName;
                $memberData[$i]['lname'] = $lastName;
                $memberData[$i]['city'] = $cityName;
                $memberData[$i]['address'] = $passengerAddress;
                $memberData[$i]['CountrySysId'] = $passengerCountry;
                $memberData[$i]['CitySysId'] = $CitySysId;
                $memberData[$i]['dob'] = $passengerDob;
                $memberData[$i]['ticket'] = $passengerticket;
                $i++;
            }
        }

        $FlightBooking = $this->convertinToAPIFormat($param);

//         echo '<pre>===';
//         print_r($FlightBooking);
//         die;
//        die('submitter');
        $interNationalSearch = isset($FlightBooking[0]['IsInternational']) ? $FlightBooking[0]['IsInternational'] : '';
        $SearchTraceId = isset($FlightBooking[0]['bookingId']) ? $FlightBooking[0]['bookingId'] : '';

        $SourceAirportCode = $oneway_origin_text = isset($FlightBooking[0]['SourceAirportCode']) ? $FlightBooking[0]['SourceAirportCode'] : '';
        $DestAirportCode = $oneway_destination_text = isset($FlightBooking[0]['DestAirportCode']) ? $FlightBooking[0]['DestAirportCode'] : '';
        $return_dates_string = isset($FlightBooking[1]['FromUTCTime']) ? $FlightBooking[1]['FromUTCTime'] : '';
        $CurrencyRate = isset($FlightBooking[0]['FairRules']['CurrencyRate']) ? $FlightBooking[0]['FairRules']['CurrencyRate'] : 1;
        if(!empty($RoomInfoJsonM)){
            $roomjson = json_decode($RoomInfoJsonM,1);
        }else{
            $roomjson = array();
            $roomjson[1]['route'] = $route;
            $roomjson[1]['Adult'] = $adultCount;
            $roomjson[1]['Child'] = $childCount;
            $roomjson[1]['Infant'] = $infantCount;
            $roomjson[1]['bedtype'] = '';
            $roomjson[1]['departuredate'] = $TravelDate;
            $roomjson[1]['returndate'] = date('d/m/Y', strtotime($return_dates_string));
            $roomjson[1]['fromaircode'] = $SourceAirportCode;
            $roomjson[1]['toaircode'] = $DestAirportCode;
            $roomjson[1]['airclass'] = $cabinclass;
        }
        

        $FLData = [];
        $BaggageArr = [];
        $MealArr = [];
        $SeatArr = [];
        $segment_ssr = [];
        $customer = [];
        $baggageByPax = [];
        $Sectors = $SectorsForPax = [];
        $TicketNumber = [];
        $BaseFare = 0;
        $PublishedFare = 0;
        $AgencyMarkUpINT_ = 0;
        $AgencyMarkUpGSTINT_ = 0;
        $CommissionEarnedAPI = 0;
//        echo "<pre>";print_r($FlightBooking);die;
        if ($FlightBooking) {
            foreach ($FlightBooking as $k => $value) {

                $BagPrice = 0;
                $MealPrice = 0;
                $SeatPrice = 0;
                $FareBreakdown_ = [];
                $GrossAmount = 0;
                $AgentMarkUp = 0;
                $TotalCommDiscount = 0;
                foreach ($value['FairRules']['FareBreakdown'] as $valueB) {
                    // echo '<pre>';print_r($valueB);
                    $baggageByPax[$valueB['PassengerType']]['Baggage'] = $valueB['Baggage'];
                    $baggageByPax[$valueB['PassengerType']]['CabinBaggage'] = $valueB['CabinBaggage'];
                    $FareBreakdown_[] = array(
                        "Currency" => $valueB['Currency'],
                        "PassengerCount" => $valueB['PassengerCount'],
                        "PassengerType" => $valueB['PassengerType'],
                        "BaseFare" => $valueB['BaseFare'],
                        "Tax" => isset($valueB['Tax']) ? ($valueB['Tax']) : (($valueB['TaxIN'])),
                        "OfferedFare" => ($valueB['OfferedFare']) ? $valueB['OfferedFare'] : 0,
                        "TotalFare" => $valueB['PublishedFare'],
                        "PublishedFare" => $valueB['PublishedFare'],
                        "TDSEarn" => $valueB['TDSEarn'],
                        "MF" => isset($valueB['TaxBR']['MF']) ? $valueB['TaxBR']['MF'] : $valueB['MF'],
                        "YQ" => isset($valueB['TaxBR']['YQ']) ? $valueB['TaxBR']['YQ'] : 0,
                        "AGST" => isset($valueB['TaxBR']['AGST']) ? $valueB['TaxBR']['AGST'] : $valueB['AGST'],
                        "MFT" => isset($valueB['TaxBR']['MFT']) ? $valueB['TaxBR']['MFT'] : $valueB['MFT'],
                        "OT" => isset($valueB['TaxBR']['OT']) ? $valueB['TaxBR']['OT'] : (($valueB['OT'])),
                        "YR" => isset($valueB['TaxBR']['YR']) ? $valueB['TaxBR']['YR'] : $valueB['YR'],
                        "CommissionEarned" => $valueB['CommissionEarned'],
                        "FixedMarkUp" => ($valueB['FixedMarkUp']) ? $valueB['FixedMarkUp'] : 0,
                        "GSTOnMarkUp" => ($valueB['GSTOnMarkUp']) ? $valueB['GSTOnMarkUp'] : 0,
                        "couponVal" => isset($valueB['couponVal']) ? $valueB['couponVal'] : 0,
                        "CommDiscount" => $valueB['CommDiscount'],
                        "AgentMarkUp" => isset($valueB['AgentMarkUp']) ? (($valueB['AgentMarkUp'])) : 0
                    );
                }
                $couponApply = isset($value['FairRules']['couponApply']) ? $value['FairRules']['couponApply'] : 0;
                $couponVal = 0;
                if ($couponApply == 1) {
                    $couponVal = isset($value['FairRules']['couponVal']) ? $value['FairRules']['couponVal'] : 0;
                }

                $BaseFare += (($value['FairRules']['BaseFare'] + $value['FairRules']['Tax']) - $couponVal);
                $PublishedFare += ($value['FairRules']['PublishedFare'] - $couponVal);
                $AgencyMarkUpINT_ += $value['FairRules']['FixedMarkUp'];
                $AgencyMarkUpGSTINT_ += $value['FairRules']['GSTOnMarkUp'];
                $CommissionEarnedAPI += ($value['FairRules']['CommissionEarned'] + $value['FairRules']['TDSEarn']);
                $fareRuless = array(
                    "Currency" => $value['FairRules']['Currency'],
                    "BaseFare" => $value['FairRules']['BaseFare'],
                    "Tax" => isset($value['FairRules']['Tax']) ? (($value['FairRules']['Tax'])) : 0,
                    "PublishedFare" => ($value['FairRules']['PublishedFare']) ? $value['FairRules']['PublishedFare'] : 0,
                    "OfferedFare" => ($value['FairRules']['OfferedFare']) ? $value['FairRules']['OfferedFare'] : 0,
                    "CommissionEarned" => ($value['FairRules']['CommissionEarned']) ? (($value['FairRules']['CommissionEarned'])) : 0,
                    "FixedMarkUp" => ($value['FairRules']['FixedMarkUp']) ? $value['FairRules']['FixedMarkUp'] : 0,
                    "GSTOnMarkUp" => ($value['FairRules']['GSTOnMarkUp']) ? $value['FairRules']['GSTOnMarkUp'] : 0,
                    "CommDiscount" => ($value['FairRules']['CommDiscount']) ? (($value['FairRules']['CommDiscount'])) : 0,
                    "couponVal" => isset($value['FairRules']['couponVal']) ? (($value['FairRules']['couponVal'])) : 0,
                    "TDSEarn" => ($value['FairRules']['TDSEarn']) ? (($value['FairRules']['TDSEarn'])) : 0,
                    "AgentMarkUp" => 0,
                    "BagPrice" => isset($BagPrice) ? $BagPrice : 0,
                    "MealPrice" => isset($MealPrice) ? $MealPrice : 0,
                    "SeatPrice" => isset($SeatPrice) ? $SeatPrice : 0,
                    "FareBreakdown" => $FareBreakdown_
                );
                $segment_ = [];
                
                if ($value['Segments']) {
                    foreach ($value['Segments'] as $seg) {
                        $Sectors[] = $SSRKey = $seg['originAirportCode'] . '-' . $seg['destinationAirportCode'];
                        $SectorsForPax[$SSRKey] = $k;
                        $BagPrice = 0;
                        if (isset($seg['BAGGAGE'])) {
                            foreach ($seg['BAGGAGE'] as $b => $bag) {
                                $BagPrice += isset($bag['Price']) ? $bag['Price'] : 0;
                                $BaggageArr[$b][$SSRKey][] = $bag;
                            }
                        }
                        $MealPrice = 0;
                        if (isset($seg['MEAL'])) {
                            foreach ($seg['MEAL'] as $m => $meals) {
                                $MealPrice += isset($meals['Price']) ? $meals['Price'] : 0;
                                $MealArr[$m][$SSRKey][] = $meals;
                            }
                        }
                        $SeatPrice = 0;
                        if (isset($seg['SEAT'])) {
                            foreach ($seg['SEAT'] as $m => $seats) {
                                $SeatPrice += isset($seats['Price']) ? $seats['Price'] : 0;
                                $SeatArr[$m][$SSRKey][] = $seats;
                            }
                        }

                        $segment_[] = $segment_ssr[$seg['segmentid']] = array(
                            "AirVersionId" => isset($value['AirVersionId']) ? $value['AirVersionId'] : 0,
                            "TPIntSysId" => isset($value['TPIntSysId']) ? $value['TPIntSysId'] : 0,
                            "id" => intval($seg['segmentid']),
                            "flight_booking_id" => '',
                            "TraceId" => $value['SearchTraceId'],
                            "segmentid" => intval($seg['segmentid']),
                            "segmentids" => isset($seg['segmentids']) ? intval($seg['segmentids']) : 0,
                            "isReturnSegment" => $seg['isReturnSegment'],
                            "arrivingnextday" => $seg['arrivingnextday'],
                            "originAirportName" => $seg['originAirportName'],
                            "destinationAirportName" => $seg['destinationAirportName'],
                            "originCityName" => $seg['originCityName'],
                            "originCountryName" => $seg['originCountryName'],
                            "destinationCityName" => $seg['destinationCityName'],
                            "destinationCountryName" => $seg['destinationCountryName'],
                            "destinationAirportCode" => $seg['destinationAirportCode'],
                            "destinationArrTime" => date('Y-m-d H:i', strtotime($seg['destinationArrTime'])),
                            "SegFlightNumber" => $seg['SegFlightNumber'],
                            "AirlineCode" => $seg['AirlineCode'],
                            "AirlineName" => $seg['AirlineName'],
                            "FareClass" => $seg['FareClass'],
                            "cabinClass" => ($seg['cabinClass']) ? $seg['cabinClass'] : $value['FlightClass'],
                            "originAirportCode" => $seg['originAirportCode'],
                            "originDepTime" => date('Y-m-d H:i', strtotime($seg['originDepTime'])),
                            "CheckinBaggage" => !empty($seg['CheckinBaggage']) ? $seg['CheckinBaggage'] : $value['FairRules']['CheckinBaggage'],
                            "CabinBaggage" => !empty($seg['CabinBaggage']) ? $seg['CabinBaggage'] : $value['FairRules']['CabinBaggage'],
                            "IsBaggage" => isset($seg['IsBaggage']) ? $seg['IsBaggage'] : false,
                            "IsMealIncludes" => isset($seg['IsMealIncludes']) ? $seg['IsMealIncludes'] : false,
                            "Duration" => $seg['Duration'],
                            "GroundTime" => $seg['GroundTime'],
                            "NoOfSeatAvailable" => $seg['NoOfSeatAvailable'],
                            "FlightDuration" => $seg['FlightDuration'],
                            "LAYOVERDuration" => $seg['LAYOVERDuration'],
                            "LAYOVERCity" => $seg['LAYOVERCity'],
                            "DepTerminal" => $seg['DepTerminal'],
                            "ArrTerminal" => $seg['ArrTerminal'],
                            "filePath" => isset($seg['filePath']) ? $seg['filePath'] : '',
                            "SourceAirportCode" => $seg['originAirportCode'],
                            "DestAirportCode" => $seg['destinationAirportCode'],
                            "strArrivalDtTime" => $seg['strArrivalDtTime'],
                            "strDepartureDtTime" => $seg['strDepartureDtTime'],
                            "TravelDate" => $seg['originDepTime'],
                            "BagPrice" => $BagPrice,
                            "MealPrice" => $MealPrice,
                            "SeatPrice" => $SeatPrice
                        );
                    }
                }
                
                if($value['JourneyType'] == 3){
                    $TripType = $k+1;
                }else{
                    $TripType = ($k == 0) ? 1 : 2;
                }
                $TicketNumber[] = $value['pnrnumber'];
                $AirVersionId = isset($value['AirVersionId']) ? $value['AirVersionId'] : 0;
                $FLData[$k]['AirVersionId'] = $AirVersionId;
                $FLData[$k]['TPIntSysId'] = isset($value['TPIntSysId']) ? $value['TPIntSysId'] : 0;
                $FLData[$k]['APIBookingId'] = $value['APIBookingId'];
                $FLData[$k]['pnrnumber'] = $value['pnrnumber'];
                $FLData[$k]['gdspnrnumber'] = $value['gdspnrnumber'];
                $FLData[$k]['FlightNumber'] = $value['FlightNumber'];
                $FLData[$k]['AirlineName'] = $value['AirlineName'];
                $FLData[$k]['AirlineCode'] = $value['AirlineCode'];
                $FLData[$k]['SupplierSysId'] = isset($value['SupplierSysId']) ? $value['SupplierSysId'] : 0;
                $FLData[$k]['BookingId'] = isset($value['bookingId']) ? $value['bookingId'] : '';
                $FLData[$k]['APIBookingId'] = isset($value['APIBookingId']) ? $value['APIBookingId'] : '';
                $FLData[$k]['IsLCC'] = $value['IsLCC'];
                $FLData[$k]['LocalFromTime'] = date('Y-m-d H:i', strtotime($value['FromUTCTime']));
                $FLData[$k]['LocalToTime'] = date('Y-m-d H:i', strtotime($value['ToUTCTime']));
                $FLData[$k]['ICSourceSysId'] = $value['ICSourceSysId'];
                $FLData[$k]['apiTraceId'] = $value['SearchTraceId'];
                $FLData[$k]['ApiResultIndex'] = $value['FairRules']['PriceID'];
                $FLData[$k]['JourneyType'] = $value['JourneyType'];
                $FLData[$k]['TripType'] = $TripType; //intval($value['TripType']);
                $FLData[$k]['IsRefundable'] = ($value['IsRefundable']) ? $value['IsRefundable'] : false;
                $FLData[$k]['IsInternational'] = $interNationalSearch;
                $FLData[$k]['SourceAirportCode'] = $value['SourceAirportCode'];
                $FLData[$k]['DestAirportCode'] = $value['DestAirportCode'];
                $FLData[$k]['FairRules'] = $fareRuless;
                $FLData[$k]['Segments'] = $segment_;
                $FLData[$k]['IsB2BProposal'] = $IsB2BProposal;
                $FLData[$k]['AgencySysId'] = $this->intLoggedinAgencyId;
                $FLData[$k]['FARERULE'] = $value['FARERULE'];
                $FLData[$k]['encodedata'] = isset($GetCustomerSelectedFlightAir[$AirVersionId]['encodedata']) ? $GetCustomerSelectedFlightAir[$AirVersionId]['encodedata'] : '';
            }
        }

//         echo '<pre>===';
//         print_r($TicketNumber);
         
        
        $TripCount = count($FlightBooking);
        $ARR_SALUTIONTBO = array("1" => "Mr", "2" => "Mrs", "3" => "Ms", "4" => "Mstr", "5" => "Miss");
        $TotalBG = 0;
        $TotalML = 0;
        $TotalST = 0;

        if ($memberData) {
            $A = 0;
            $C = 0;
            $I = 0;

            $ARR_SALUTION = array_flip($ARR_SALUTIONTBO);
            $ARR_SALUTION_CHILD = array_flip($ARR_SALUTIONTBO);
            
            foreach ($memberData as $kkkk => $ValCustomer) {
                $paxType = $ValCustomer['PaxType'];
                $paxTypeID = $ValCustomer['PaxType'];
                if ($ValCustomer['PaxType'] == 1) {
                    $paxType = 'ADULT-' . $A;
                    $A++;
                } elseif ($ValCustomer['PaxType'] == 2) {
                    $paxType = 'CHILD-' . $C;
                    $C++;
                } else {
                    $paxType = 'INFANT-' . $I;
                    $I++;
                }
                $SelectedSeat = [];
                $paxTypeMeal = [];
                $paxTypeBag = [];
                $BagPrice = 0;
                $MealPrice = 0;
                $SeatPrice_c = 0;
                if($IsMeal == 1){
                    foreach($Sectors as $stKey => $stVlue){
                        if(!isset($paxTypeMeal[$stVlue])){
                            $paxTypeMeal[$stVlue][] = array('Description' => 'Included');
                        }
                    }
                }
                if (isset($MealArr[$paxType])) {
                    foreach ($MealArr[$paxType] as $seckey => $value) {
                        foreach ($value as $va) {
                            $MealPrice += isset($va['Price']) ? $va['Price'] : 0;
                        }
                        $paxTypeMeal[$seckey] = $value;
                    }
                }
                if (isset($BaggageArr[$paxType])) {
                    foreach ($BaggageArr[$paxType] as $seckey => $value) {
                        foreach ($value as $va) {
                            $BagPrice += isset($va['Price']) ? $va['Price'] : 0;
                        }
                        $paxTypeBag[$seckey] = $value;
                    }
                }
                if (isset($SeatArr[$paxType])) {
                    foreach ($SeatArr[$paxType] as $seckey => $value) {
                        foreach ($value as $va) {
                            $SeatPrice_c += isset($va['Price']) ? $va['Price'] : 0;
                        }
                        $SelectedSeat[$seckey] = $value;
                    }
                }

                $CheckinBaggage = isset($baggageByPax[$ValCustomer['PaxType']]['Baggage']) ? $baggageByPax[$ValCustomer['PaxType']]['Baggage'] : '';
                $CabinBaggage = isset($baggageByPax[$ValCustomer['PaxType']]['CabinBaggage']) ? $baggageByPax[$ValCustomer['PaxType']]['CabinBaggage'] : '';

                $TotalBG += (float) $BagPrice;
                $TotalML += (float) $MealPrice;
                $TotalST += (float) $SeatPrice_c;
                $paxTitle = (int)$ValCustomer['title'];
//                if ($ValCustomer['PaxType'] == 1) {
//                    $paxTitle = ($ARR_SALUTION[$ValCustomer['title']]);
//                } elseif ($ValCustomer['PaxType'] == 2) {
//                    $paxTitle = ($ARR_SALUTION_CHILD[$ValCustomer['title']]);
//                } else {
//                    $paxTitle = ($ARR_SALUTION_CHILD[$ValCustomer['title']]);
//                }
                $docid = isset($ValCustomer['docid']) ? $ValCustomer['docid'] : '';
                $ticketN = isset($ValCustomer['ticket']) ? $ValCustomer['ticket'] : '';
                
                $ticket = array();
                foreach($TicketNumber as $tnKey => $tnVlue){
                    $ticket[] = $ticketN; 
                }
                
                
//                $TicketNumberUnq = array_values(array_unique($TicketNumber));
                $TicketNumberUnq = array_values($TicketNumber);
                
                $SectorsForPaxCh = array();
                 
                if($SectorsForPax){
                    foreach($SectorsForPax as $spkey => $spvalue){
                        if(isset($ticket[$spvalue]) && !empty($ticket[$spvalue])){
                            $SectorsForPaxCh[$spkey] = $ticket[$spvalue];
                        } 
                    }
                }
                
                $customer[] = array(
                    "VersionId" => isset($ValCustomer['VersionId']) ? $ValCustomer['VersionId'] : 0,
                    "TPPaxSysId" => $ValCustomer['TPPaxSysId'],
                    "city_id" => $ValCustomer['CitySysId'],
                    "country_id" => $ValCustomer['CountrySysId'],
                    "countryName" => isset($ValCustomer['countryName']) ? $ValCustomer['countryName'] : '',
                    "city" => $ValCustomer['city'],
                    "address" => $ValCustomer['address'],
                    "email" => $email_id,
                    "mobile" => (int) $mobileNumber,
                    "countryCode" => (int) isset($ValCustomer['countrycode']) ? $ValCustomer['countrycode'] : '',
                    "countryCodeISO" => isset($countryCodeISO) ? $countryCodeISO : '',
                    "relation" => isset($ValCustomer['relation']) ? $ValCustomer['relation'] : '9',
                    "firstname" => $ValCustomer['fname'],
                    "lastname" => $ValCustomer['lname'],
                    "salution" => $paxTitle, //$ValCustomer['title'],
                    "dateofbirth" => $ValCustomer['dob'],
                    "docid" => $docid,
                    "isgstapply" => false,
                    "passportnoexpiry" => isset($ValCustomer['passexp']) ? $ValCustomer['passexp'] : '',
                    "passporIssue" => isset($ValCustomer['passisse']) ? $ValCustomer['passisse'] : '',
                    "PassportNationality" => isset($ValCustomer['passnational']) ? $ValCustomer['passnational'] : '',
                    "passportno" => isset($ValCustomer['passno']) ? $ValCustomer['passno'] : '',
                    "paxType" => $ValCustomer['PaxType'],
                    "sectors" => isset($ValCustomer['Sectors']) ? implode('@@', $Sectors) : '',
                    "TicketNumbers" => isset($TicketNumber) ? implode('-', $TicketNumber) : '',
                    "ticketNumberView" => isset($ticket) ? $ticket : array(),
                    "ticketNumberDetails" => isset($SectorsForPaxCh) ? $SectorsForPaxCh : array(),
                    "CheckinBaggage" => isset($CheckinBaggage) ? $CheckinBaggage : '',
                    "CabinBaggage" => isset($CabinBaggage) ? $CabinBaggage : '',
                    "BagPrice" => (!empty($BagPrice)) ? ($BagPrice) : $BagPrice,
                    "MealPrice" => (!empty($MealPrice)) ? ($MealPrice) : $MealPrice,
                    "SeatPrice" => (!empty($SeatPrice_c)) ? ($SeatPrice_c) : $SeatPrice_c,
                    "SelectedBag" => (!empty($paxTypeBag)) ? json_encode($paxTypeBag) : '',
                    "SelectedMeal" => (!empty($paxTypeMeal)) ? json_encode($paxTypeMeal) : '',
                    "SelectedSeat" => (!empty($SelectedSeat)) ? json_encode($SelectedSeat) : ''
                );
            }
        }

//         echo '<pre>';
//         print_r($TotalBG . '==' . $TotalML . '==' . $TotalST);
//         echo '<pre>===';
//         print_r($customer);
//         die;

        $TripCount = count($FlightBooking);
        $FLDataNew = [];
        if ($FLData) {
            foreach ($FLData as $kfl => $vlfl) {
                $vlfl['FairRules']['BagPrice'] = round($TotalBG / $TripCount, 2);
                $vlfl['FairRules']['MealPrice'] = round($TotalML / $TripCount, 2);
                $vlfl['FairRules']['SeatPrice'] = round($TotalST / $TripCount, 2);
                $FLDataNew[$kfl] = $vlfl;
            }
        }
        $customerNew = [];
        if ($customer) {
            foreach ($customer as $kfl => $vlfl) {
                $vlfl['BagPrice'] = round($TotalBG / $TripCount, 2);
                $vlfl['MealPrice'] = round($TotalML / $TripCount, 2);
                $vlfl['SeatPrice'] = round($TotalST / $TripCount, 2);
                $customerNew[$kfl] = $vlfl;
            }
        }
        
        $objAirport = new Travel_Model_TblAirport();
        $objAirport->strAirportCode = $SourceAirportCode;
        $arrSourceCityId = $objAirport->getAirportList();
        $objAirport->strAirportCode = $DestAirportCode;
        $arrdestinationCityId = $objAirport->getAirportList();

        $sourceCityId = isset($arrSourceCityId[0]['CityId']) ? $arrSourceCityId[0]['CityId'] : 0;
        $destinationCityId = isset($arrdestinationCityId[0]['CityId']) ? $arrdestinationCityId[0]['CityId'] : 0;
        $UserSysId = $AgentSysId; ////$sessionFlightSearchParams['UserSysId'];
        $MasterAgencySysId = $this->intLoggedinAgencyId; //$sessionFlightSearchParams['MasterAgencySysId'];
        $FlightBookingDataRiya = array(
            "FlightBookingData" => $FLDataNew,
            "customer" => $customerNew,
            "roominfojson" => $roomjson,
            "Cities" => $oneway_origin_text . '-' . $oneway_destination_text,
            "IsHotelFromApi" => 1,
            "ICSourceSysId" => 9,
            'AgencySysId' => $MasterAgencySysId,
            'AgentSysId' => $UserSysId,
            "SourcePlaces" => $oneway_origin_text,
            "DestinationPlaces" => $oneway_destination_text,
            "SourcePlaceSysId" => $sourceCityId,
            "DestinationPlacesSysId" => $destinationCityId,
            "BaseAmount" => $BaseFare + $TotalBG + $TotalML + $TotalST,
            "PublishedFare" => $PublishedFare + $TotalBG + $TotalML + $TotalST,
            "AgencyMarkUp" => $AgencyMarkUpINT_,
            "AgencyMarkUpGST" => $AgencyMarkUpGSTINT_,
            "AgentCommisionEarned" => $CommissionEarnedAPI,
            "AgentCommisionEarnedGST" => 0,
            "adults" => $adultCount,
            "childs" => $childCount,
            "infants" => $infantCount,
            "route" => $JourneyType,
            "email" => $email_id,
            "mobile" => $mobileNumber,
            "editLeadId" => $editLeadId,
            "ProposalID" => $ProposalID,
            "CustomerSysId" => $CustomerSysId,
            'IsB2BQuery' => $IsB2BProposal,
            'B2BAgentSysId' => $UserSysId,
            'B2BAgencySysId' => $AgencySysId,
            'leadsource' => 'Agency',
            'IsB2BProposal' => $IsB2BProposal,
            'ExchangeCurrencyRate' => $CurrencyRate,
            'APIMode' => 0,
            'IsNewMigration' => 3,
            'IsforPackage' => $ispackage,
            'IsOnlyProposal' => 1,
        );
//        echo "<pre>";print_r($FlightBookingDataRiya);die;
        if ($submitter == 'Preview') {
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/views/scripts/flight-new/');
            $html->assign(array(
                'TaxLabelId' => $this->agencyDetails['TaxLabelId'],
                'bookingDataByAPI' => $FLData,
                'arrtravellerList' => $customer,
                'CustomerDetails' => [],
                'getSupportContact' => [],
                'CurrencyRate' => $this->CurrencyRate,
                'CurrencyTitle' => $this->CurrencyTitle
            ));
            $bodyText = $html->render('preview-ticket.phtml');
            $response = array('success' => true, 'message' => 'success', 'html' => $bodyText);
            echo json_encode($response);
            exit;
        }
        $getData['SecurityKey'] = $this->agencyDetails['SecurityKey'];
        $URL = $this->baseUrl . '/gtxwebservices/flight-api';
//        echo '<pre>';print_r(($FlightBookingDataRiya)); die;
        $GENERATE_FLIGHT_QUERY = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($FlightBookingDataRiya, $getData, $URL);
//         $GENERATE_FLIGHT_QUERY = json_decode('{"status":true,"arrIds":{"MasterTPSysId":3481,"TPSysId":5245,"VersionId":[3830,3831],"CustomerSysId":"329","TrxId":"1896","FareBreakdownid":["372402","372403"]},"redirect":false,"message":"Query Send Successfully."}', 1);
//         echo '<pre>';
//         print_r($GENERATE_FLIGHT_QUERY);
//         die;
        $GTXQueryStatus = isset($GENERATE_FLIGHT_QUERY['status']) ? $GENERATE_FLIGHT_QUERY['status'] : false;
        if ($GTXQueryStatus == 1) {
            $TPSysId = isset($GENERATE_FLIGHT_QUERY['arrIds']['TPSysId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['TPSysId'] : false;
            $MasterTPSysId = !empty($GENERATE_FLIGHT_QUERY['arrIds']['MasterTPSysId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['MasterTPSysId'] : 0;
            $CustomerSysIdGTX = !empty($GENERATE_FLIGHT_QUERY['arrIds']['CustomerSysId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['CustomerSysId'] : 0;
            $TrxId = !empty($GENERATE_FLIGHT_QUERY['arrIds']['TrxId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['TrxId'] : 0;
            $VersionId = !empty($GENERATE_FLIGHT_QUERY['arrIds']['VersionId']) ? $GENERATE_FLIGHT_QUERY['arrIds']['VersionId'] : [];
            $Bookres = [];
            if ($ispackage == 1) {
                $GenerateInstantTicket = $this->GenerateInstantTicket($FlightBookingDataRiya);
                $Bookres = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->SetGTXUpdateData($GenerateInstantTicket, $FlightBookingDataRiya);

                foreach ($FLData as $k => $value) {
                    $response = isset($Bookres[$k]) ? $Bookres[$k] : [];
                    $APIBookingresponse[] = $response;
                    $IsBookingStatus = isset($response['IsBookingStatus']) ? $response['IsBookingStatus'] : 0;
                    if ($IsBookingStatus == 1) {

                        $response['PublishedFare'] = $PublishedFare;
                        $response['MasterTPSysId'] = $MasterTPSysId;
                        $response['TPSysId'] = $TPSysId;
                        $response['TrxId'] = $TrxId;
                        $response['VersionId'] = $VersionId[$k];
                        $response['IsforPackage'] = $ispackage;

                        $URL = $this->baseUrl . "/gtxwebservices/flight-api/updatebooking";
                        $result = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->apiHttpRequest($response, $getData, $URL);
                        // echo '<pre>';
                        // print_r($result);
                        // echo '<pre>';
                        // print_r($response);
                    }
                }
            }

            $arrData = array(
                "FlightBookingData" => $FlightBooking,
                "customer" => $customer,
                "intTPSysId" => $TPSysId,
                "TrxSysId" => $TrxId,
                "post" => $param,
                "GENERATE_FLIGHT_QUERY" => $GENERATE_FLIGHT_QUERY,
                "Bookres" => $Bookres,
                "adultCount" => $adultCount,
                "childCount" => $childCount,
                "infantCount" => $infantCount,
                "CustomerSysId" => $CustomerSysIdGTX,
                "sessionFlightSearchParams" => $sessionFlightSearchParams,
            );
            $tempData = array(
                'TPSysId' => $TPSysId,
                'TraceId' => $SearchTraceId,
                'APIBookingData' => json_encode($arrData),
            );

            // echo '<pre>';
            // print_r($tempData);
            // die;
            $objFlight->deleteFlightTempData($SearchTraceId);
            $objFlight->insertFlightTempData($tempData);

            $response = array('success' => true, 'strUrlData' => $SearchTraceId, 'msg' => 'SUCCESS', 'ispackage' => $ispackage);
            echo json_encode($response);
            exit;
        } else {
            $response = array('success' => true, 'strUrlData' => $SearchTraceId, 'msg' => 'Unabble to create ticket. Please try again or contact with customer support.', 'ispackage' => $ispackage);
            echo json_encode($response);
            exit;
        }
    }

    public function GenerateInstantTicket($post) {
        $status = 'PENDING';
        $Request = $post;
        $passanger = $bookingId = $pnrDetails = $gdsPnrs = $CheckAutoTicket = array();
        $BookingData = (isset($post['FlightBookingData']) && !empty($post['FlightBookingData'])) ? $post['FlightBookingData'] : [];
        $customer = (isset($post['customer']) && !empty($post['customer'])) ? $post['customer'] : [];
        if ($BookingData) {
            foreach ($BookingData as $Data) {

                $SourceAirportCode = trim($Data['SourceAirportCode']);
                $DestAirportCode = trim($Data['DestAirportCode']);
                $OnwardGroupPNR = !empty($Data['pnrnumber']) ? trim($Data['pnrnumber']) : 'PENDING';
                $OnwardGroupGDSPNR = !empty($Data['gdspnrnumber']) ? trim($Data['gdspnrnumber']) : '';
                $OnwardAutoTicket = ($OnwardGroupPNR == 'PENDING') ? false : true;

                $CheckAutoTicket[] = $OnwardAutoTicket;
                if ($OnwardAutoTicket == 1) {
                    $status = 'SUCCESS';
                }
                $bookingId[] = trim($Data['APIBookingId']);
                if (isset($Data['Segments']) && !empty($Data['Segments'])) {
                    foreach ($Data['Segments'] as $sskey => $ssVal) {
                        $pnrDetails[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = $OnwardGroupPNR;
                        $gdsPnrs[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = $OnwardGroupGDSPNR;
                    }
                } else {
                    $pnrDetails = array($SourceAirportCode . '-' . $DestAirportCode => $OnwardGroupPNR);
                }
            }
            if (in_array('0', $CheckAutoTicket)) {
                $status = 'PENDING';
            }
            $ARR_SALUTION = unserialize(ARR_SALUTIONTBO);
            foreach ($customer as $key => $val) {
                $paxtype = $val['paxType'];
                if ($paxtype == 1) {
                    $paxtypeName = 'ADULT';
                    $Salutation = $ARR_SALUTION[$val['salution']];
                } else if ($paxtype == 2) {
                    $paxtypeName = 'CHILD';
                    $Salutation = $ARR_SALUTION[$val['salution']];
                } else {
                    $paxtypeName = 'INFANT';
                    $Salutation = $ARR_SALUTION[$val['salution']];
                }
                $passanger[] = array(
                    'pnrDetails' => $pnrDetails,
                    'gdsPnrs' => $gdsPnrs,
                    'ti' => $Salutation,
                    'pt' => $paxtypeName,
                    'fN' => $val['firstname'],
                    'lN' => $val['lastname'],
                    'id' => $paxtype,
                    'DOB' => isset($val['dateofbirth']) ? $val['dateofbirth'] : '',
                );
            }
            $response = array(
                'status' => array('success' => 1),
                'itemInfos' => array('AIR' => array('travellerInfos' => $passanger)),
                'order' => array('bookingId' => $bookingId, 'status' => $status),
            );
            return $response;
        }
    }

    public function convertinToAPIFormat($param) {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
//        echo "<pre>";print_r($param);die;
        $fareRules = isset($param['fareRules']) ? $param['fareRules'] : '';
        $cancellationPolicy = isset($param['cancellationPolicy']) ? $param['cancellationPolicy'] : '';
        $internalRemarks = isset($param['internalRemarks']) ? $param['internalRemarks'] : '';
        $param['fareRules'] = $fareRules;
        $param['cancellationPolicy'] = $cancellationPolicy;
        $param['internalRemarks'] = $internalRemarks;
        $TPSysId = $param['TPSysId'];
        $isquery = isset($param['isquery']) ? $param['isquery'] : '';
        $ispackage = isset($param['ispackage']) ? $param['ispackage'] : '';
        $memberDetails = isset($param['memberDetails']) ? json_decode($param['memberDetails'], 1) : [];
        $IsMeal = isset($param['IsMeal']) ? $param['IsMeal'] : 0;
        $checkinbag = $param['checkInLuggage'];
        $cabinbag = $param['cabainluggage'];
        $JourneyType = isset($param['flightType']) ? (int) $param['flightType'] : 1;
        $supplier_id = isset($param['supplier_id']) ? (int) $param['supplier_id'] : 0;
        $currency = $param['currency'];
        $currencytype = $param['currencytype'];
        $IsLcc = $param['IsLcc'];
        $paxcount = isset($param['paxcount']) ? $param['paxcount'] : [];
        $adultCount = isset($paxcount[0]) ? $paxcount[0] : 1;
        $childCount = isset($paxcount[1]) ? $paxcount[1] : 0;
        $infantCount = isset($paxcount[2]) ? $paxcount[2] : 0;

        $intMemberCount = ($adultCount + $childCount + $infantCount);
        $refundable = $param['Refundable'];
        $cabinClass = $param['cabinclass'];
        $pnrnumber = $param['pnrnumber'];
        $gdspnrnumber = $param['gdspnrnumber'];
        $bookingId = isset($param['bookingId']) ? $param['bookingId'] : array();

        $FARERULE = [
            'fareRules' => $fareRules,
            'cancellationPolicy' => $cancellationPolicy,
            'internalRemarks' => $internalRemarks,
        ];

        $objAirport = new Travel_Model_TblAirport();
        $Prefix = 'GTX';
        if($this->intLoggedinAgencyId == 207825){
            $Prefix = 'TSURE';
        }else if($this->intLoggedinAgencyId == 2656){
            $Prefix = 'PKG';
        }
        $invBookingID = $searchID = $Prefix . floor(microtime(true) * 1000);
        $TotalJourney = $JourneyType;
        if($JourneyType == 3){
            $TotalJourney = count($bookingId);
        }
        
        $basefare = (isset($param['cost_textbased_1']) && (int)$param['cost_textbased_1'] > 0) ? ($param['cost_textbased_1'] / $TotalJourney) : 0;
        $tax_gst = (isset($param['textBased_gst_1']) && (int)$param['textBased_gst_1'] > 0) ? $param['textBased_gst_1'] : 0;
        $b2cmarkup = (isset($param['markup_textbased_1']) && (int)$param['markup_textbased_1'] > 0) ? ($param['markup_textbased_1'] / $TotalJourney) : 0;
        $b2cdisc = (isset($param['cost_textdisc_1']) && (int)$param['cost_textdisc_1'] > 0) ? ($param['cost_textdisc_1'] / $TotalJourney) : 0;
        $taxes = 0;
        $totalseat = 0;

        $TF = ($basefare + $taxes - $b2cdisc);
        $fC = [
            'NCM' => $b2cdisc,
            'TF' => $TF,
            'TAF' => $taxes,
            'BF' => $basefare,
            'NF' => $TF,
        ];
        $afC = [
            'NCM' => ['TDS' => 0, 'OT' => 0],
            'TAF' => ['MFT' => 0, 'YQ' => 0, 'MF' => 0, 'MU' => $b2cmarkup, 'OT' => ($taxes)],
        ];

        $PaxwiseFare['ADULT'] = [
            'fC' => $fC,
            'afC' => $afC,
            'sR' => $totalseat,
            'rT' => $refundable,
            'cc' => $cabinClass,
            'bI' => ['iB' => $checkinbag, 'cB' => $cabinbag],
            'cB' => '',
            'mI' => ($IsMeal == 1) ? true : false,
            'tax_gst' => $tax_gst,
        ];
        $BaggaeInfo[0]['ADULT'] = ['iB' => $checkinbag, 'cB' => $cabinbag];
        if ($childCount > 0) {
            $basefare = isset($param['cost_textbased_2']) ? ($param['cost_textbased_2'] / $TotalJourney) : 0;
            $b2cmarkup = isset($param['markup_textbased_2']) ? ($param['markup_textbased_2'] / $TotalJourney) : 0;
            $b2cdisc = (isset($param['cost_textdisc_2']) && (int)$param['cost_textdisc_2'] > 0) ? ($param['cost_textdisc_2'] / $TotalJourney) : 0;
            $tax_gst = isset($param['textBased_gst_2']) ? $param['textBased_gst_2'] : 0;
            $BaggaeInfo[1]['CHILD'] = ['iB' => $checkinbag, 'cB' => $cabinbag];
            $TF = ($basefare + $taxes - $b2cdisc);
            $fC = [
                'NCM' => $b2cdisc,
                'TF' => $TF,
                'TAF' => $taxes,
                'BF' => $basefare,
                'NF' => $TF,
            ];
            $afC = [
                'NCM' => ['TDS' => 0, 'OT' => 0],
                'TAF' => ['MFT' => 0, 'YQ' => 0, 'MF' => 0, 'MU' => $b2cmarkup, 'OT' => ($taxes)],
            ];
            $PaxwiseFare['CHILD'] = [
                'fC' => $fC,
                'afC' => $afC,
                'sR' => $totalseat,
                'rT' => $refundable,
                'cc' => $cabinClass,
                'bI' => ['iB' => $checkinbag, 'cB' => $cabinbag],
                'cB' => '',
                'mI' => ($IsMeal == 1) ? true : false,
                'tax_gst' => $tax_gst,
            ];
        }
        if ($infantCount > 0) {
            $BaggaeInfo[3]['INFANT'] = ['iB' => 'NA', 'cB' => $cabinbag];
            $basefare = isset($param['cost_textbased_3']) ? ($param['cost_textbased_3'] / $TotalJourney) : 0;
            $b2cmarkup = isset($param['markup_textbased_3']) ? ($param['markup_textbased_3'] / $TotalJourney) : 0;
            $b2cdisc = (isset($param['cost_textdisc_3']) && (int)$param['cost_textdisc_3'] > 0) ? ($param['cost_textdisc_3'] / $TotalJourney) : 0;
            $tax_gst = isset($param['textBased_gst_3']) ? $param['textBased_gst_3'] : 0;
            $taxes = 0;
            $TF = ($basefare + $taxes - $b2cdisc);
            $fC = [
                'NCM' => $b2cdisc,
                'TF' => $TF,
                'TAF' => $taxes,
                'BF' => $basefare,
                'NF' => $TF,
            ];
            $afC = [
                'NCM' => ['TDS' => 0, 'OT' => 0],
                'TAF' => ['MFT' => 0, 'YQ' => 0, 'MF' => 0, 'MU' => $b2cmarkup, 'OT' => ($taxes)],
            ];
            $PaxwiseFare['INFANT'] = [
                'fC' => $fC,
                'afC' => $afC,
                'sR' => $totalseat,
                'rT' => $refundable,
                'cc' => $cabinClass,
                'bI' => ['iB' => '0 Kg', 'cB' => '0 Kg'],
                'cB' => '',
                'mI' => ($IsMeal == 1) ? true : false,
                'tax_gst' => $tax_gst,
            ];
        }

        $PriceList = [
            'fd' => $PaxwiseFare,
            'fareIdentifier' => 'SPECIAL_DEAL',
            'id' => $invBookingID,
            'autoticket' => true,
            'tai' => '',
            'messages' => '',
        ];

        $TotalMealPrice = 0;
        $TotalSeatPrice = 0;
        $TotalBaggPrice = 0;
        $memberData = [];
        $FareBreakdown = [];
        if ($memberDetails) {
            $i = 1;
            foreach ($memberDetails as $ikey => $value) {

                $firstName = $fname = $param['passenger-firstname-' . $i];
                $lastName = $param['passenger-lastname-' . $i];
                $relation = $param['relation-' . $i];
                $salutation = $param['passenger-salutation-' . $i];
                $cityName = isset($param['passenger-city-name-0']) ? $param['passenger-city-name-0'] : '';
                $CitySysId = isset($param['passenger-city-1']) ? $param['passenger-city-1'] : 0;
                $passengerCountry = isset($param['passenger-country-0']) ? $param['passenger-country-0'] : 0;
                $passengerAddress = isset($param['passenger-address-0']) ? $param['passenger-address-0'] : '';

                $passengerDob = isset($param['passenger-dob-' . $i]) ? $param['passenger-dob-' . $i] : '';
                $nationality = isset($param['passenger-nationality-' . $i]) ? $param['passenger-nationality-' . $i] : '';
                $passengerPassportNo = isset($param['passenger-PassportNo-' . $i]) ? $param['passenger-PassportNo-' . $i] : '';
                $PassportExpiry = isset($param['passenger-PassportExpiry-' . $i]) ? $param['passenger-PassportExpiry-' . $i] : '';
                $passporIssue = isset($param['passenger-passporIssue-' . $i]) ? $param['passenger-passporIssue-' . $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');

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

                if (empty($lastName)) {
                    $response = array('success' => false, 'message' => 'Please enter last name.', 'index' => 'passenger-lastname-' . $i);
                    echo json_encode($response);
                    exit;
                }
                if (empty($salutation)) {
                    $response = array('success' => false, 'message' => 'Please select title.', 'index' => 'passenger-salutation-' . $i);
                    echo json_encode($response);
                    exit;
                }

                $memberData[$i] = $value;
                $memberData[$i]['relation'] = $relation;
                $memberData[$i]['title'] = $salutation;
                $memberData[$i]['passno'] = $passengerPassportNo;
                $memberData[$i]['passisse'] = $passporIssue;
                $memberData[$i]['passexp'] = $PassportExpiry;
                $memberData[$i]['passnational'] = $nationality;
                $memberData[$i]['fname'] = $firstName;
                $memberData[$i]['lname'] = $lastName;
                $memberData[$i]['city'] = $cityName;
                $memberData[$i]['address'] = $passengerAddress;
                $memberData[$i]['CountrySysId'] = $passengerCountry;
                $memberData[$i]['CitySysId'] = $CitySysId;
                $memberData[$i]['dob'] = $passengerDob;
                $i++;
            }
        }

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

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

        $tripInfos = [];
        foreach ($param['airlinename'] as $aKey => $aVal) {
            if ($param['flightType']) {
                $SegmentsArray = [];
                $segmentsBagg = [];
                foreach ($aVal as $aaKey => $aaVal) {
                    if (isset($param['airlinename_id'][$aKey][$aaKey]) && trim($param['airlinename_id'][$aKey][$aaKey]) != '') {
                        $isReturnSegment = (isset($param['isReturnSegment'][$aKey][$aaKey]) && !empty($param['isReturnSegment'][$aKey][$aaKey])) ? $param['isReturnSegment'][$aKey][$aaKey] : 0;
                        $DepartureTime = isset($param['departuretime'][$aKey][$aaKey]) ? $param['departuretime'][$aKey][$aaKey] : 0;
                        $arrivaltime = isset($param['arrivaltime'][$aKey][$aaKey]) ? $param['arrivaltime'][$aKey][$aaKey] : 0;
                        $EstimateHours = isset($param['EstimateHours'][$aKey][$aaKey]) ? $param['EstimateHours'][$aKey][$aaKey] : 0;
                        $TransitTime = isset($param['TransitTime'][$aKey][$aaKey]) ? $param['TransitTime'][$aKey][$aaKey] : '';
                        $AirVersionId = isset($param['AirVersionId'][$aKey][$aaKey]) ? $param['AirVersionId'][$aKey][$aaKey] : 0;
                        $TPIntSysId = isset($param['TPIntSysId'][$aKey][$aaKey]) ? $param['TPIntSysId'][$aKey][$aaKey] : 0;

                        $BaggaeInfo[0]['ADULT'] = ['iB' => $checkinbag, 'cB' => $cabinbag];
                        if ($childCount > 0) {
                            $BaggaeInfo[1]['CHILD'] = ['iB' => $checkinbag, 'cB' => $cabinbag];
                        }
                        if ($infantCount > 0) {
                            $BaggaeInfo[2]['INFANT'] = ['iB' => 'NA', 'cB' => $cabinbag];
                        }

                        $DepartureDate = $FromUTCTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->UTCTime($DepartureTime, 'd/m/y');
                        $ArrivalDate = $ToUTCTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->UTCTime($arrivaltime, 'd/m/y');
                        $strDuration = $EstimateHours;

                        $from = isset($param['fromAirportCode'][$aKey][$aaKey]) ? $param['fromAirportCode'][$aKey][$aaKey] : '';
                        $to = isset($param['toAirportCode'][$aKey][$aaKey]) ? $param['toAirportCode'][$aKey][$aaKey] : '';
                        $SectorKey = $from . '-' . $to;

                        $mealdetails = isset($param['mealdetails'][$aKey][$aaKey]) ? $param['mealdetails'][$aKey][$aaKey] : array();
                        if(empty($mealdetails) && $IsMeal == 1){
                            $mealdetails = array(
                                0 => 'Included'
                            );
                        }
                        $baggagedetails = isset($param['baggagedetails'][$aKey][$aaKey]) ? $param['baggagedetails'][$aKey][$aaKey] : '';
                        $seatnumber = isset($param['seatnumber'][$aKey][$aaKey]) ? $param['seatnumber'][$aKey][$aaKey] : '';

                        $mealprice = isset($param['mealprice'][$aKey][$aaKey]) ? $param['mealprice'][$aKey][$aaKey] : '';
                        $baggageprice = isset($param['baggageprice'][$aKey][$aaKey]) ? $param['baggageprice'][$aKey][$aaKey] : '';
                        $seatprice = isset($param['seatprice'][$aKey][$aaKey]) ? $param['seatprice'][$aKey][$aaKey] : '';

                        $flightnumber = isset($param['flightnumber'][$aKey][$aaKey]) ? $param['flightnumber'][$aKey][$aaKey] : '';
                        $flightnumberEX = explode('-', $flightnumber);

                        $objAirport->strAirportCode = $from;
                        $arrSourceCityId = $objAirport->getAirportList();
                        $objAirport->strAirportCode = $to;
                        $arrdestinationCityId = $objAirport->getAirportList();
                        $filePath = $this->getflightlogo($flightnumberEX[0]);
                        $StopCount = isset($aVal) ? (count($aVal) - 1) : 0;

                        $intCountryCode = trim($arrSourceCityId[0]['CountryCode']);
                        $intOriginCountryCode = trim($arrSourceCityId[0]['CountryCode']);

                        $intdestinationCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
                        $intDestinaionCountryCode = trim($arrdestinationCityId[0]['CountryCode']);

                        if ($intOriginCountryCode != "IN" || empty($intOriginCountryCode)) {
                            $interNationalSearch = true;
                        } else if ($intDestinaionCountryCode != "IN" || empty($intDestinaionCountryCode)) {
                            $interNationalSearch = true;
                        } else {
                            $interNationalSearch = false;
                        }

                        $segmentsBagg[$flightnumberEX[1] . '' . $aaKey] = $BaggaeInfo;
                        $MealArrNew = [];
                        $SeatArrNew = [];
                        $BaggageArrNew = [];
                        if ($mealdetails) {
                            foreach ($mealdetails as $m => $meals) {
                                if (!empty($meals)) {
                                    $TotalMealPrice += (isset($mealprice[$m]) && $mealprice[$m] > 0) ? $mealprice[$m] : 0;
                                    $MealArrNew[$m]['Currency'] = $currency;
                                    $MealArrNew[$m]['key'] = $flightnumberEX[1] . '' . $aaKey;
                                    $MealArrNew[$m]['Code'] = '';
                                    $MealArrNew[$m]['Price'] = isset($mealprice[$m]) ? $mealprice[$m] : 0;
                                    $MealArrNew[$m]['Description'] = $meals;
                                    $MealArrNew[$m]['sector'] = $from . '-' . $to;
                                }
                            }
                        }

//                         echo "<pre>";
//                         print_r($MealArrNew); 
//                         print_r($mealdetails);die;
                        if ($seatnumber) {
                            foreach ($seatnumber as $m => $seat) {
                                if (!empty($seat)) {
                                    $TotalSeatPrice += (isset($seatprice[$m]) && $seatprice[$m] > 0) ? $seatprice[$m] : 0;
                                    $SeatArrNew[$m]['Currency'] = $currency;
                                    $SeatArrNew[$m]['key'] = $flightnumberEX[1] . '' . $aaKey;
                                    $SeatArrNew[$m]['Code'] = $seat;
                                    $SeatArrNew[$m]['Price'] = isset($seatprice[$m]) ? $seatprice[$m] : 0;
                                    $SeatArrNew[$m]['SeatNo'] = $seat;
                                    $SeatArrNew[$m]['sector'] = $from . '-' . $to;
                                }
                            }
                        }
                        if ($baggagedetails) {
                            foreach ($baggagedetails as $b => $bag) {
                                if (!empty($bag)) {
                                    $TotalBaggPrice += (isset($baggageprice[$b]) && $baggageprice[$b] > 0) ? $baggageprice[$b] : 0;
                                    $Weight = str_replace('Excess Baggage - ', '', $bag);
                                    $BaggageArrNew[$b]['Currency'] = $currency;
                                    $BaggageArrNew[$b]['key'] = $flightnumberEX[1] . '' . $aaKey;
                                    $BaggageArrNew[$b]['Code'] = '';
                                    $BaggageArrNew[$b]['Price'] = isset($baggageprice[$b]) ? $baggageprice[$b] : 0;
                                    $BaggageArrNew[$b]['Weight'] = $Weight;
                                    $BaggageArrNew[$b]['sector'] = $from . '-' . $to;
                                }
                            }
                        }
                        $duration = $this->convertToMinutes($strDuration);

                        $DepTerminal = isset($param['fromAirportTerminal'][$aKey][$aaKey]) ? $param['fromAirportTerminal'][$aKey][$aaKey] : '';
                        $ArrTerminal = isset($param['toAirportTerminal'][$aKey][$aaKey]) ? $param['toAirportTerminal'][$aKey][$aaKey] : '';

                        $fromcode = isset($arrSourceCityId[0]['AirportCode']) ? trim($arrSourceCityId[0]['AirportCode']) : '';
                        $fromname = isset($arrSourceCityId[0]['AirportTitle']) ? trim($arrSourceCityId[0]['AirportTitle']) : '';
                        $fromcity = isset($arrSourceCityId[0]['CityName']) ? trim($arrSourceCityId[0]['CityName']) : '';
                        $fromcountry = isset($arrSourceCityId[0]['CountryName']) ? trim($arrSourceCityId[0]['CountryName']) : '';
                        $fromcountryCode = isset($arrSourceCityId[0]['CountryCode']) ? trim($arrSourceCityId[0]['CountryCode']) : '';

                        $fromcode_de = isset($arrdestinationCityId[0]['AirportCode']) ? trim($arrdestinationCityId[0]['AirportCode']) : '';
                        $fromname_de = isset($arrdestinationCityId[0]['AirportTitle']) ? trim($arrdestinationCityId[0]['AirportTitle']) : '';
                        $fromcity_de = isset($arrdestinationCityId[0]['CityName']) ? trim($arrdestinationCityId[0]['CityName']) : '';
                        $fromcountry_de = isset($arrdestinationCityId[0]['CountryName']) ? trim($arrdestinationCityId[0]['CountryName']) : '';
                        $fromcountryCode_de = isset($arrdestinationCityId[0]['CountryCode']) ? trim($arrdestinationCityId[0]['CountryCode']) : '';
                        $ConnectingTime = 0;

                        if (isset($aVal[1]) && $aaKey == 0) {
                            list($hours, $minutes) = explode(":", $strDuration);
                            $ConnectingTime = ($hours * 60) + $minutes;
                        }
                        if (isset($aVal[2]) && $aaKey == 1) {
                            list($hours, $minutes) = explode(":", $strDuration);
                            $ConnectingTime = ($hours * 60) + $minutes;
                        }
                        if (isset($aVal[3]) && $aaKey == 2) {
                            list($hours, $minutes) = explode(":", $strDuration);
                            $ConnectingTime = ($hours * 60) + $minutes;
                        }

                        $SegmentsArray[] = [
                            'id' => $flightnumberEX[1] . '' . $aaKey,
                            'AirVersionId' => $AirVersionId,
                            'TPIntSysId' => $TPIntSysId,
                            'fD' => [
                                'aI' => ['code' => $flightnumberEX[0], 'name' => $aaVal, 'isLcc' => $IsLcc],
                                'fN' => $flightnumber,
                                'eT' => 0,
                            ],
                            'stops' => 0,
                            'layover' => '',
                            'duration' => $duration,
                            'cT' => $ConnectingTime,
                            'cTT' => $TransitTime,
                            'da' => [
                                'code' => $fromcode,
                                'name' => $fromname,
                                'cityCode' => $fromcode,
                                'city' => $fromcity,
                                'country' => $fromcountry,
                                'countryCode' => $fromcountryCode,
                                'terminal' => $DepTerminal,
                            ],
                            'aa' => [
                                'code' => $fromcode_de,
                                'name' => $fromname_de,
                                'cityCode' => $fromcode_de,
                                'city' => $fromcity_de,
                                'country' => $fromcountry_de,
                                'countryCode' => $fromcountryCode_de,
                                'terminal' => $ArrTerminal,
                            ],
                            'dt' => $FromUTCTime,
                            'at' => $ToUTCTime,
                            'iand' => false,
                            'isRs' => $isReturnSegment,
                            'sN' => $aaKey,
                            'isIntSearch' => $interNationalSearch,
                            'ssrInfo' => ['MEAL' => $MealArrNew, 'BAGGAGE' => $BaggageArrNew, 'SEAT' => $SeatArrNew],
                                // 'SeatArrNew' => $SeatArrNew,
                                // 'MealArrNew' => $MealArrNew,
                                // 'BaggageArrNew' => $BaggageArrNew,
                        ];
                    }
                }
                $PriceList['tai'] = ['tbi' => $segmentsBagg];
                $tripInfos[] = [
                    'bookingId' => isset($bookingId[$aKey - 1]) ? $bookingId[$aKey - 1] : '',
                    'sI' => $SegmentsArray,
                    'totalPriceList' => [$PriceList],
                ];
            }
        }

        $conditions = [
            'pcs' => ['pped' => false, 'pid' => false, 'pm' => false, 'dobe' => false],
            'isa' => false,
            'dob' => ['adobr' => false, 'cdobr' => true, 'idobr' => true],
            'isBA' => false,
            'st' => 900,
            'sct' => date('Y-m-d H:i:s'),
            'gst' => ['gstappl' => false, 'igm' => false],
        ];
        $results = [
            'status' => ['success' => true, 'httpStatus' => 200],
            'message' => 'success',
            'tripInfos' => $tripInfos,
            'bookingId' => $invBookingID,
            'conditions' => $conditions,
            'grouppnr' => $pnrnumber,
            'gdspnrnumber' => $gdspnrnumber
        ];
        //echo "<pre>";
        // print_r(json_encode($tripInfos));
        //print_r(($tripInfos));
        //die;
        $AgencyMarkTax['Markup']['Symbol'] = $Symbol;
        $AgencyMarkTax['Markup']['Currency'] = $CurrencyId;

        $tripInfos = $results['tripInfos'];
        $bookingId = $results['bookingId'];
        $alerts = isset($results['alerts']) ? $results['alerts'] : [];
        $IsPassMandatory = isset($results['conditions']['pcs']['pm']) ? $results['conditions']['pcs']['pm'] : false;
        $IsPassExpiry = isset($results['conditions']['pcs']['pped']) ? $results['conditions']['pcs']['pped'] : false;
        $IsPassIssue = isset($results['conditions']['pcs']['pid']) ? $results['conditions']['pcs']['pid'] : false;
        $IsPassDateOfBirth = isset($results['conditions']['pcs']['dobe']) ? $results['conditions']['pcs']['dobe'] : false;
        $isGSTMandatory = isset($results['conditions']['gst']['igm']) ? $results['conditions']['gst']['igm'] : false;
        $isDobAdult = isset($results['conditions']['dob']['adobr']) ? $results['conditions']['dob']['adobr'] : false;
        $isDobChild = isset($results['conditions']['dob']['cdobr']) ? $results['conditions']['dob']['cdobr'] : false;
        $isDobInfant = isset($results['conditions']['dob']['idobr']) ? $results['conditions']['dob']['idobr'] : false;
        $isSeatAppli = isset($results['conditions']['isa']) ? $results['conditions']['isa'] : false;
        $isDocIdAllowedMandatory = isset($results['conditions']['dc']['idm']) ? $results['conditions']['dc']['idm'] : false;
        $isDocIdAllowedAplicable = isset($results['conditions']['dc']['ida']) ? $results['conditions']['dc']['ida'] : false;
        $isHoldAllowed = isset($results['conditions']['isBA']) ? $results['conditions']['isBA'] : false;

        $arrFlightData = [];
        foreach ($tripInfos as $key => $result) {
            $GroupPNR = (isset($pnrnumber[$key]) && !empty($pnrnumber[$key])) ? $pnrnumber[$key] : 'PENDING';
            $GroupGDSPNR = (isset($gdspnrnumber[$key]) && !empty($gdspnrnumber[$key])) ? $gdspnrnumber[$key] : '';
            $totalPriceList = current($result['totalPriceList']);
            $IsRefundable = isset($totalPriceList['fd']['ADULT']['rT']) ? $totalPriceList['fd']['ADULT']['rT'] : 0;
            $NoOfSeatAvailable = $totalPriceList['fd']['ADULT']['sR'];
            $strFareClass = $totalPriceList['fd']['ADULT']['cB']; //Class Of Booking
            $IsMealIncludes = isset($totalPriceList['fd']['ADULT']['mI']) ? $totalPriceList['fd']['ADULT']['mI'] : false;

            $checkinbag = ucfirst(strtolower(str_replace(" ", "", $totalPriceList['fd']['ADULT']['bI']['iB']))); ///Check In Baggage
            $cabinbagInfo = ucfirst(strtolower(str_replace(" ", "", $totalPriceList['fd']['ADULT']['bI']['cB']))); ///Cabin Baggage
            $ResultIndex = $totalPriceList['id'];
            $alertsFare = isset($alerts[$key]) ? $alerts[$key] : [];
            $newFare = isset($alertsFare['newFare']) ? $alertsFare['newFare'] : 0;
            $oldFare = isset($alertsFare['oldFare']) ? $alertsFare['oldFare'] : 0;
            $SegmentInformation = $result['sI'];
            $APIBookingId = isset($result['bookingId']) ? $result['bookingId'] : '';
            $arrSegments = [];
            $FareBreakdown = [];
            $FairRules = [];

            $TotalLAYOVERMinutes = 0;
            $FlyingMinutes = 0;
            $SegFlightNumberArr = [];
            $segmentSector = [];
            $AirVersionIds = [];
            $TPIntSysIds = [];
            if ($SegmentInformation) {
                foreach ($SegmentInformation as $segments) {
                    $StopOverVal = isset($segments['so']) ? count($segments['so']) : 0;
                    $StopPoint = [];
                    $StopOver = false;
                    if ($StopOverVal > 0) {
                        $StopOver = true;
                        foreach ($segments['so'] as $valOs) {
                            $StopPoint[] = [
                                'code' => $valOs['code'],
                                'name' => $valOs['name'],
                                'city' => $valOs['city']
                            ];
                        }
                    }
                    $segmentid = $segments['id'];
                    $AirVersionIds[] = $AirVersionId = isset($segments['AirVersionId']) ? $segments['AirVersionId'] : 0;
                    $TPIntSysIds[] = $TPIntSysId = isset($segments['TPIntSysId']) ? $segments['TPIntSysId'] : 0;
                    $duration = $segments['duration'];
                    $LAYOVERMinutes = $GroundTime = isset($segments['cT']) ? $segments['cT'] : 0;
                    $LAYOVERCity = $LAYOVERCityArr[] = isset($segments['cT']) ? $segments['aa']['city'] : '';
                    $FlyingMinutes += ($duration + $LAYOVERMinutes);
                    $TotalLAYOVERMinutes += $LAYOVERMinutes;

                    $BAGGAGE = isset($segments['ssrInfo']['BAGGAGE']) ? $segments['ssrInfo']['BAGGAGE'] : [];
                    $MEAL = isset($segments['ssrInfo']['MEAL']) ? $segments['ssrInfo']['MEAL'] : [];
                    $SEAT = isset($segments['ssrInfo']['SEAT']) ? $segments['ssrInfo']['SEAT'] : [];
                    $BaggageArr = [];
                    $MealArr = [];
                    $SeatArr = [];
                    if ($BAGGAGE) {
                        foreach ($BAGGAGE as $b => $bag) {
                            $BaggageArr[$b]['symbol'] = $Symbol;
                            $BaggageArr[$b]['Currency'] = $Symbol;
                            $BaggageArr[$b]['key'] = $segments['id'];
                            $BaggageArr[$b]['sector'] = $bag['sector'];
                            $BaggageArr[$b]['Code'] = $bag['code'];
                            $BaggageArr[$b]['Price'] = isset($bag['Price']) ? round((float) $bag['Price'] * $ConvertionRate, 2) : 0;
                            $BaggageArr[$b]['cost'] = isset($bag['Price']) ? $bag['Price'] : 0;
                            $BaggageArr[$b]['Weight'] = $bag['Weight'];
                        }
                    }
                    if ($MEAL) {
                        foreach ($MEAL as $m => $meals) {
                            $MealArr[$m]['symbol'] = $Symbol;
                            $MealArr[$m]['Currency'] = $Symbol;
                            $MealArr[$m]['key'] = $segments['id'];
                            $MealArr[$m]['sector'] = $meals['sector'];
                            $MealArr[$m]['Code'] = $meals['code'];
                            $MealArr[$m]['Price'] = isset($meals['Price']) ? round((float) $meals['Price'] * $ConvertionRate, 2) : 0;
                            $MealArr[$m]['cost'] = isset($meals['Price']) ? (float) $meals['Price'] : 0;
                            $MealArr[$m]['Description'] = $meals['Description'];
                        }
                    }
                    if ($SEAT) {
                        foreach ($SEAT as $m => $seats) {
                            $SeatArr[$m]['symbol'] = $Symbol;
                            $SeatArr[$m]['Currency'] = $Symbol;
                            $SeatArr[$m]['key'] = $segments['id'];
                            $SeatArr[$m]['sector'] = $seats['sector'];
                            $SeatArr[$m]['Code'] = $seats['code'];
                            $SeatArr[$m]['Price'] = isset($seats['Price']) ? round((float) $seats['Price'] * $ConvertionRate, 2) : 0;
                            $SeatArr[$m]['cost'] = isset($seats['Price']) ? (float) $seats['Price'] : 0;
                            $SeatArr[$m]['seatNo'] = $seats['SeatNo'];
                        }
                    }

                    $FareClass = $totalPriceList['fd']['ADULT']['cB'];
                    $strBaggage = ucfirst(strtolower(str_replace(" ", "", $totalPriceList['fd']['ADULT']['bI']['iB']))); ///Checking Baggage
                    $strCabinBaggage = ucfirst(strtolower(str_replace(" ", "", $totalPriceList['fd']['ADULT']['bI']['cB']))); ////Cabin Baggage

                    if (!empty($strCabinBaggage)) {
                        $IscabinbagInc = true;
                    } else {
                        $IscabinbagInc = false;
                    }
                    if (!empty($strBaggage)) {
                        $IscheckinBagInc = true;
                    } else {
                        $IscheckinBagInc = false;
                    }
                    $isReturnSegment = (isset($segments['isRs']) && $segments['isRs']) ? $segments['isRs'] : false;
                    $arrivingnextday = (isset($segments['iand']) && $segments['iand']) ? $segments['iand'] : false;
                    $TripIndicator = (isset($segments['sN']) && $segments['sN']) ? $segments['sN'] : false;

                    $AirlineCode = $segments['fD']['aI']['code'];
                    $AirlineName = $segments['fD']['aI']['name'];
                    $FlightNumber = $segments['fD']['fN'];
                    $SegFlightNumber = $FlightNumber;

                    $originAirportName = $segments['da']['name'];
                    $originAirportCode = $segments['da']['code'];
                    $originCityName = $segments['da']['city'];
                    $originCountryName = $segments['da']['country'];
                    $originDepTime = $segments['dt'];

                    $destinationAirportName = $segments['aa']['name'];
                    $destinationAirportCode = $segments['aa']['code'];
                    $destinationCityName = $segments['aa']['city'];
                    $destinationCountryName = $segments['aa']['country'];
                    $destinationArrTime = $segments['at'];

                    $DepTerminal = isset($segments['da']['terminal']) ? $segments['da']['terminal'] : '';
                    $ArrTerminal = isset($segments['aa']['terminal']) ? $segments['aa']['terminal'] : '';

                    $filePath = $this->getflightlogo($AirlineCode);
                    if(isset($segments['cTT']) && !empty($segments['cTT'])){
                        $LAYOVERDuration = $segments['cTT'];
                    }else{
                        $LAYOVERDuration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->MinutesToHours($LAYOVERMinutes);
                    }
                    

                    $strArrivalDtTime = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getTimeFromApiStringTJ($destinationArrTime);
                    $strDepartureDtTime = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getTimeFromApiStringTJ($originDepTime);
                    $strDuration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($duration);
                    $arrSegments[] = array(
                        "segmentid" => $segmentid,
                        "AirVersionId" => $AirVersionId,
                        "isReturnSegment" => $isReturnSegment,
                        "arrivingnextday" => $arrivingnextday,
                        "originAirportName" => $originAirportName,
                        "destinationAirportName" => $destinationAirportName,
                        "originCityName" => $originCityName,
                        "originCountryName" => $originCountryName,
                        "destinationCityName" => $destinationCityName,
                        "destinationCountryName" => $destinationCountryName,
                        "destinationAirportCode" => $destinationAirportCode,
                        "destinationAirportCode" => $destinationAirportCode,
                        "destinationArrTime" => $destinationArrTime,
                        "SegFlightNumber" => $SegFlightNumber,
                        "AirlineCode" => $AirlineCode,
                        "AirlineName" => $AirlineName,
                        "FareClass" => $FareClass,
                        "cabinClass" => $cabinClass,
                        "originAirportCode" => $originAirportCode,
                        "originDepTime" => $originDepTime,
                        "TripIndicator" => $TripIndicator,
                        "IscheckinBagInc" => $IscheckinBagInc,
                        "IscabinbagInc" => $IscabinbagInc,
                        "CheckinBaggage" => $strBaggage,
                        "CabinBaggage" => $strCabinBaggage,
                        "IsMealIncludes" => $IsMealIncludes,
                        "Duration" => $duration,
                        "StopPoint" => $StopPoint,
                        "StopOver" => $StopOver,
                        "GroundTime" => $GroundTime,
                        "NoOfSeatAvailable" => $NoOfSeatAvailable,
                        "strDepartureDtTime" => $strDepartureDtTime,
                        "strArrivalDtTime" => $strArrivalDtTime,
                        "FlightDuration" => $strDuration,
                        "LAYOVERDuration" => $LAYOVERDuration,
                        "LAYOVERCity" => $LAYOVERCity,
                        "DepTerminal" => $DepTerminal,
                        "ArrTerminal" => $ArrTerminal,
                        "filePath" => $filePath,
                        "BAGGAGE" => $BaggageArr,
                        "MEAL" => $MealArr,
                        "SEAT" => $SeatArr,
                    );
                    $SegFlightNumberArr[] = $SegFlightNumber;
                    $segmentSector[$segmentid] = ['origin' => $originAirportCode, 'destination' => $destinationAirportCode];
                }
            }
            $OriginSegments = current($SegmentInformation);
            $AirlineCode = $OriginSegments['fD']['aI']['code'];

            $tripbaggageinfo = [];
            $PublishedFarePerPax = 0;

            if ($result['totalPriceList']) {
                foreach ($result['totalPriceList'] as $kp => $price) {
                    $fareDetail = $price['fd'];

                    if ($price['tai']['tbi']) {
                        foreach ($price['tai']['tbi'] as $keyss => $tbi) {
                            $segc = isset($segmentSector[$keyss]) ? $segmentSector[$keyss] : '';
                            $sectorKey = $segc['origin'] . '-' . $segc['destination'];
                            if ($tbi) {
                                foreach ($tbi as $kgk => $pbi) {
                                    if ($pbi) {
                                        foreach ($pbi as $gk => $vll) {
                                            $tripbaggageinfo[$sectorKey][$gk] = ['cabin' => isset($vll['cB']) ? $vll['cB'] : 'NA', 'checkin' => isset($vll['iB']) ? $vll['iB'] : 'NA'];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $IsRefundable = isset($fareDetail['ADULT']['rT']) ? $fareDetail['ADULT']['rT'] : 0;
                    $PriceID = $price['id'];
                    $fareIdentifier = $price['fareIdentifier'];
                    $AddMarkup = isset($AdditionalMarkup['finalArr'][$fareIdentifier]) ? $AdditionalMarkup['finalArr'][$fareIdentifier] : [];
                    $colors = !empty($AddMarkup['color']) ? $AddMarkup['color'] : '#000000';

                    $MarkUpValue = isset($AdditionalMarkup['AirlineWiseMarkup'][$AirlineCode]['MarkUpValue']) ? $AdditionalMarkup['AirlineWiseMarkup'][$AirlineCode]['MarkUpValue'] : 0;
                    $AddMarkup['markup_b2b'] = ($AddMarkup['markup_b2b'] + $MarkUpValue);

                    $IsMealIncludes = $fareDetail['ADULT']['mI'];
                    $tax_gst = isset($fareDetail['ADULT']['tax_gst']) ? $fareDetail['ADULT']['tax_gst'] : 0;
                    $AgencyMarkTax['TaxSetting'] = ['TaxPercentage' => $tax_gst, 'TaxType' => 2];

                    $strBaggage = ucfirst(strtolower(str_replace(" ", "", $price['fd']['ADULT']['bI']['iB']))); ///Checking Baggage
                    $strCabinBaggage = ucfirst(strtolower(str_replace(" ", "", $price['fd']['ADULT']['bI']['cB']))); ////Cabin Baggage
                    if (!empty($strCabinBaggage)) {
                        $IscabinbagInc = true;
                    } else {
                        $IscabinbagInc = false;
                    }
                    if (!empty($strBaggage)) {
                        $IscheckinBagInc = true;
                    } else {
                        $IscheckinBagInc = false;
                    }
                    if ($IsRefundable == 0) {
                        $Refundable = 'Non Refundable';
                    } elseif ($IsRefundable == 1) {
                        $Refundable = 'Refundable';
                    } else {
                        $Refundable = 'Partial Refundable';
                    }
                    $fareIdentifier = isset($AdditionalMarkup['finalArr'][$fareIdentifier]['faretype_rename']) ? $AdditionalMarkup['finalArr'][$fareIdentifier]['faretype_rename'] : $fareIdentifier;

                    $classOfBooking = $fareDetail['ADULT']['cB'];
                    $ADULT = $fareDetail['ADULT']['fC']; //fare Components
                    $CHILD = isset($fareDetail['CHILD']['fC']) ? $fareDetail['CHILD']['fC'] : []; //fare Components
                    $INFANT = isset($fareDetail['INFANT']['fC']) ? $fareDetail['INFANT']['fC'] : []; //fare Components

                    $ADULTafC = $fareDetail['ADULT']['afC']['TAF']; //additional fareComponents
                    $CHILDafC = isset($fareDetail['CHILD']['afC']['TAF']) ? $fareDetail['CHILD']['afC']['TAF'] : []; //additional fareComponents
                    $INFANTafC = isset($fareDetail['INFANT']['afC']['TAF']) ? $fareDetail['INFANT']['afC']['TAF'] : []; //additional fareComponents

                    $ADULTNCMTDS = isset($fareDetail['ADULT']['afC']['NCM']['TDS']) ? $fareDetail['ADULT']['afC']['NCM']['TDS'] : 0; //TDS
                    $CHILDNCMTDS = isset($fareDetail['CHILD']['afC']['NCM']['TDS']) ? $fareDetail['CHILD']['afC']['NCM']['TDS'] : 0; //TDS
                    $INFANTNCMTDS = isset($fareDetail['INFANT']['afC']['NCM']['TDS']) ? $fareDetail['INFANT']['afC']['NCM']['TDS'] : 0; //TDS

                    $ADULTNCMTOT = isset($fareDetail['ADULT']['afC']['NCM']['OT']) ? $fareDetail['ADULT']['afC']['NCM']['OT'] : 0; //- Gross Commission
                    $CHILDNCMTOT = isset($fareDetail['CHILD']['afC']['NCM']['OT']) ? $fareDetail['CHILD']['afC']['NCM']['OT'] : 0; //- Gross Commission
                    $INFANTNCMTOT = isset($fareDetail['INFANT']['afC']['NCM']['OT']) ? $fareDetail['INFANT']['afC']['NCM']['OT'] : 0; //- Gross Commission
                    $GrossCommission = ((($ADULTNCMTOT * $adultCount) + ($CHILDNCMTOT * $childCount) + ($INFANTNCMTOT * $infantCount)));
                    $PublishedFare = (($ADULT['TF'] * $adultCount) + ($CHILD['TF'] * $childCount) + ($INFANT['TF'] * $infantCount)); //Total Fare
                    $BaseFare = (($ADULT['BF'] * $adultCount) + ($CHILD['BF'] * $childCount) + ($INFANT['BF'] * $infantCount)); //Base Fare
                    $TaxIN = (($ADULT['TAF'] * $adultCount) + ($CHILD['TAF'] * $childCount) + ($INFANT['TAF'] * $infantCount)); //Taxes and Fees
                    $NetFare = (($ADULT['NF'] * $adultCount) + ($CHILD['NF'] * $childCount) + ($INFANT['NF'] * $infantCount)); //Taxes and Fees
                    $NetCommission = (($ADULT['NCM'] * $adultCount) + ($CHILD['NCM'] * $childCount) + ($INFANT['NCM'] * $infantCount)); //Taxes and Fees
                    $TDS = str_replace('-', '', (($ADULTNCMTDS * $adultCount) + ($CHILDNCMTDS * $childCount) + ($INFANTNCMTDS * $infantCount)));

                    $PublishedFareIN = (($ADULT['TF'] * $adultCount) + ($CHILD['TF'] * $childCount) + ($INFANT['TF'] * $infantCount));

                    $AD_MF = isset($ADULTafC['MF']) ? $ADULTafC['MF'] : 0; //Management Fee
                    $AD_YQ = isset($ADULTafC['YQ']) ? $ADULTafC['YQ'] : 0; //Fuel Surcharge
                    $AD_AGST = isset($ADULTafC['AGST']) ? $ADULTafC['AGST'] : 0; //Airline GST Component
                    $AD_MFT = isset($ADULTafC['MFT']) ? $ADULTafC['MFT'] : 0; //Management Fee Tax
                    $AD_OT = isset($ADULTafC['OT']) ? $ADULTafC['OT'] : 0; //Other Charges
                    $AD_MU = isset($ADULTafC['MU']) ? $ADULTafC['MU'] : 0; //markup
                    $AD_YR = isset($ADULTafC['YR']) ? $ADULTafC['YR'] : 0; //Carrier Misc Fee

                    $CH_MF = isset($CHILDafC['MF']) ? $CHILDafC['MF'] : 0; //Management Fee
                    $CH_YQ = isset($CHILDafC['YQ']) ? $CHILDafC['YQ'] : 0; //Fuel Surcharge
                    $CH_AGST = isset($CHILDafC['AGST']) ? $CHILDafC['AGST'] : 0; //Airline GST Component
                    $CH_MFT = isset($CHILDafC['MFT']) ? $CHILDafC['MFT'] : 0; //Management Fee Tax
                    $CH_OT = isset($CHILDafC['OT']) ? $CHILDafC['OT'] : 0; //Other Charges
                    $CH_MU = isset($CHILDafC['MU']) ? $CHILDafC['MU'] : 0; //markup
                    $CH_YR = isset($CHILDafC['YR']) ? $CHILDafC['YR'] : 0; //Carrier Misc Fee

                    $IN_MF = isset($INFANTafC['MF']) ? $INFANTafC['MF'] : 0; //Management Fee
                    $IN_YQ = isset($INFANTafC['YQ']) ? $INFANTafC['YQ'] : 0; //Fuel Surcharge
                    $IN_AGST = isset($INFANTafC['AGST']) ? $INFANTafC['AGST'] : 0; //Airline GST Component
                    $IN_MFT = isset($INFANTafC['MFT']) ? $INFANTafC['MFT'] : 0; //Management Fee Tax
                    $IN_OT = isset($INFANTafC['OT']) ? $INFANTafC['OT'] : 0; //Other Charges
                    $IN_MU = isset($INFANTafC['MU']) ? $INFANTafC['MU'] : 0; //markup
                    $IN_YR = isset($INFANTafC['YR']) ? $INFANTafC['YR'] : 0; //Carrier Misc Fee

                    $MUFee = (($AD_MU * $adultCount) + ($CH_MU * $childCount) + ($IN_MU * $infantCount));
                    $TaxIN = ($TaxIN - $GrossCommission);
                    $NetFare = ($NetFare - $TDS);
                    $markUpArr = array(
                        'AgentMarkUp' => 0,
                        'getMarkup' => $AgencyMarkTax,
                        'PublishedFare' => $PublishedFare,
                        'OfferedFare' => ($NetFare),
                        'Commission' => $NetCommission,
                        'TDS' => $TDS,
                        'MUFee' => $MUFee,
                        'intMemberCount' => $intMemberCount,
                        'intFlightRoute' => $JourneyType,
                        'interNationalSearch' => $interNationalSearch,
                        'AddMarkup' => [],
                        'IsRPActivated' => false,
                    );

                    $arrMarkUps = $this->calculateMarkup($markUpArr, 'farequote');

                    // if($interNationalSearch == 1 && $JourneyType == 2){
                    //     $BNPLPublishFare = $arrMarkUps['PublishFare'] + $arrMarkUps['FixedMarkUp'] + $arrMarkUps['GSTOnMarkUp'];
                    // }else{
                    //     $BNPLPublishFare = $arrMarkUps['PublishFare'];
                    // }
                    $calculateFlexiPayment = [];

                    $MUFeeBR = (($AD_MU * $adultCount));
                    $TaxINBR = (($ADULT['TAF'] - $ADULTNCMTOT) * $adultCount);
                    $TDSBR = str_replace('-', '', (($ADULTNCMTDS * $adultCount)));
                    $NetFareBR = (($ADULT['NF'] * $adultCount) - $TDSBR);
                    $markUpArrBR = array(
                        'AgentMarkUp' => 0,
                        'getMarkup' => $AgencyMarkTax,
                        'PublishedFare' => ($ADULT['TF'] * $adultCount),
                        'OfferedFare' => ($NetFareBR),
                        'Commission' => ($ADULT['NCM'] * $adultCount),
                        'TDS' => $TDSBR,
                        'MUFee' => $MUFeeBR,
                        'intMemberCount' => $adultCount,
                        'intFlightRoute' => $JourneyType,
                        'interNationalSearch' => $interNationalSearch,
                        'AddMarkup' => [],
                    );

                    $arrMarkUpsBR = $this->calculateMarkup($markUpArrBR, 'farequote');

                    $FareBreakdown[0]['Currency'] = $arrMarkUpsBR['Currency'];
                    $FareBreakdown[0]['PassengerType'] = 1;
                    $FareBreakdown[0]['PaxType'] = 'ADULT';
                    $FareBreakdown[0]['PassengerCount'] = $adultCount;
                    $FareBreakdown[0]['BaseFare'] = round(($ADULT['BF'] * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['Tax'] = round($TaxINBR * $ConvertionRate, 2);
                    $FareBreakdown[0]['OfferedFare'] = round($NetFareBR * $ConvertionRate, 2);
                    $FareBreakdown[0]['PublishedFare'] = round($arrMarkUpsBR['CostToCustomer'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['TDS'] = round($arrMarkUpsBR['TDS'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['TDSEarn'] = round($arrMarkUpsBR['TDSEarn'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['MF'] = round(($AD_MF * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['YQ'] = round(($AD_YQ * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['AGST'] = round(($AD_AGST * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['MFT'] = round(($AD_MFT * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['OT'] = round((($AD_OT - $ADULTNCMTOT) * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['TaxBR']['YR'] = round(($AD_YR * $adultCount) * $ConvertionRate, 2);
                    $FareBreakdown[0]['ApiNCM'] = round($arrMarkUpsBR['IntNetCommission'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['CommissionEarned'] = round($arrMarkUpsBR['CommEarned'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['FixedMarkUp'] = round($arrMarkUpsBR['FixedMarkUp'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['GSTOnMarkUp'] = round($arrMarkUpsBR['GSTOnMarkUp'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['CommDiscount'] = round($arrMarkUpsBR['CommDiscount'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['AgentMarkUp'] = round($arrMarkUpsBR['AgentMarkUp'] * $ConvertionRate, 2);
                    $FareBreakdown[0]['Baggage'] = isset($fareDetail['ADULT']['bI']['iB']) ? $fareDetail['ADULT']['bI']['iB'] : ''; //Check In Baggage;
                    $FareBreakdown[0]['CabinBaggage'] = isset($fareDetail['ADULT']['bI']['cB']) ? $fareDetail['ADULT']['bI']['cB'] : ''; //Cabin Baggage ;

                    if (isset($fareDetail['CHILD']) && $childCount > 0) {
                        $MUFeeBR = (($CH_MU * $childCount));
                        $TaxINBR = (($CHILD['TAF'] - $CHILDNCMTOT) * $childCount);
                        $TDSBR = str_replace('-', '', (($CHILDNCMTDS * $childCount)));
                        $NetFareBR = (($CHILD['NF'] * $childCount) - $TDSBR);

                        $tax_gst = isset($fareDetail['CHILD']['tax_gst']) ? $fareDetail['CHILD']['tax_gst'] : 0;
                        $AgencyMarkTax['TaxSetting'] = ['TaxPercentage' => $tax_gst, 'TaxType' => 2];

                        $markUpArrBR = array(
                            'AgentMarkUp' => 0,
                            'getMarkup' => $AgencyMarkTax,
                            'PublishedFare' => ($CHILD['TF'] * $childCount),
                            'OfferedFare' => ($NetFareBR),
                            'Commission' => ($CHILD['NCM'] * $childCount),
                            'TDS' => $TDSBR,
                            'MUFee' => $MUFeeBR,
                            'intMemberCount' => $childCount,
                            'intFlightRoute' => $JourneyType,
                            'interNationalSearch' => $interNationalSearch,
                            'AddMarkup' => [],
                        );

                        $arrMarkUpsBR = $this->calculateMarkup($markUpArrBR, 'farequote');

                        $FareBreakdown[1]['Currency'] = $arrMarkUpsBR['Currency'];
                        $FareBreakdown[1]['PassengerType'] = 2;
                        $FareBreakdown[1]['PaxType'] = 'CHILD';
                        $FareBreakdown[1]['PassengerCount'] = $childCount;
                        $FareBreakdown[1]['BaseFare'] = round(($CHILD['BF'] * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['Tax'] = round($TaxINBR * $ConvertionRate, 2);
                        $FareBreakdown[1]['OfferedFare'] = round(($NetFareBR * $ConvertionRate), 2);
                        $FareBreakdown[1]['PublishedFare'] = round($arrMarkUpsBR['CostToCustomer'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['TDS'] = round($arrMarkUpsBR['TDS'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['TDSEarn'] = round($arrMarkUpsBR['TDSEarn'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['MF'] = round(($CH_MF * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['YQ'] = round(($CH_YQ * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['AGST'] = round(($CH_AGST * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['MFT'] = round(($CH_MFT * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['OT'] = round((($CH_OT - $CHILDNCMTOT) * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['TaxBR']['YR'] = round(($CH_YR * $childCount) * $ConvertionRate, 2);
                        $FareBreakdown[1]['ApiNCM'] = round($arrMarkUpsBR['IntNetCommission'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['CommissionEarned'] = round($arrMarkUpsBR['CommEarned'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['FixedMarkUp'] = round($arrMarkUpsBR['FixedMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['GSTOnMarkUp'] = round($arrMarkUpsBR['GSTOnMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['CommDiscount'] = round($arrMarkUpsBR['CommDiscount'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['AgentMarkUp'] = round($arrMarkUpsBR['AgentMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[1]['Baggage'] = isset($fareDetail['CHILD']['bI']['iB']) ? $fareDetail['CHILD']['bI']['iB'] : ''; //Check In Baggage;
                        $FareBreakdown[1]['CabinBaggage'] = isset($fareDetail['CHILD']['bI']['cB']) ? $fareDetail['CHILD']['bI']['cB'] : ''; //Cabin Baggage ;
                    }
                    if (isset($fareDetail['INFANT']) && $infantCount > 0) {
                        $MUFeeBR = (($IN_MU * $infantCount));
                        $TaxINBR = (($INFANT['TAF'] - $INFANTNCMTOT) * $infantCount);
                        $TDSBR = str_replace('-', '', (($INFANTNCMTDS * $infantCount)));
                        $NetFareBR = (($INFANT['NF'] * $infantCount) - $TDSBR);

                        $tax_gst = isset($fareDetail['INFANT']['tax_gst']) ? $fareDetail['INFANT']['tax_gst'] : 0;
                        $AgencyMarkTax['TaxSetting'] = ['TaxPercentage' => $tax_gst, 'TaxType' => 2];

                        $markUpArrBR = array(
                            'AgentMarkUp' => 0,
                            'getMarkup' => $AgencyMarkTax,
                            'PublishedFare' => ($INFANT['TF'] * $infantCount),
                            'OfferedFare' => ($NetFareBR),
                            'Commission' => ($INFANT['NCM'] * $infantCount),
                            'TDS' => $TDSBR,
                            'MUFee' => $MUFeeBR,
                            'intMemberCount' => $infantCount,
                            'intFlightRoute' => $JourneyType,
                            'interNationalSearch' => $interNationalSearch,
                            'AddMarkup' => [],
                        );

                        $arrMarkUpsBR = $this->calculateMarkup($markUpArrBR, 'farequote');

                        $FareBreakdown[2]['Currency'] = $arrMarkUpsBR['Currency'];
                        $FareBreakdown[2]['PassengerType'] = 3;
                        $FareBreakdown[2]['PaxType'] = 'INFANT';
                        $FareBreakdown[2]['PassengerCount'] = $infantCount;
                        $FareBreakdown[2]['BaseFare'] = round(($INFANT['BF'] * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['Tax'] = round($TaxINBR * $ConvertionRate, 2);
                        $FareBreakdown[2]['OfferedFare'] = round($NetFareBR * $ConvertionRate, 2);
                        $FareBreakdown[2]['PublishedFare'] = round($arrMarkUpsBR['CostToCustomer'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['TDS'] = round($arrMarkUpsBR['TDS'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['TDSEarn'] = round($arrMarkUpsBR['TDSEarn'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['MF'] = round(($IN_MF * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['YQ'] = round(($IN_YQ * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['AGST'] = round(($IN_AGST * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['MFT'] = round(($IN_MFT * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['OT'] = round((($IN_OT - $INFANTNCMTOT) * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['TaxBR']['YR'] = round(($IN_YR * $infantCount) * $ConvertionRate, 2);
                        $FareBreakdown[2]['ApiNCM'] = round($arrMarkUpsBR['IntNetCommission'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['CommissionEarned'] = round($arrMarkUpsBR['CommEarned'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['FixedMarkUp'] = round($arrMarkUpsBR['FixedMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['GSTOnMarkUp'] = round($arrMarkUpsBR['GSTOnMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['CommDiscount'] = round($arrMarkUpsBR['CommDiscount'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['AgentMarkUp'] = round($arrMarkUpsBR['AgentMarkUp'] * $ConvertionRate, 2);
                        $FareBreakdown[2]['Baggage'] = isset($fareDetail['INFANT']['bI']['iB']) ? $fareDetail['INFANT']['bI']['iB'] : ''; //Check In Baggage;
                        $FareBreakdown[2]['CabinBaggage'] = isset($fareDetail['INFANT']['bI']['cB']) ? $fareDetail['INFANT']['bI']['cB'] : ''; //Cabin Baggage ;
                    }

                    $FairRules = array(
                        "Currency" => $arrMarkUps['Currency'], //$Currency,
                        "CurrencyRate" => $ConvertionRate, //$Currency,
                        "currencySysId" => $arrMarkUps['currencySysId'],
                        "BaseFare" => round($BaseFare * $ConvertionRate, 2),
                        "Tax" => round($TaxIN * $ConvertionRate, 2),
                        "intPublishedFare" => $PublishedFareIN,
                        "PublishedFare" => ceil($arrMarkUps['CostToCustomer'] * $ConvertionRate),
                        "PublishedFareAgent" => ($arrMarkUps['Currency'] == 'INR') ? ceil($arrMarkUps['CostToAgentCustomer'] * $ConvertionRate) : round($arrMarkUps['CostToAgentCustomer'] * $ConvertionRate, 2),
                        "PublishedFarePerPax" => ceil(($arrMarkUps['CostToCustomer'] * $ConvertionRate) / $intMemberCount),
                        "OfferedFare" => round($NetFare * $ConvertionRate, 2),
                        "CommissionEarned" => round($arrMarkUps['CommEarned'] * $ConvertionRate, 2),
                        "CommDiscount" => round($arrMarkUps['CommDiscount'] * $ConvertionRate, 2),
                        "TDS" => round((float) $arrMarkUps['TDS'] * $ConvertionRate, 2),
                        "TDSEarn" => round($arrMarkUps['TDSEarn'] * $ConvertionRate, 2),
                        "Refundable" => $IsRefundable,
                        "IsRefundableTxt" => $Refundable,
                        "PriceID" => $PriceID,
                        "classOfBooking" => $classOfBooking,
                        "FareClass" => $fareDetail['ADULT']['cc'],
                        "fareIdentifier" => str_replace('_', ' ', $fareIdentifier),
                        "IsSpecialReturn" => ($price['fareIdentifier'] == 'SPECIAL_RETURN') ? true : false,
                        "colors" => $colors,
                        "SeatAvailable" => $fareDetail['ADULT']['sR'],
                        "FixedMarkUp" => round($arrMarkUps['FixedMarkUp'] * $ConvertionRate, 2),
                        "GSTOnMarkUp" => round($arrMarkUps['GSTOnMarkUp'] * $ConvertionRate, 2),
                        "AgentMarkUp" => round($arrMarkUps['AgentMarkUp'] * $ConvertionRate, 2),
                        "IscheckinBagInc" => $IscheckinBagInc,
                        "IscabinbagInc" => $IscabinbagInc,
                        "CheckinBaggage" => $strBaggage,
                        "CabinBaggage" => $strCabinBaggage,
                        "IsMealIncludes" => $IsMealIncludes,
                        "FareBreakdown" => array_values($FareBreakdown),
                        "tripbinfo" => $tripbaggageinfo,
                    );
                    $PublishedFarePerPax += ceil(($arrMarkUps['CostToCustomer'] * 1) / $intMemberCount);
                }
            }

            $FareChange = false;

            $OriginSegments = current($SegmentInformation);
            $DestinationSegments = end($SegmentInformation);
            $LAYOVERTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($TotalLAYOVERMinutes);

            $AirlineCode = $OriginSegments['fD']['aI']['code'];
            $FlightNumber = $OriginSegments['fD']['fN'];
            $strFlightNumber = $FlightNumber;
            $strAirlineName = $OriginSegments['fD']['aI']['name'];
            $IsLCC = $OriginSegments['fD']['aI']['isLcc'];
            $strSourceAirportCode = $OriginSegments['da']['code'];
            $strDestinationAirportCode = $DestinationSegments['aa']['code'];
            $StopOverVal = (isset($OriginSegments['so']) && !empty($OriginSegments['so'])) ? $OriginSegments['so'] : [];
            $Stops = (count($StopOverVal) > 0) ? count($StopOverVal) : $DestinationSegments['sN'];

            // $Stops = $DestinationSegments['sN'];
            if ($Stops == 0) {
                $StopCountTxt = "Non-stop";
            } else {
                $StopCountTxt = $Stops . " Stop(s)";
            }
            $filePath = $this->getflightlogo($AirlineCode);

            $FlightDuration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($FlyingMinutes);
            $strArrivalDtTime = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getTimeFromApiStringTJ($DestinationSegments['at']);
            $strDepartureDtTime = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getTimeFromApiStringTJ($OriginSegments['dt']);
            if ($IsPassDateOfBirth && $interNationalSearch) {
                $isDobAdult = true;
                $isDobChild = true;
                $isDobInfant = true;
            }
            $VersionId = array_unique(array_values($AirVersionIds));
            $IntSysId = array_unique(array_values($TPIntSysIds));
            $arrFlightData[$key]['AirVersionId'] = isset($VersionId[0]) ? $VersionId[0] : 0;
            $arrFlightData[$key]['TPIntSysId'] = isset($IntSysId[0]) ? $IntSysId[0] : 0;
            $arrFlightData[$key]['bookingId'] = $searchID;
            $arrFlightData[$key]['APIBookingId'] = !empty($APIBookingId) ? $APIBookingId : $bookingId;
            $arrFlightData[$key]['ApiResultIndex'] = $ResultIndex;
            $arrFlightData[$key]['pnrnumber'] = $GroupPNR;
            $arrFlightData[$key]['gdspnrnumber'] = $GroupGDSPNR;
            $arrFlightData[$key]['FlightNumber'] = $strFlightNumber;
            $arrFlightData[$key]['SupplierSysId'] = $supplier_id;
            $arrFlightData[$key]['SegFlightNumberArr'] = implode(', ', $SegFlightNumberArr);
            $arrFlightData[$key]['AirlineName'] = ucfirst(strtolower($strAirlineName));
            $arrFlightData[$key]['AirlineCode'] = $AirlineCode;
            $arrFlightData[$key]['IsLCC'] = $IsLCC;
            $arrFlightData[$key]['SearchTraceId'] = $searchID;
            $arrFlightData[$key]['IsRefundable'] = $IsRefundable;
            $arrFlightData[$key]['IsRefundableTxt'] = $Refundable;
            $arrFlightData[$key]['FromUTCTime'] = $OriginSegments['dt'];
            $arrFlightData[$key]['ToUTCTime'] = $DestinationSegments['at'];
            $arrFlightData[$key]['FareClass'] = $cabinClass;
            $arrFlightData[$key]['SourceAirportCode'] = $strSourceAirportCode;
            $arrFlightData[$key]['DestAirportCode'] = $strDestinationAirportCode;
            $arrFlightData[$key]['FlightDuration'] = $FlightDuration;
            $arrFlightData[$key]['StopCount'] = $StopCountTxt;
            $arrFlightData[$key]['NoOfSeatAvailable'] = $NoOfSeatAvailable;
            $arrFlightData[$key]['logo'] = $filePath;

            $arrFlightData[$key]['JourneyType'] = $JourneyType;
            $arrFlightData[$key]['TripType'] = 1;
            $arrFlightData[$key]['ICSourceSysId'] = 9;
            $arrFlightData[$key]['IsInternational'] = $interNationalSearch;
            $arrFlightData[$key]['IsPassMandatory'] = $IsPassMandatory;
            $arrFlightData[$key]['IsPassExpiry'] = $IsPassExpiry;
            $arrFlightData[$key]['IsPassIssue'] = $IsPassIssue;
            $arrFlightData[$key]['IsPassDateOfBirth'] = $IsPassDateOfBirth;
            $arrFlightData[$key]['isGSTMandatory'] = $isGSTMandatory;
            $arrFlightData[$key]['isDobAdult'] = $isDobAdult;
            $arrFlightData[$key]['isDobChild'] = $isDobChild;
            $arrFlightData[$key]['isDobInfant'] = $isDobInfant;
            $arrFlightData[$key]['isSeatAppli'] = $isSeatAppli;
            $arrFlightData[$key]['isHoldAllowed'] = $isHoldAllowed;
            $arrFlightData[$key]['isDocIdAllowedMandatory'] = $isDocIdAllowedMandatory;
            $arrFlightData[$key]['isDocIdAllowedAplicable'] = $isDocIdAllowedAplicable;
            $arrFlightData[$key]['Segments'] = $arrSegments;
            $arrFlightData[$key]['FairRules'] = $FairRules;
            $arrFlightData[$key]['FARERULE'] = !empty($FARERULE) ? $FARERULE : [];
        }

        return $arrFlightData;
        // echo '<pre>===============';
        // print_r($arrFlightData);
        // die;
    }

    private function calculateMarkup($data, $types = 'search') {
        $IsRPActivated = (isset($data['IsRPActivated']) && !empty($data['IsRPActivated'])) ? (int) $data['IsRPActivated'] : 0;
        $AddMarkup = isset($data['AddMarkup']) ? $data['AddMarkup'] : [];
        $markup_b2b = isset($AddMarkup['markup_b2b']) ? $AddMarkup['markup_b2b'] : 0;
        $TaxSetting = isset($data['getMarkup']['TaxSetting']) ? $data['getMarkup']['TaxSetting'] : [];
        $getMarkup = isset($data['getMarkup']['Markup']) ? $data['getMarkup']['Markup'] : [];
        $arrApiServiceTax = (isset($TaxSetting['TaxPercentage']) && !empty($TaxSetting['TaxPercentage'])) ? $TaxSetting['TaxPercentage'] : 0;
        $TaxType = (isset($TaxSetting['TaxType']) && !empty($TaxSetting['TaxType'])) ? $TaxSetting['TaxType'] : 2; // 2 On Markup, 1 On Total
        //echo '<pre>';print_r($getMarkup);die;
        $AgentMarkUp = isset($data['AgentMarkUp']) ? $data['AgentMarkUp'] : 0;
        $intMemberCount = isset($data['intMemberCount']) ? $data['intMemberCount'] : 1;
        $intFlightRoute = isset($data['intFlightRoute']) ? $data['intFlightRoute'] : 1;
        $interNationalSearch = isset($data['interNationalSearch']) ? $data['interNationalSearch'] : 0;
        $NetCommission = isset($data['Commission']) ? $data['Commission'] : 0;
        $TDS = isset($data['TDS']) ? str_replace('-', '', $data['TDS']) : 0;
        $getAPIMarkup = isset($data['MUFee']) ? $data['MUFee'] : 0;
        $intPublishedFare = isset($data['PublishedFare']) ? $data['PublishedFare'] : 0;
        $intOfferedFare = isset($data['OfferedFare']) ? $data['OfferedFare'] : 0;

        $TDSApply = (isset($getMarkup['TDS']) && !empty($getMarkup['TDS'])) ? $getMarkup['TDS'] : 0;
        $MarkUpType = (isset($getMarkup['MarkUpType']) && !empty($getMarkup['MarkUpType'])) ? $getMarkup['MarkUpType'] : 0;
        $Symbol = $getMarkup['Symbol'];
        $currencySysId = $getMarkup['Currency'];
        $intCommssionType = $getMarkup['CommssionType']; // 2 For percentage
        $intCommssionVal = ($getMarkup['CommssionVal']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
        // $intAgencyMarkUp = ($getMarkup['StdMarkUpPer'] * $intMemberCount); // Agency Fix Mark UP...
        $IsMarkupDiscount = !empty($getMarkup['IsMarkupDiscount']) ? (int) $getMarkup['IsMarkupDiscount'] : 0;
        $RewardsPoints = !empty($getMarkup['RewardsPoints']) ? (float) $getMarkup['RewardsPoints'] : 0;
        // echo "IsMarkupDiscount($IsMarkupDiscount)";die;
        if ($IsMarkupDiscount == 2) {
            $getMarkup['MarkUpValue'] = -abs($getMarkup['MarkUpValue']);
        }
        if ($MarkUpType == 1) {
            $totalAgencyMarkUp = ($getMarkup['MarkUpValue'] * $intMemberCount); //$intAgencyMarkUp; // Agency Fix Mark UP...
        } else {
            $totalAgencyMarkUp = ((($intOfferedFare * $getMarkup['MarkUpValue']) / 100)); // Agency percentage Mark UP...
        }

        $intAgentMarkUp = ($AgentMarkUp * $intMemberCount); // Agency Fix Mark UP...
        $TDSEarn = 0;
        if ($intCommssionType == 2) {
            $CommissionEarn = (($NetCommission * $intCommssionVal) / 100);
            if ($TDSApply) {
                $TDSEarn = (($TDS * $intCommssionVal) / 100);
            }
        }
        $CommissionEarn = !empty($CommissionEarn) ? $CommissionEarn : 0;
        $TDSEarn = !empty($TDSEarn) ? $TDSEarn : 0;
        if ($interNationalSearch == 1 && $types != 'farequote' && $MarkUpType == 1) {
            $totalAgencyMarkUp = ($totalAgencyMarkUp * $intFlightRoute);
        }
        if ($interNationalSearch == 1 && $types != 'farequote') {
            $markup_b2b = ($markup_b2b * $intFlightRoute);
            $intAgentMarkUp = ($intAgentMarkUp * $intFlightRoute);
        }
        $markup_b2b = ($markup_b2b * $intMemberCount);

        $calculateReverseAdd = $this->calculateServiceTax($markup_b2b, $arrApiServiceTax);
        $AddiMarkup = $markup_b2b;
        $AddiaxOnMarkup = $calculateReverseAdd['serviceTaxAmount'];

        $calculateReverse = $this->calculateServiceTax($getAPIMarkup, $arrApiServiceTax);

        $apiMarkup = !empty($calculateReverse['BasePrice']) ? $calculateReverse['BasePrice'] : 0;
        $apiTaxOnMarkup = !empty($calculateReverse['serviceTaxAmount']) ? $calculateReverse['serviceTaxAmount'] : 0;
        if ($totalAgencyMarkUp > 0) {
            $arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
            $totalTaxOnAgencyMarkUp = ($arrGSTOnAgencyFixMarkUp['serviceTaxAmount'] + $apiTaxOnMarkup);
        } else {
            $totalTaxOnAgencyMarkUp = $apiTaxOnMarkup;
        }
        $CommisionPass = ($NetCommission - $CommissionEarn);

        $totalAgencyMarkUp = ($totalAgencyMarkUp + $apiMarkup + $AddiMarkup);
        $totalTaxOnAgencyMarkUp = ($totalTaxOnAgencyMarkUp + $AddiaxOnMarkup);

        $CostToCustomer = ($intOfferedFare + $totalAgencyMarkUp + $totalTaxOnAgencyMarkUp + $CommissionEarn + $TDSEarn);
        $intAgencyCommisionEarned = ($totalAgencyMarkUp + $CommissionEarn + $TDSEarn);
        $CostToCompany = ($CostToCustomer - $intAgencyCommisionEarned - $totalTaxOnAgencyMarkUp);
        if ($IsRPActivated == 1) {
            $Rewards = $this->calculateServiceTax($CostToCustomer, $RewardsPoints);
            $RewardsEarn = !empty($Rewards['serviceTaxAmount']) ? $Rewards['serviceTaxAmount'] : 0;
        } else {
            $RewardsEarn = 0;
        }
        $dataArr = array(
            'Currency' => $Symbol, // Currency
            'currencySysId' => $currencySysId, // currencySysId
            'IntNetCommission' => round($NetCommission, 2), // GTX Agency Commission Retain %
            'IntCommissionValInPercentage' => round($intCommssionVal, 2), // GTX Agency Commission Retain %
            'CommEarned' => round($CommissionEarn, 2), // GTX agency Comm in Amount
            'CommDiscount' => round($CommisionPass, 2), // GTX agency Comm in Amount
            'FixedMarkUp' => round($totalAgencyMarkUp, 2),
            'GSTOnMarkUp' => round($totalTaxOnAgencyMarkUp, 2),
            "PublishFare" => round($CostToCustomer, 2),
            "CostToCustomer" => round($CostToCustomer, 2),
            "CostToAgentCustomer" => round($CostToCustomer + $intAgentMarkUp, 2),
            "TotalEarning" => round($intAgencyCommisionEarned, 2),
            "CostToCompany" => round($CostToCompany, 2),
            "CostToAgent" => round($CostToCompany, 2),
            'AgentB2CEarning' => ($intAgentMarkUp),
            "intOfferedFare" => $intOfferedFare,
            "intPublishFare" => $intPublishedFare,
            "APIMarkup" => $getAPIMarkup,
            "AgentMarkUp" => $intAgentMarkUp,
            "TDS" => $TDS,
            "TDSEarn" => $TDSEarn,
            "markup_b2b" => $markup_b2b,
            "AddiMarkup" => 0,
            "AddiTaxOnMarkup" => 0,
            "RewardsEarn" => ceil($RewardsEarn),
            "RewardsPoints" => $RewardsPoints,
        );
        return $dataArr;
    }

    function calculateServiceTax($intAmount, $percentAgencySTax) {
        $intAmount = (float) $intAmount;
        $intNetSTax = (($intAmount * (float) $percentAgencySTax) / 100);
        $BasePriceWithSTax = $intNetSTax + $intAmount;
        $arrSerciceTax = array(
            "BasePrice" => $intAmount,
            "serviceTaxAmount" => $intNetSTax,
            "BasePriceWithSTax" => $BasePriceWithSTax,
            "ServiceTaxPercentage" => $percentAgencySTax,
        );
        return $arrSerciceTax;
    }

    function calculateReverse($intAmount, $percentAgencySTax) {
        $intAmount = (float) $intAmount;
        $percentAgencySTax = (float) $percentAgencySTax;
        $TaxAmount = ($intAmount - ($intAmount * (100 / (100 + $percentAgencySTax))));
        $NetPrice = ($intAmount - $TaxAmount);
        return array('NetPrice' => $NetPrice, 'TaxAmount' => $TaxAmount);
    }

    public function convertToMinutes($timeString) {
        // Use regex to extract hours and minutes
        preg_match('/(\d+)h/', $timeString, $hoursMatch);
        preg_match('/(\d+)m/', $timeString, $minutesMatch);

        // Convert extracted values to integers (default to 0 if not found)
        $hours = isset($hoursMatch[1]) ? (int) $hoursMatch[1] : 0;
        $minutes = isset($minutesMatch[1]) ? (int) $minutesMatch[1] : 0;

        // Calculate total minutes
        return ($hours * 60) + $minutes;
    }

    public function getflightlogo($strAirlineCodeLogo) {
        $filePath = $_SERVER['DOCUMENT_ROOT'] . "/public/upload/AirlineLogo/";
        if (file_exists($filePath . $strAirlineCodeLogo . ".gif")) {
            $strAirlineLogo = $strAirlineCodeLogo . ".gif";
            $filePath = $this->baseUrl . "/public/upload/AirlineLogo/" . $strAirlineLogo;
        } elseif (file_exists($filePath . $strAirlineCodeLogo . ".png")) {
            $strAirlineLogo = $strAirlineCodeLogo . ".png";
            $filePath = $this->baseUrl . "/public/upload/AirlineLogo/" . $strAirlineLogo;
        } elseif (file_exists($filePath . $strAirlineCodeLogo . ".jpg")) {
            $strAirlineLogo = $strAirlineCodeLogo . ".jpg";
            $filePath = $this->baseUrl . "/public/upload/AirlineLogo/" . $strAirlineLogo;
        } elseif (file_exists($filePath . $strAirlineCodeLogo . ".jpeg")) {
            $strAirlineLogo = $strAirlineCodeLogo . ".jpeg";
            $filePath = $this->baseUrl . "/public/upload/AirlineLogo/" . $strAirlineLogo;
        } else {
            $filePath = $this->baseUrl . "/public/upload/AirlineLogo/noimage.png";
        }
        return $filePath;
    }
    public function splitFlightArray($flights) {
        $objAirport = new Travel_Model_TblAirport();
        $objFlight = new Travel_Model_TblFlight();
            if (empty($flights)) return ['onward' => [], 'inward' => []];
            if (count($flights) === 1) return ['onward' => $flights, 'inward' => []];

            // 1. Get the starting point coordinates (Home)
            $homeLat = (float)$flights[0]['dep']['latitude'];
            $homeLon = (float)$flights[0]['dep']['longitude'];

            $furthestIndex = 0;
            $maxDistanceSq = 0;
            $AllAirportCodes = $AirlineCodes = [];
            // 2. Identify the "Pivot Point"
            // We look for the arrival airport that is geographically furthest from the start
            foreach ($flights as $index => $flight) {
                
                $dep = $flight['dep']['airportcode'];
                $arr = $flight['arr']['airportcode'];
                $iatacode = $flight['flt']['iatacode'];
                $AllAirportCodes[] = "'" . (string)$dep . "'";
                $AllAirportCodes[] = "'" . (string)$arr . "'";
                $AirlineCodes[] = "'" . (string)$iatacode . "'";
                
                
                
                $lat = (float)$flight['arr']['latitude'];
                $lon = (float)$flight['arr']['longitude'];

                // Simple squared distance (Pythagorean) is enough for comparison
                $distSq = pow($lat - $homeLat, 2) + pow($lon - $homeLon, 2);

                if ($distSq >= $maxDistanceSq) {
                    $maxDistanceSq = $distSq;
                    $furthestIndex = $index;
                }
            }
            
            $onward = array_slice($flights, 0, $furthestIndex + 1);
            $inward =  array_slice($flights, $furthestIndex + 1);
           
            
            $AllAirportCodesStr = implode(',',$AllAirportCodes);
            $getMultipleAirportList = $objAirport->getMultipleAirportList($AllAirportCodesStr);
            $AirlineCodesStr = implode(',',$AirlineCodes);
            $getMultipleAirlineByCode = $objFlight->getMultipleAirlineByCode($AirlineCodesStr);
            
            $getMultipleAirportBYCode = $getMultipleAirlineByCodeArray = array();
            foreach($getMultipleAirportList as $key => $value){
                $getMultipleAirportBYCode[$value['AirportCode']] = $value;
            }
            foreach($getMultipleAirlineByCode as $akey => $avalue){
                $getMultipleAirlineByCodeArray[trim($avalue['Code'])] = $avalue;
            }
            $onwardFinal = $inwardFinal = array();
            foreach ($onward as $i => $flight) {
                $FromAirportDetail = isset($getMultipleAirportBYCode[$flight['dep']['airportcode']]) ? $getMultipleAirportBYCode[$flight['dep']['airportcode']] : array();
                $ToAirportDetail = isset($getMultipleAirportBYCode[$flight['arr']['airportcode']]) ? $getMultipleAirportBYCode[$flight['arr']['airportcode']] : array();
                $flt = $flight['flt']; 
                $AirLineDetail = isset($getMultipleAirlineByCodeArray[$flt['iatacode']]) ? $getMultipleAirlineByCodeArray[$flt['iatacode']] : array();
                
                $departuredate =  date('d/m/Y H:i',strtotime($flt['departure']['string']));
                $arrivaldate =  date('d/m/Y H:i',strtotime($flt['arrival']['string']));
                $transit_timeStr = '';
                if($flt['transit_time']['months'] > 0){
                    $transit_timeStr .= $flt['transit_time']['months'].'mo ';
                }
                if($flt['transit_time']['days'] > 0){
                    $transit_timeStr .= $flt['transit_time']['days'].'d ';
                }
                if($flt['transit_time']['hours'] > 0){
                    $transit_timeStr .= $flt['transit_time']['hours'].'h ';
                }
                if($flt['transit_time']['minutes'] > 0){
                    $transit_timeStr .= $flt['transit_time']['minutes'].'m ';
                }
                $duration = $flt['duration']['hours'].'h '.$flt['duration']['minutes'].'m';
               
                $flightN = array(
                    'FromAirportName' => trim($FromAirportDetail['CityName']).', '. trim($FromAirportDetail['CountryCode']).' - '.trim($FromAirportDetail['AirportTitle']).' ('.trim($FromAirportDetail['AirportCode']).')',
                    'FromAirportCode' => trim($FromAirportDetail['AirportCode']),
                    'FromCityId' => trim($FromAirportDetail['CityId']),
                    'ToAirportName' => trim($ToAirportDetail['CityName']).', '. trim($ToAirportDetail['CountryCode']).' - '.trim($ToAirportDetail['AirportTitle']).' ('.trim($ToAirportDetail['AirportCode']).')',
                    'ToAirportCode' => trim($ToAirportDetail['AirportCode']),
                    'ToCityId' => trim($ToAirportDetail['CityId']),
                    
                    'AirlineSysId' => trim($AirLineDetail['AirlineSysId']),
                    'AirlineTitle' => trim($AirLineDetail['Title']),
                    'AirlineCode' => trim($flt['iatacode']),
                    'FlightNo' => trim($flt['flightNo']),
                    'departuredate' => $departuredate,
                    'arrivaldate' => $arrivaldate,
                    'transit_time' => $transit_timeStr,
                    'duration' => $duration,
                );
                $onwardFinal[] = $flightN;
                 
            }
            foreach ($inward as $i => $flight) {
                $FromAirportDetail = isset($getMultipleAirportBYCode[$flight['dep']['airportcode']]) ? $getMultipleAirportBYCode[$flight['dep']['airportcode']] : array();
                $ToAirportDetail = isset($getMultipleAirportBYCode[$flight['arr']['airportcode']]) ? $getMultipleAirportBYCode[$flight['arr']['airportcode']] : array();
                $flt = $flight['flt']; 
                $AirLineDetail = isset($getMultipleAirlineByCodeArray[$flt['iatacode']]) ? $getMultipleAirlineByCodeArray[$flt['iatacode']] : array();
                
                $departuredate =  date('d/m/Y H:i',strtotime($flt['departure']['string']));
                $arrivaldate =  date('d/m/Y H:i',strtotime($flt['arrival']['string']));
                $transit_timeStr = '';
                if($flt['transit_time']['months'] > 0){
                    $transit_timeStr .= $flt['transit_time']['months'].'mo ';
                }
                if($flt['transit_time']['days'] > 0){
                    $transit_timeStr .= $flt['transit_time']['days'].'d ';
                }
                if($flt['transit_time']['hours'] > 0){
                    $transit_timeStr .= $flt['transit_time']['hours'].'h ';
                }
                if($flt['transit_time']['minutes'] > 0){
                    $transit_timeStr .= $flt['transit_time']['minutes'].'m ';
                }
                $duration = $flt['duration']['hours'].'h '.$flt['duration']['minutes'].'m';
               
                $flightN = array(
                    'FromAirportName' => trim($FromAirportDetail['CityName']).', '. trim($FromAirportDetail['CountryCode']).' - '.trim($FromAirportDetail['AirportTitle']).' ('.trim($FromAirportDetail['AirportCode']).')',
                    'FromAirportCode' => trim($FromAirportDetail['AirportCode']),
                    'FromCityId' => trim($FromAirportDetail['CityId']),
                    'ToAirportName' => trim($ToAirportDetail['CityName']).', '. trim($ToAirportDetail['CountryCode']).' - '.trim($ToAirportDetail['AirportTitle']).' ('.trim($ToAirportDetail['AirportCode']).')',
                    'ToAirportCode' => trim($ToAirportDetail['AirportCode']),
                    'ToCityId' => trim($ToAirportDetail['CityId']),
                    
                    'AirlineSysId' => trim($AirLineDetail['AirlineSysId']),
                    'AirlineTitle' => trim($AirLineDetail['Title']),
                    'AirlineCode' => trim($flt['iatacode']),
                    'FlightNo' => trim($flt['flightNo']),
                    'departuredate' => $departuredate,
                    'arrivaldate' => $arrivaldate,
                    'transit_time' => $transit_timeStr,
                    'duration' => $duration,
                );
                $inwardFinal[] = $flightN;
                 
            }
            return array(
                'onward' => $onwardFinal,
                'inward' => $inwardFinal,
            );
            
        }
    public function getFlightByPnrAction(){
        
        
        if ($this->getRequest()->isPost()) {
            $getData = $this->getRequest()->getPost();
//            echo "<pre>";print_r($getData);die;
            
            $pnr_detail = isset($getData['pnr_detail']) ? trim($getData['pnr_detail']) : '';
            if(empty($pnr_detail)){
                $response = array('status' => false, 'message' => 'PNR can not be blank');
                echo json_encode($response);
                exit;
            }
             
            $curl = curl_init();

            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://api.pnrconverter.com/api',
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'POST',
              CURLOPT_POSTFIELDS => 'pnr='.$pnr_detail,
//              CURLOPT_POSTFIELDS => 'pnr=F04KFN%2FFM%20LONOU%2005Q1FM%20AG%2091205262%2010NOV%20%20%0A%201.1MAJID%2FNAZNEEN%20MRS%20%0A%203%20.%20EK%20%20625%20X%20%2029DEC%20LHEDXB%20HK1%20%201235%20%20%201505%20%20O*%20%20%20%20%20%20%20%20E%20MO%20%20%20%204%20%20%20%0A%204%20.%20EK%20%20%20%205%20X%20%2029DEC%20DXBLHR%20HK1%20%201605%20%20%202000%20%20O*%20%20%20%20%20%20%20%20E%20MO%20%20%20%204',
              CURLOPT_HTTPHEADER => array(
                'PUBLIC_APP_KEY: d0a23c8fc20337afec48106b967727517148b3ab4f21f199e68a2c5c60713277',
                'PRIVATE_APP_KEY: 8OI4tHPm6cdylRAlOcthNfqDzL0oflBcT3w',
                'Content-Type: application/x-www-form-urlencoded'
              ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
//            echo $response;die;
//            $response = '{"flightData":{"info":[{"agencyName":"Catabatic","requestsLeft":65}],"names":[{"fullName":"1JONES/RACHAEL"}],"flights":[{"dep":{"airportname":"New York John F Kennedy Airport","cityname":"","countryname":"United States","airportcode":"JFK","latitude":"40.639801030","longitude":"-73.778900150","timezone":"America/New_York","timezoneshort":"EST"},"arr":{"airportname":"Amsterdam Schiphol Airport","cityname":"Amsterdam","countryname":"Netherlands","airportcode":"AMS","latitude":"52.308601380","longitude":"4.763889790","timezone":"Europe/Amsterdam","timezoneshort":"CET"},"flt":{"flightNo":"46","iatacode":"DL","name":"Delta","operated_by":"Delta","code_share":false,"cabin":"Economy","class":"T","aircraft":null,"departure":{"string":"2026-07-19 16:36","day":"Sun"},"arrival":{"string":"2026-07-20 05:55","day":"Mon"},"transit_time":{"minutes":35,"hours":3,"days":0,"months":0},"duration":{"minutes":"19","hours":"7"},"distance":{"miles":3783,"km":6087},"co2":{"co2":"4.72","co2_with_environmental_impact":"8.93"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/dl.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/dl.png"}},{"dep":{"airportname":"Amsterdam Schiphol Airport","cityname":"Amsterdam","countryname":"Netherlands","airportcode":"AMS","latitude":"52.308601380","longitude":"4.763889790","timezone":"Europe/Amsterdam","timezoneshort":"CET"},"arr":{"airportname":"Zagreb Airport","cityname":"Zagreb","countryname":"Croatia","airportcode":"ZAG","latitude":"45.742900850","longitude":"16.068799970","timezone":"Europe/Zagreb","timezoneshort":"CET"},"flt":{"flightNo":"9355","iatacode":"DL","name":"Delta","operated_by":"Klmcityhoppe As Kl Flt 1939","code_share":true,"cabin":"Economy","class":"T","aircraft":null,"departure":{"string":"2026-07-20 09:30","day":"Mon"},"arrival":{"string":"2026-07-20 11:20","day":"Mon"},"transit_time":{"minutes":50,"hours":3,"days":9,"months":0},"duration":{"minutes":"50","hours":"1"},"distance":{"miles":683,"km":1099},"co2":{"co2":"0.96","co2_with_environmental_impact":"1.81"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/dl.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/dl.png"}},{"dep":{"airportname":"Zagreb Airport","cityname":"Zagreb","countryname":"Croatia","airportcode":"ZAG","latitude":"45.742900850","longitude":"16.068799970","timezone":"Europe/Zagreb","timezoneshort":"CET"},"arr":{"airportname":"Paris Charles de Gaulle Airport","cityname":"Paris","countryname":"France","airportcode":"CDG","latitude":"49.012798310","longitude":"2.549999952","timezone":"Europe/Paris","timezoneshort":"CET"},"flt":{"flightNo":"8329","iatacode":"DL","name":"Delta","operated_by":"Air France As Af Flt 1561","code_share":true,"cabin":"Economy","class":"K","aircraft":null,"departure":{"string":"2026-07-29 15:10","day":"Wed"},"arrival":{"string":"2026-07-29 17:10","day":"Wed"},"transit_time":{"minutes":0,"hours":2,"days":0,"months":0},"duration":{"minutes":"0","hours":"2"},"distance":{"miles":671,"km":1080},"co2":{"co2":"0.94","co2_with_environmental_impact":"1.78"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/dl.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/dl.png"}},{"dep":{"airportname":"Paris Charles de Gaulle Airport","cityname":"Paris","countryname":"France","airportcode":"CDG","latitude":"49.012798310","longitude":"2.549999952","timezone":"Europe/Paris","timezoneshort":"CET"},"arr":{"airportname":"New York John F Kennedy Airport","cityname":"","countryname":"United States","airportcode":"JFK","latitude":"40.639801030","longitude":"-73.778900150","timezone":"America/New_York","timezoneshort":"EST"},"flt":{"flightNo":"1021","iatacode":"DL","name":"Delta","operated_by":"Air France As Af Flt 8","code_share":true,"cabin":"Economy","class":"K","aircraft":null,"departure":{"string":"2026-07-29 19:10","day":"Wed"},"arrival":{"string":"2026-07-29 21:25","day":"Wed"},"transit_time":{},"duration":{"minutes":"15","hours":"8"},"distance":{"miles":3765,"km":6058},"co2":{"co2":"4.70","co2_with_environmental_impact":"8.89"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/dl.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/dl.png"}}],"meta":{"pnr":null}}}';
//            $response = '{"flightData":{"info":[{"agencyName":"Catabatic","requestsLeft":89}],"names":[{"fullName":"1MAHMOOD/MIAN MR"}],"flights":[{"dep":{"airportname":"London Heathrow Airport","cityname":"London","countryname":"United Kingdom","airportcode":"LHR","latitude":"51.470600000","longitude":"-0.461941000","timezone":"Europe/London","timezoneshort":"GMT"},"arr":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"flt":{"flightNo":"2","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"L","aircraft":null,"departure":{"string":"2026-02-02 13:40","day":"Mon"},"arrival":{"string":"2026-02-03 00:40","day":"Tue"},"transit_time":{"minutes":30,"hours":2,"days":0,"months":0},"duration":{"minutes":"0","hours":"7"},"distance":{"miles":3415,"km":5495},"co2":{"co2":"4.26","co2_with_environmental_impact":"8.07"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"arr":{"airportname":"Benazir Bhutto Intl Airport","cityname":"Islamabad","countryname":"Pakistan","airportcode":"ISB","latitude":"33.616699220","longitude":"73.099197390","timezone":"Asia/Karachi","timezoneshort":"PKT"},"flt":{"flightNo":"612","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"L","aircraft":null,"departure":{"string":"2026-02-03 03:10","day":"Tue"},"arrival":{"string":"2026-02-03 07:15","day":"Tue"},"transit_time":{"minutes":45,"hours":1,"days":22,"months":0},"duration":{"minutes":"5","hours":"3"},"distance":{"miles":1210,"km":1947},"co2":{"co2":"1.70","co2_with_environmental_impact":"3.21"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Benazir Bhutto Intl Airport","cityname":"Islamabad","countryname":"Pakistan","airportcode":"ISB","latitude":"33.616699220","longitude":"73.099197390","timezone":"Asia/Karachi","timezoneshort":"PKT"},"arr":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"flt":{"flightNo":"613","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"L","aircraft":null,"departure":{"string":"2026-02-25 09:00","day":"Wed"},"arrival":{"string":"2026-02-25 11:35","day":"Wed"},"transit_time":{"minutes":5,"hours":2,"days":0,"months":0},"duration":{"minutes":"35","hours":"3"},"distance":{"miles":1210,"km":1947},"co2":{"co2":"1.70","co2_with_environmental_impact":"3.21"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"arr":{"airportname":"London Heathrow Airport","cityname":"London","countryname":"United Kingdom","airportcode":"LHR","latitude":"51.470600000","longitude":"-0.461941000","timezone":"Europe/London","timezoneshort":"GMT"},"flt":{"flightNo":"41","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"L","aircraft":null,"departure":{"string":"2026-02-25 13:40","day":"Wed"},"arrival":{"string":"2026-02-25 17:40","day":"Wed"},"transit_time":{},"duration":{"minutes":"0","hours":"8"},"distance":{"miles":3415,"km":5495},"co2":{"co2":"4.26","co2_with_environmental_impact":"8.07"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}}],"meta":{"pnr":null}}}';
//            $response = '{"flightData":{"info":[{"agencyName":"Catabatic","requestsLeft":94}],"names":[{"fullName":"1HASAN/MOHAMMAD MR "},{"fullName":"1KOUSAR/RUKHSANA MRS"},{"fullName":"1HAMZA/MOHAMMAD MR"}],"flights":[{"dep":{"airportname":"London Heathrow Airport","cityname":"London","countryname":"United Kingdom","airportcode":"LHR","latitude":"51.470600000","longitude":"-0.461941000","timezone":"Europe/London","timezoneshort":"GMT"},"arr":{"airportname":"Jeddah King Abdulaziz Intl Airport","cityname":"Jeddah","countryname":"Saudi Arabia","airportcode":"JED","latitude":"21.679600000","longitude":"39.156502000","timezone":"Asia/Riyadh","timezoneshort":"+03"},"flt":{"flightNo":"118","iatacode":"SV","name":"Saudia","operated_by":"Saudia","code_share":false,"cabin":"Economy","class":"T","aircraft":null,"departure":{"string":"2026-03-10 22:05","day":"Tue"},"arrival":{"string":"2026-03-11 07:10","day":"Wed"},"transit_time":{"minutes":30,"hours":10,"days":0,"months":0},"duration":{"minutes":"5","hours":"6"},"distance":{"miles":2928,"km":4712},"co2":{"co2":"3.66","co2_with_environmental_impact":"6.92"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/sv.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/sv.png"}},{"dep":{"airportname":"Jeddah King Abdulaziz Intl Airport","cityname":"Jeddah","countryname":"Saudi Arabia","airportcode":"JED","latitude":"21.679600000","longitude":"39.156502000","timezone":"Asia/Riyadh","timezoneshort":"+03"},"arr":{"airportname":"Benazir Bhutto Intl Airport","cityname":"Islamabad","countryname":"Pakistan","airportcode":"ISB","latitude":"33.616699220","longitude":"73.099197390","timezone":"Asia/Karachi","timezoneshort":"PKT"},"flt":{"flightNo":"726","iatacode":"SV","name":"Saudia","operated_by":"Saudia","code_share":false,"cabin":"Economy","class":"H","aircraft":null,"departure":{"string":"2026-03-11 17:40","day":"Wed"},"arrival":{"string":"2026-03-12 00:20","day":"Thu"},"transit_time":{"minutes":15,"hours":10,"days":22,"months":0},"duration":{"minutes":"40","hours":"4"},"distance":{"miles":2221,"km":3575},"co2":{"co2":"2.77","co2_with_environmental_impact":"5.25"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/sv.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/sv.png"}},{"dep":{"airportname":"Benazir Bhutto Intl Airport","cityname":"Islamabad","countryname":"Pakistan","airportcode":"ISB","latitude":"33.616699220","longitude":"73.099197390","timezone":"Asia/Karachi","timezoneshort":"PKT"},"arr":{"airportname":"Jeddah King Abdulaziz Intl Airport","cityname":"Jeddah","countryname":"Saudi Arabia","airportcode":"JED","latitude":"21.679600000","longitude":"39.156502000","timezone":"Asia/Riyadh","timezoneshort":"+03"},"flt":{"flightNo":"723","iatacode":"SV","name":"Saudia","operated_by":"Saudia","code_share":false,"cabin":"Economy","class":"H","aircraft":null,"departure":{"string":"2026-04-03 10:35","day":"Fri"},"arrival":{"string":"2026-04-03 13:45","day":"Fri"},"transit_time":{"minutes":15,"hours":2,"days":0,"months":0},"duration":{"minutes":"10","hours":"5"},"distance":{"miles":2221,"km":3575},"co2":{"co2":"2.77","co2_with_environmental_impact":"5.25"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/sv.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/sv.png"}},{"dep":{"airportname":"Jeddah King Abdulaziz Intl Airport","cityname":"Jeddah","countryname":"Saudi Arabia","airportcode":"JED","latitude":"21.679600000","longitude":"39.156502000","timezone":"Asia/Riyadh","timezoneshort":"+03"},"arr":{"airportname":"London Heathrow Airport","cityname":"London","countryname":"United Kingdom","airportcode":"LHR","latitude":"51.470600000","longitude":"-0.461941000","timezone":"Europe/London","timezoneshort":"GMT"},"flt":{"flightNo":"117","iatacode":"SV","name":"Saudia","operated_by":"Saudia","code_share":false,"cabin":"Economy","class":"T","aircraft":null,"departure":{"string":"2026-04-03 16:00","day":"Fri"},"arrival":{"string":"2026-04-03 20:30","day":"Fri"},"transit_time":{},"duration":{"minutes":"30","hours":"6"},"distance":{"miles":2928,"km":4712},"co2":{"co2":"3.66","co2_with_environmental_impact":"6.92"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/sv.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/sv.png"}}],"meta":{"pnr":null}}}';
//              $response = '{"flightData":{"info":[{"agencyName":"Catabatic","requestsLeft":92}],"names":[{"fullName":"1MAHMOOD/FAZ MR"}],"flights":[{"dep":{"airportname":"London Stansted Airport","cityname":"London","countryname":"United Kingdom","airportcode":"STN","latitude":"51.884998320","longitude":"0.234999999","timezone":"Europe/London","timezoneshort":"GMT"},"arr":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"flt":{"flightNo":"66","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"Q","aircraft":null,"departure":{"string":"2026-02-10 14:05","day":"Tue"},"arrival":{"string":"2026-02-11 01:00","day":"Wed"},"transit_time":{"minutes":10,"hours":2,"days":0,"months":0},"duration":{"minutes":"55","hours":"6"},"distance":{"miles":3388,"km":5453},"co2":{"co2":"4.23","co2_with_environmental_impact":"8.00"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"arr":{"airportname":"Benazir Bhutto Intl Airport","cityname":"Islamabad","countryname":"Pakistan","airportcode":"ISB","latitude":"33.616699220","longitude":"73.099197390","timezone":"Asia/Karachi","timezoneshort":"PKT"},"flt":{"flightNo":"612","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"Q","aircraft":null,"departure":{"string":"2026-02-11 03:10","day":"Wed"},"arrival":{"string":"2026-02-11 07:15","day":"Wed"},"transit_time":{"minutes":25,"hours":2,"days":9,"months":0},"duration":{"minutes":"5","hours":"3"},"distance":{"miles":1210,"km":1947},"co2":{"co2":"1.70","co2_with_environmental_impact":"3.21"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Alama Iqbal International Airport","cityname":"Lahore","countryname":"Pakistan","airportcode":"LHE","latitude":"31.521600720","longitude":"74.403602600","timezone":"Asia/Karachi","timezoneshort":"PKT"},"arr":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"flt":{"flightNo":"625","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"M","aircraft":null,"departure":{"string":"2026-02-20 09:40","day":"Fri"},"arrival":{"string":"2026-02-20 12:10","day":"Fri"},"transit_time":{"minutes":20,"hours":2,"days":0,"months":0},"duration":{"minutes":"30","hours":"3"},"distance":{"miles":1233,"km":1985},"co2":{"co2":"1.73","co2_with_environmental_impact":"3.28"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"arr":{"airportname":"London Stansted Airport","cityname":"London","countryname":"United Kingdom","airportcode":"STN","latitude":"51.884998320","longitude":"0.234999999","timezone":"Europe/London","timezoneshort":"GMT"},"flt":{"flightNo":"67","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"M","aircraft":null,"departure":{"string":"2026-02-20 14:30","day":"Fri"},"arrival":{"string":"2026-02-20 17:55","day":"Fri"},"transit_time":{},"duration":{"minutes":"25","hours":"7"},"distance":{"miles":3388,"km":5453},"co2":{"co2":"4.23","co2_with_environmental_impact":"8.00"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}}],"meta":{"pnr":null}}}';
//              $response = '{"flightData":{"info":[{"agencyName":"Catabatic","requestsLeft":90}],"names":[{"fullName":"1MAJID/NAZNEEN MRS"}],"flights":[{"dep":{"airportname":"Alama Iqbal International Airport","cityname":"Lahore","countryname":"Pakistan","airportcode":"LHE","latitude":"31.521600720","longitude":"74.403602600","timezone":"Asia/Karachi","timezoneshort":"PKT"},"arr":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"flt":{"flightNo":"625","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"X","aircraft":null,"departure":{"string":"2026-12-29 12:35","day":"Tue"},"arrival":{"string":"2026-12-29 15:05","day":"Tue"},"transit_time":{"minutes":0,"hours":1,"days":0,"months":0},"duration":{"minutes":"30","hours":"3"},"distance":{"miles":1233,"km":1985},"co2":{"co2":"1.73","co2_with_environmental_impact":"3.28"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}},{"dep":{"airportname":"Dubai Intl Airport","cityname":"Dubai","countryname":"United Arab Emirates","airportcode":"DXB","latitude":"25.252799990","longitude":"55.364398960","timezone":"Asia/Dubai","timezoneshort":"+04"},"arr":{"airportname":"London Heathrow Airport","cityname":"London","countryname":"United Kingdom","airportcode":"LHR","latitude":"51.470600000","longitude":"-0.461941000","timezone":"Europe/London","timezoneshort":"GMT"},"flt":{"flightNo":"5","iatacode":"EK","name":"Emirates","operated_by":"Emirates","code_share":false,"cabin":"Economy","class":"X","aircraft":null,"departure":{"string":"2026-12-29 16:05","day":"Tue"},"arrival":{"string":"2026-12-29 20:00","day":"Tue"},"transit_time":{},"duration":{"minutes":"55","hours":"7"},"distance":{"miles":3415,"km":5495},"co2":{"co2":"4.26","co2_with_environmental_impact":"8.07"},"svg-logo-high-res":"https://www.pnrconverter.com/images/airlines/ek.svg","png-logo-low-res":"https://www.pnrconverter.com/images/airlines/png/150/ek.png"}}],"meta":{"pnr":null}}}';
            $responseArray = json_decode($response,1);
            
              
            
            $flights = isset($responseArray['flightData']['flights']) ? $responseArray['flightData']['flights'] : array();
            if(empty($flights)){
                $return = array('status' => false,'message' => 'Incorrect PNR Detail!!');
                echo json_encode($return);exit;
            }
            
            $result = $this->splitFlightArray($flights);
             
//            echo "<pre>"; print_r($onward); die;
            $isReturn = !empty($result['inward']) ? 1 : 0;
            $return = array('status' => true,'isReturn' => $isReturn,'onward' => $result['onward'],'inward' => $result['inward']);
            echo json_encode($return);exit;
            
            
        }
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit