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/patratravelsonline.com/application/modules/flights/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/patratravelsonline.com/application/modules/flights/controllers/SearchController.php
<?php

/* * *************************************************************
 * Catabatic Technology Pvt. Ltd.
 * File Name     : HotelsController.php
 * File Desc.    : Hotels controller for Hotel Search
 * Created By    : Pardeep Panchal <pardeep@catpl.co.in>
 * Created Date  : 14 Nov 2017
 * Updated Date  : 14 Nov 2017
 * ************************************************************* */

class Flights_SearchController extends Catabatic_ValidateCustomer {

    public $baseUrl = '';

    public function init() {
        ini_set('max_execution_time', 300);
        $this->objMdl = new Admin_Model_CRUD();
        $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
        $BootStrap = $aConfig['bootstrap'];

        $this->siteName = $BootStrap['siteName'];
        $this->baseUrl = $BootStrap['siteUrl'];
        $this->superAdminEmail = $BootStrap['superAdminEmail'];
        $this->tollfreenumber = $BootStrap['tollfreenumber'];
        

        $this->gtxwebservicesURL = $BootStrap['gtxwebserviceurl']; // get gtxwebserviceurl from application config
        $this->gtxagencysysid = $BootStrap['gtxagencysysid']; // get gtxagencysysid from application config
        $this->gtxAgentSysid = $BootStrap['gtxagentsysid']; // get gtxagencysysid from application config
        $this->gtxBtoBsite = $BootStrap['gtxBtoBsite']; // get gtxagencysysid from application config
        
        //api urls
        $this->flightSearchUrl      = $this->gtxBtoBsite . "api/flights/flight-search";
        $this->flightFareRulesUrl   = $this->gtxBtoBsite . "api/flights/fare-rules";
        $this->flightFareQuotesUrl  = $this->gtxBtoBsite . "api/flights/fare-quotes";
        $this->flightBookUrl        = $this->gtxBtoBsite . "api/flights/book";
        $this->flightSSRUrl         = $this->gtxBtoBsite . "api/flights/ssr-request";
        $this->flightTicketUrl      = $this->gtxBtoBsite . "api/flights/ticket";
        $this->flightLogoPath       = $_SERVER['DOCUMENT_ROOT'] . "/public/assets/img/airline-logo/";
        //api urls
        
        $this->objMdl = new Admin_Model_CRUD();
        
        $this->objHelperGeneral = $this->_helper->General;
        
    }

    public function indexAction() {
        
        $this->view->baseUrl = $this->baseUrl;
        $this->view->trip_type = $trip_type = $this->getRequest()->getParam('trip_type');
        $this->view->from = $from = $this->getRequest()->getParam('from');
        $this->view->to = $to = $this->getRequest()->getParam('to');
        $this->view->source = $source = $this->getRequest()->getParam('source'); // airport code
        $this->view->destination = $destination = $this->getRequest()->getParam('destination'); // airport code
        $this->view->changeflight = $changeflight = !empty($this->getRequest()->getParam('changeflight'))?$this->getRequest()->getParam('changeflight'):0;
        $this->view->traceid = $traceid = !empty($this->getRequest()->getParam('traceid'))?$this->getRequest()->getParam('traceid'):'';
        
        $this->view->mydevice = $this->objHelperGeneral->getDevice();
        
        $this->view->depart_date = $depart_date = $this->getRequest()->getParam('depart_date');
        if(!empty($depart_date)){
            $arrDepatureDate = explode("/",$depart_date);
            if(count($arrDepatureDate) > 0){
                    $this->view->strDepatureDate = $strDepatureDate = $arrDepatureDate[2]."-".$arrDepatureDate[1]."-".$arrDepatureDate[0];
            }
        }
        
        $this->view->return_date = $return_date = $this->getRequest()->getParam('return_date');
        if(!empty($return_date)){
            $arrReturnDate = explode("/",$return_date);
            if(count($arrReturnDate) > 0){
                $this->view->strReturnDate = $strReturnDate = $arrReturnDate[2]."-".$arrReturnDate[1]."-".$arrReturnDate[0];
            }
        }
        
        $this->view->airlines = $airlines = (count($this->getRequest()->getParam('airline'))>0)?$this->getRequest()->getParam('airline'):NULL;
        $this->view->direct_flight = $direct_flight = ($this->getRequest()->getParam('direct_flight'))?$this->getRequest()->getParam('direct_flight'):false;
        $this->view->cabin_class = $cabin_class = $this->getRequest()->getParam('cabin_class');
        // city & country codes...
        $fromArr = isset($to)?explode("-",$from):'';
        $fromDepartArr = isset($fromArr[0])?explode(",",$fromArr[0]):[];
        $this->view->fromDepartCity = $fromDepartCity = isset($fromDepartArr[0])?trim($fromDepartArr[0]):'';
        $fromDepartCountryCode = isset($fromDepartArr[1])?trim($fromDepartArr[1]):'';

        $destinationArr = isset($to)?explode("-",$to):'';
        $toDestinationArr = isset($destinationArr[0])?explode(",",$destinationArr[0]):[];
        $this->view->destinationCity = $destinationCity = isset($toDestinationArr[0])?trim($toDestinationArr[0]):'';
        $destinationCountryCode = isset($toDestinationArr[1])?trim($toDestinationArr[1]):'';
        
        // check for international airports...
        $this->view->isInternational = $isInternational = false;
        if(($fromDepartCountryCode != "IN" || $destinationCountryCode != "IN")){
            $this->view->isInternational = $isInternational = true;
        }
        
        // city & country codes
        
        $this->view->adults = $adults = $this->getRequest()->getParam('adults');
        $this->view->childs = $childs = $this->getRequest()->getParam('childs');
        $this->view->infants = $infants = $this->getRequest()->getParam('infants');
        
        $this->view->arrPrefferedAirlines = $arrPrefferedAirlines = unserialize(CONST_FLIGHT_PREFERRED_AIRLINES);
        
        $this->view->arrCabinClass = $arrCabinClass = unserialize(CONST_FLIGHT_CABIN_CLASS);
        $cabinClass = isset($arrCabinClass[$cabin_class])?$arrCabinClass[$cabin_class]:'1';
        $travellerBox = "";
        $travellerBox .= ($adults>0)?$adults." Adult(s)":"";
        $travellerBox .= ($childs>0)?", ".$childs." Child(s)":"";
        $travellerBox .= ($infants>0)?", ".$infants." Infant(s)":"";
        $travellerBox .= !empty($cabinClass)?", ".$cabinClass." Class":"";
        $this->view->travellerBox = ($travellerBox)?$travellerBox:"1 Adult(s), Any Class"; 
        
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
            
            $changeflight = $this->getRequest()->getParam('changeflight');
            $traceid = $this->getRequest()->getParam('traceid');
            
            if(empty($changeflight) && empty($traceid)){
                
                $trip_type = $this->getRequest()->getParam('trip_type');
                $source = $this->getRequest()->getParam('source'); // airport code
                $destination = $this->getRequest()->getParam('destination'); // airport code

                $depart_date = $this->getRequest()->getParam('depart_date');
                if(!empty($depart_date)){
                    $arrDepatureDate = explode("/",$depart_date);
                    if(count($arrDepatureDate) > 0){
                            $strDepatureDate = $arrDepatureDate[2]."-".$arrDepatureDate[1]."-".$arrDepatureDate[0];
                    }
                }

                $return_date = $this->getRequest()->getParam('return_date');
                if(!empty($return_date)){
                    $arrReturnDate = explode("/",$return_date);
                    if(count($arrReturnDate) > 0){
                        $strReturnDate = $arrReturnDate[2]."-".$arrReturnDate[1]."-".$arrReturnDate[0];
                    }
                }

                $airlines = (count($this->getRequest()->getParam('airline'))>0)?$this->getRequest()->getParam('airline'):NULL;
                $direct_flight = ($this->getRequest()->getParam('direct_flight'))?$this->getRequest()->getParam('direct_flight'):false;
                $cabin_class = $this->getRequest()->getParam('cabin_class');


                // check for international airports...
    //            $isInternational = false;
    //            if($trip_type == 2 && ($fromDepartCountryCode != "IN" || $destinationCountryCode != "IN")){
    //                $isInternational = true;
    //            }
                // city & country codes

                $adults = $this->getRequest()->getParam('adults');
                $childs = $this->getRequest()->getParam('childs');
                $infants = $this->getRequest()->getParam('infants');



                $datah = [
                    "Origin" => $source,
                    "Destination" => $destination,
                    "AdultCount" => $adults,
                    "ChildCount" => $childs,
                    "InfantCount" => $infants,
                    "JourneyType" => $trip_type,
                    "isInternational" => $isInternational,
                    "FlightCabinClass" => $cabin_class,
                    "DepatureDate" => $strDepatureDate,
                    "ReturnDate" => $strReturnDate,
                    "PreferredAirlines" => $airlines,
                    "DirectFlight" => $direct_flight,
                    "AgencySysId" => $this->gtxagencysysid
                ];
                //echo "<pre>";print_r($datah);exit;
                try {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $this->flightSearchUrl);
                    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        ////                'Content-Type: application/json',                                                                                
        ////                'Content-Length: ' . strlen($data_string)
        //            ));
                    $response = curl_exec($ch);
                } catch (Exception $error) {
                    $response = $error->getMessage();
                }

                $arrResponse = json_decode($response,true);
                //echo "<pre>";print_r($arrResponse);exit;
                $arrResponse['pricerange'] = []; 
                $arrResponse['airlines']   = []; 



                $this->view->traceid = $traceid = isset($arrResponse['traceid'])?$arrResponse['traceid']:'';
                $arrOutbound = isset($arrResponse['outbound'])?$arrResponse['outbound']:[];
                $arrInbound  = isset($arrResponse['inbound'])?$arrResponse['inbound']:[];

                $arrBoth = array_merge($arrOutbound,$arrInbound);
                if(count($arrBoth)>0){
                    $arr = [];
                    $priceArr = [];
                    foreach ($arrBoth as $value){
                        $airlinecode = isset($value['airlinecode'])?$value['airlinecode']:'';

                        if(!in_array([
                                "airlinecode" => $airlinecode,
                                "airlinename" => $value['airline'],
                                "on" => false
                                ], $arr)){
                            $arr[] = [
                                "airlinecode" => $airlinecode,
                                "airlinename" => $value['airline'],
                                "on" => false
                                ];
                        }

                        $publishedfare = isset($value['publishedfare'])?round($value['publishedfare']):0;
                        if(!in_array($publishedfare, $priceArr)){
                            $priceArr[] = $publishedfare;
                        }
                    }

                    $arrResponse['airlines'] = $arr;  // all airlines found in response...

                    // price ranges....
                    sort($priceArr);
                    $last = end($priceArr);
                    $start = 0;
                    $fraction = 5000;
                    $priceArr[] = $last + $fraction;
                    $maximum = end($priceArr);
                    $arrRange = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->getPriceDropdown( $start, $maximum , $fraction , $priceArr );
                    $arrR = [];
                    foreach ($arrRange as $range){
                        $arrR[] = [
                                "type" => "price",
                                "range" => $range,
                                "on" => false
                                ];
                    }


                    $arrResponse['pricerange'] = $arrR;
                    $arrResponse['isInternational'] = ($isInternational)?1:0;
                    // price ranges ends....


                }

                //echo "<pre>";print_r($arrResponse);exit;
                $JSONFileName = $_SERVER['DOCUMENT_ROOT']."/public/data/flight-search/flight_search_".$traceid.".json";
                $strFolder = trim($JSONFileName, basename($JSONFileName));//exit;
                if (!file_exists($strFolder)) {  // if folder does not exists...
                    mkdir($strFolder, 0777, true);
                }
                //echo "<pre>";print_r($arrResponse);exit;
                $filePathToDelete = $_SERVER['DOCUMENT_ROOT']."/public/data/flight-search";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->deleteSearchJsonFile( $filePathToDelete );

                $strresponse = json_encode($arrResponse);

                file_put_contents($JSONFileName, $strresponse);
                $JSONFileName = $_SERVER['DOCUMENT_ROOT']."/public/data/flight-search/flight_search_".$traceid.".json";
                $strJsonResponse = file_get_contents($JSONFileName, $strresponse);
                echo $strJsonResponse;
                exit;
                
                
            }else{
                $JSONFileName = $_SERVER['DOCUMENT_ROOT']."/public/data/flight-search/flight_search_".$traceid.".json";
                $strJsonResponse = file_get_contents($JSONFileName);
                echo $strJsonResponse;
                exit;
            }
            
            
            
        }
        
    }
    
    public function flightFareRuleAction() {
        if ($this->_request->isXmlHttpRequest()) {
            /* Disable Layout */ 
            $this->_helper->layout->disableLayout();
            
            $TraceId =  $this->getRequest()->getParam('apiTraceId');
            $ResultIndex = $this->getRequest()->getParam('ApiResultIndex');
            
            $datah = [
                "TraceId"       => $TraceId,
                "ResultIndex"   => $ResultIndex
            ];
            try {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->flightFareRulesUrl);
                curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    //                'Content-Type: application/json',                                                                                
    //                'Content-Length: ' . strlen($data_string)
                ));
                $response = curl_exec($ch);
            } catch (Exception $error) {
                $response = $error->getMessage();
            }
            
            $arrResponse = json_decode($response,true);
            
            if (isset($arrResponse['Response']['Error']['ErrorCode']) && $arrResponse['Response']['Error']['ErrorCode'] == '0') {
                $this->view->FareRuleDetail = isset($arrResponse['Response']['FareRules'][0]['FareRuleDetail'])?$arrResponse['Response']['FareRules'][0]['FareRuleDetail']:'';
            }
            $this->render('flight-fare-rule');
            
        }
    }
    
    public function reviewDetailsAction(){
        
        if ($this->_request->isXmlHttpRequest()) {
             $this->_helper->layout->disableLayout();
                $postData = $this->getRequest()->getPost();
                
                //echo "<pre>";print_r($postData);exit;
                
                $arrFarequote      = json_decode($postData['fare-quote'],true);
                
                
                $TraceId = isset($arrFarequote['TraceId'])?$arrFarequote['TraceId']:'';
                
                $publishedfare      = ($postData['publishedfare']);
                $BaseFare           = $postData['BaseFare'];
                $gtxMarkup          = $postData['gtxMarkup'];
                $agencyMarkUp       = $postData['agencyMarkUp'];
                $agencyMarkUpGST    = $postData['agencyMarkUpGST'];
                $agencyCommision    = $postData['agencyCommision'];
                $GSTAgencyTotalCommisions    = $postData['GSTAgencyTotalCommisions'];
                $departureDates     = $postData['departureDates'];
                $paxAddress         = $postData['paxaddress'];
                $totalPax         = $postData['totalPax'];
                
                
                
                
                $strCountry = file_get_contents($this->baseUrl."public/data/static/country.json");
                $arrCountry = json_decode($strCountry,true);
                
                
                $arrFareQuote   = json_decode($postData['fare-quote'],true);
                
                $PassengerType = $postData['PassengerType'];
                
                
                for($i=0;$i<count($PassengerType);$i++){
                    $arrPax[$i]['PassengerType'] = $PassengerType[$i];
                    $arrPax[$i]['salutation']    = $postData['salutation'][$i];
                    $arrPax[$i]['firstName']     = $postData['firstName'][$i];
                    $arrPax[$i]['lastName']      = $postData['lastName'][$i];
                    $arrPax[$i]['dob']           = $postData['dob'][$i];
                    
                    $passengerDob = "";
                    if(!empty($postData['dob'][$i])){
                        $arrPassengerDob       = explode("/", $postData['dob'][$i]);
                        $passengerDob       = $arrPassengerDob[2]."-".$arrPassengerDob[1]."-".$arrPassengerDob[0];
                    }
                    
                    
                    if($i == 0){
                        $arrPax[$i]['paxCity']         = $postData['city'];
                        $arrPax[$i]['paxCountryCode']  = $postData['country'];
                        $arrPax[$i]['paxCountryName']  = $arrCountry[$postData['country']];
                        $arrPax[$i]['paxAddress']      = $paxAddress; 
                    }
                    
                    if($PassengerType[$i] == 1){
                        $paxType = "Adult";
                    }elseif ($PassengerType[$i] == 2) {
                        $paxType = "Child";
                    }elseif ($PassengerType[$i] == 3) {
                        $paxType = "Infant";
                    }
                    
                    if(empty($postData['firstName'][$i])) {
                        $response = array('success' => false, 'msg' => 'Please enter first name for '.$paxType.' '.($i+1).'.');
                        echo json_encode($response);
                        exit;
                    }

                    if(empty($postData['dob'][$i])) {
                        $response = array('success' => false, 'msg' => 'Please enter date of birth for '.$paxType.' '.($i+1).'.');
                        echo json_encode($response);
                        exit;
                    }
                    
                    
                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 1) {
                        
                        if (!empty($departureDates)) {
                            
                            $adultAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($adultAge < 12 ) {
                                $response = array('success' => false, 'msg' => "Adult ".($i+1)." age should be greater than  12 years.");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 2) {
                        if (!empty($departureDates)) {
                            $childAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($childAge < 2 || $childAge >= 12) {
                                $response = array('success' => false, 'msg' => "Child ".($i+1)." age should be 2 years or less than 12 years. ");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 3) {
                        if (!empty($departureDates)) {
                            $infantAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($infantAge >= 2) {
                                $response = array('success' => false, 'msg' => "Infant ".($i+1)." age should be less than 2 years. ");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }


                    if($i == 0){
                        if(empty($paxAddress)) {
                            $response = array('success' => false, 'msg' => 'Please enter Address for '.$paxType.' '.($i+1).'.');
                            echo json_encode($response);
                            exit;
                        }
                    }
                    
                }
                
                $arrFareQuote['PaxPrimaryContact'] = [
                    'contact' => $postData['mobileNumber'],
                    'emailid' => $postData['emailId'],
                ];
                
                $arrFareQuote['PaxDetails']     = $arrPax;
                
                
                
                //echo "<pre>";print_r($arrFareQuote);exit;

                // Create B2B Query & Proposal....
                
                $arrMarkupsAndPrice = [
                    "AgentCommisionEarned" => round($agencyCommision),
                    "AgentCommisionEarnedGST" => round($GSTAgencyTotalCommisions),
                    "AgencyMarkUp" => round($agencyMarkUp),
                    "AgencyMarkUpGST" => round($agencyMarkUpGST),
                    "GTXMarkUp" => round($gtxMarkup),
                    "GTXMarkUpGST" => 0,
                    "BaseAmount" => round($BaseFare - $gtxMarkup),
                    "TotalCost" => round($publishedfare)
                ];
                
                $arrFareQuote['arrMarkupsAndPrice']     = $arrMarkupsAndPrice;
                
                $proposalResponse = $this->generateFlightProposalAction($postData,$arrMarkupsAndPrice);
                
                $proposalStatus = $proposalResponse['status'];
                $arrProposalIds = $proposalResponse['arrIds'];
                $errorMessage = isset($proposalResponse['message'])?$proposalResponse['message']:'Oops! there might be some technical issue please contact administrator';
                $redirect = isset($proposalResponse['redirect'])?$proposalResponse['redirect']:false;
                
                if(!$proposalStatus || empty($arrProposalIds)){
                    echo json_encode(["success" => false, "msg" => base64_encode($errorMessage), "redirect" => $redirect]);
                    exit;
                }
                
                $arrFareQuote['arrIds']     = $arrProposalIds;
                //echo "<pre>";print_r($arrFareQuote);exit;
                
                
                // Create B2B Query & Proposal....
                
                $insertdata = [
                    'UrlData' => json_encode($arrFareQuote),
                    'CreatedDate' => date('Y-m-d h:i:s')
                ];
                
                
               $lastInsertId = $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
               
               $CustomerSysId   = $arrProposalIds['CustomerSysId'];
               $TPSysId         = $arrProposalIds['TrxId'];
               
               //echo "<pre>";print_r($arrIds);exit;
                
                
            // Generate scurecode wallet code etc...    

            $markuparray['intAgentMarkUpAmount'] = round($agencyCommision);
            $markuparray['intAgencyMarkUpAmount'] = round($agencyMarkUp);
            $markuparray['intGTXMarkUpAmount'] = round($gtxMarkup);
            $markuparray['intTotalAmount'] = round($BaseFare - $gtxMarkup);
            $markuparray['intTax'] = 0;
            $markuparray['intTotalGTXTaxAmount'] = 0;
            $markuparray['GTXServiceTaxAmount'] = 0;
            $markuparray['AgentServiceTaxAmount'] = round($agencyMarkUpGST);
            $markuparray['AgentsCustomServiceTaxAmount'] = round($GSTAgencyTotalCommisions);
            $markuparray['Pax'] = $$totalPax;
            $markuparray['TotalDiscount'] = 0;
            $markuparray['CurrencyType'] = 1; //currency Id
            $markuparray['MarketPlaceId']= 2; //b2b or b2c
            

            $encryptMarkUpData = $this->getEnc(json_encode($markuparray));
            $AgentSysId  = $this->gtxAgentSysid;
            $AgencySysId = $this->gtxagencysysid;
            //$intTPSysId  = $lastInsertId;
            $intCustSysId = $CustomerSysId;
            $guid = $TraceId;//$this->GUID();
            $walletCode = $this->walletCode($AgentSysId, $guid, round($publishedfare), $AgencySysId, json_encode([$TPSysId]), $intCustSysId, $encryptMarkUpData);
            //$securecode = $this->secureCode($intCustSysId, $guid);
            $strReturnURL = $this->baseUrl . "flights/search/process-booking/id/".base64_encode($lastInsertId);   

            // Generate scurecode wallet code etc...    
            echo json_encode(["success" => true, 'guid' => $guid, 'walletCode' => $walletCode, 'stringData' => $encryptMarkUpData, 'strReturnURL' => $strReturnURL, 'TPSysId' => json_encode([$TPSysId]),'UserData' => ['name'=> $arrPax[0]['firstName'],'email' => $postData['emailId'],'mobile' => $postData['mobileNumber'], 'CustSysId' => $intCustSysId]]);
            exit;
                
            
        }
        
        
        $this->_helper->layout->setLayout('flight-book-layout');
        $this->view->baseUrl    = $this->baseUrl;
        $this->view->search_id  = $search_id = $this->getRequest()->getParam('search_id');
        $this->view->rindex     = $rindex = $this->getRequest()->getParam('rindex');
        $this->view->fare       = $fare = $this->getRequest()->getParam('fare');
        $this->view->isInternational       = $isInternational = $this->getRequest()->getParam('isInternational');
        $this->view->AgencySysId       = $this->gtxagencysysid;
        $this->view->AgencyUserSysId       = $this->gtxAgentSysid;
        
//        $JSONFileName = $_SERVER['DOCUMENT_ROOT'] . "/public/data/flight-search/flight_search_".trim($search_id).".json";
//        if (file_exists($JSONFileName)) { 
//            unlink($JSONFileName);
//        }
        
        
        
    }
    
    public function reviewReturnFlightAction(){
        
        if ($this->_request->isXmlHttpRequest()) {
             $this->_helper->layout->disableLayout();
                $postData = $this->getRequest()->getPost();
                
                
                
                $arrFarequote      = json_decode($postData['fare-quote'],true);
                //echo "<pre>";print_r($arrFarequote);exit;
                $TraceId = isset($arrFarequote['TraceId'])?$arrFarequote['TraceId']:'';
                
                //echo "<pre>";print_r($arrFarequote['TraceId']);exit;
                
                $publishedfare      = ($postData['publishedfare']);
                $BaseFare           = $postData['BaseFare'];
                $gtxMarkup          = $postData['gtxMarkup'];
                $agencyMarkUp       = $postData['agencyMarkUp'];
                $agencyMarkUpGST    = $postData['agencyMarkUpGST'];
                $agencyCommision    = $postData['agencyCommision'];
                $GSTAgencyTotalCommisions    = $postData['GSTAgencyTotalCommisions'];
                $departureDates     = $postData['departureDates'];
                $paxAddress         = $postData['paxaddress'];
                $totalPax         = $postData['totalPax'];
                
                
                
                
                $publishedfareDepart      = ($postData['publishedfareDepart']);
                $BaseFareDepart           = $postData['BaseFareDepart'];
                $gtxMarkupDepart          = $postData['gtxMarkupDepart'];
                $agencyMarkUpDepart       = $postData['agencyMarkUpDepart'];
                $agencyMarkUpGSTDepart    = $postData['agencyMarkUpGSTDepart'];
                $agencyCommisionDepart    = $postData['agencyCommisionDepart'];
                $GSTAgencyTotalCommisionsDepart    = $postData['GSTAgencyTotalCommisionsDepart'];
                
                
                $publishedfareReturn      = ($postData['publishedfareReturn']);
                $BaseFareReturn           = $postData['BaseFareReturn'];
                $gtxMarkupReturn          = $postData['gtxMarkupReturn'];
                $agencyMarkUpReturn       = $postData['agencyMarkUpReturn'];
                $agencyMarkUpGSTReturn    = $postData['agencyMarkUpGSTReturn'];
                $agencyCommisionReturn    = $postData['agencyCommisionReturn'];
                $GSTAgencyTotalCommisionsReturn    = $postData['GSTAgencyTotalCommisionsReturn'];
                
                
                $arrMarkupsAndPrice = [
                   "Depart" => [
                            "AgentCommisionEarned" => round($agencyCommisionDepart),
                            "AgentCommisionEarnedGST" => round($GSTAgencyTotalCommisionsDepart),
                            "AgencyMarkUp" => round($agencyMarkUpDepart),
                            "AgencyMarkUpGST" => round($agencyMarkUpGSTDepart),
                            "GTXMarkUp" => round($gtxMarkupDepart),
                            "GTXMarkUpGST" => 0,
                            "BaseAmount" => round($BaseFareDepart - $gtxMarkupDepart),
                            "TotalCost" => round($publishedfareDepart)
                        ],
                    
                    
                    "Return" => [
                            "AgentCommisionEarned" => round($agencyCommisionReturn),
                            "AgentCommisionEarnedGST" => round($GSTAgencyTotalCommisionsReturn),
                            "AgencyMarkUp" => round($agencyMarkUpReturn),
                            "AgencyMarkUpGST" => round($agencyMarkUpGSTReturn),
                            "GTXMarkUp" => round($gtxMarkupReturn),
                            "GTXMarkUpGST" => 0,
                            "BaseAmount" => round($BaseFareReturn - $gtxMarkupReturn),
                            "TotalCost" => round($publishedfareReturn)
                        ]
                    
                ];
                
                
                $arrFareQuote['arrMarkupsAndPrice']     = $arrMarkupsAndPrice;
                
                $strCountry = file_get_contents($this->baseUrl."public/data/static/country.json");
                $arrCountry = json_decode($strCountry,true);
                
                $arrFareQuote   = json_decode($postData['fare-quote'],true);
                
                $arrFareQuote['arrMarkupsAndPrice']     = $arrMarkupsAndPrice;
                
                $PassengerType = $postData['PassengerType'];
                
                
                for($i=0;$i<count($PassengerType);$i++){
                    $arrPax[$i]['PassengerType'] = $PassengerType[$i];
                    $arrPax[$i]['salutation']    = $postData['salutation'][$i];
                    $arrPax[$i]['firstName']     = $postData['firstName'][$i];
                    $arrPax[$i]['lastName']      = $postData['lastName'][$i];
                    $arrPax[$i]['dob']           = $postData['dob'][$i];
                    
                    $passengerDob = "";
                    if(!empty($postData['dob'][$i])){
                        $arrPassengerDob       = explode("/", $postData['dob'][$i]);
                        $passengerDob       = $arrPassengerDob[2]."-".$arrPassengerDob[1]."-".$arrPassengerDob[0];
                    }
                    
                    
                    if($i == 0){
                        $arrPax[$i]['paxCity']         = $postData['city'];
                        $arrPax[$i]['paxCountryCode']  = $postData['country'];
                        $arrPax[$i]['paxCountryName']  = $arrCountry[$postData['country']];
                        $arrPax[$i]['paxAddress']      = $postData['paxaddress']; 
                    }
                    
                    if($PassengerType[$i] == 1){
                        $paxType = "Adult";
                    }elseif ($PassengerType[$i] == 2) {
                        $paxType = "Child";
                    }elseif ($PassengerType[$i] == 3) {
                        $paxType = "Infant";
                    }
                    
                    if(empty($postData['firstName'][$i])) {
                        $response = array('success' => false, 'msg' => 'Please enter first name for '.$paxType.' '.($i+1).'.');
                        echo json_encode($response);
                        exit;
                    }

                    if(empty($postData['dob'][$i])) {
                        $response = array('success' => false, 'msg' => 'Please enter date of birth for '.$paxType.' '.($i+1).'.');
                        echo json_encode($response);
                        exit;
                    }
                    
                    
                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 1) {
                        
                        if (!empty($departureDates)) {
                            
                            $adultAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($adultAge < 12 ) {
                                $response = array('success' => false, 'msg' => "Adult ".($i+1)." age should be greater than  12 years.");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 2) {
                        if (!empty($departureDates)) {
                            $childAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($childAge < 2 || $childAge >= 12) {
                                $response = array('success' => false, 'msg' => "Child ".($i+1)." age should be 2 years or less than 12 years. ");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }

                    if (!empty($PassengerType[$i]) && $PassengerType[$i] == 3) {
                        if (!empty($departureDates)) {
                            $infantAge = date_diff(date_create($passengerDob), date_create($departureDates))->y;
                            if ($infantAge >= 2) {
                                $response = array('success' => false, 'msg' => "Infant ".($i+1)." age should be less than 2 years. ");
                                echo json_encode($response);
                                exit;
                            }
                        } else {
                            $response = array('success' => false, 'msg' => "Departure date can not be empty.");
                            echo json_encode($response);
                            exit;
                        }
                    }


                    if($i == 0){
                        if(empty($paxAddress)) {
                            $response = array('success' => false, 'msg' => 'Please enter Address for '.$paxType.' '.($i+1).'.');
                            echo json_encode($response);
                            exit;
                        }
                    }
                    
                }
                
                $arrFareQuote['PaxPrimaryContact'] = [
                    'contact' => $postData['mobileNumber'],
                    'emailid' => $postData['emailId'],
                ];
                
                $arrFareQuote['PaxDetails']     = $arrPax;
                
                
                
                // Create B2B Query & Proposal....
                
                $proposalResponse = $this->generateReturnFlightProposalAction($postData,$arrMarkupsAndPrice);
                
                $proposalStatus = $proposalResponse['Depart']['status'];
                $arrProposalIds = $proposalResponse['Depart']['arrIds'];
                $errorMessage = isset($proposalResponse['Depart']['message'])?$proposalResponse['Depart']['message']:'Oops! there might be some technical issue please contact administrator';
                $redirect = isset($proposalResponse['Depart']['redirect'])?$proposalResponse['Depart']['redirect']:false;
                if(!$proposalStatus || empty($arrProposalIds)){
                    echo json_encode(["success" => false, "msg" => base64_encode($errorMessage), "redirect" => $redirect]);
                    exit;
                }
                
                
                $proposalStatus = $proposalResponse['Return']['status'];
                $arrProposalIds = $proposalResponse['Return']['arrIds'];
                $errorMessage = isset($proposalResponse['Return']['message'])?$proposalResponse['Return']['message']:'Oops! there might be some technical issue please contact administrator';
                $redirect = isset($proposalResponse['Return']['redirect'])?$proposalResponse['Return']['redirect']:false;
                if(!$proposalStatus || empty($arrProposalIds)){
                    echo json_encode(["success" => false, "msg" => base64_encode($errorMessage), "redirect" => $redirect]);
                    exit;
                }
                
                
                $arrFareQuote['arrIds']     = $proposalResponse;
                $CustomerSysId = !empty($arrIds['Depart']['arrIds']['CustomerSysId'])?$arrIds['Depart']['arrIds']['CustomerSysId']:0;
                $DepartTrxId = !empty($arrIds['Depart']['arrIds']['TrxId'])?$arrIds['Depart']['arrIds']['TrxId']:0;
                $ReturnTrxId = !empty($arrIds['Return']['arrIds']['TrxId'])?$arrIds['Return']['arrIds']['TrxId']:0;
                // Create B2B Query & Proposal....
                
                
                
                $arrTrxId = [$DepartTrxId,$ReturnTrxId];
                //echo "<pre>";print_r($arrTrxId);exit;
                
                
                $insertdata = [
                    'UrlData' => json_encode($arrFareQuote),
                    'CreatedDate' => date('Y-m-d h:i:s')
                ];
                
                //echo "<pre>";print_r($arrFareQuote);exit;

               $lastInsertId = $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
                
                
            // Generate scurecode wallet code etc...    

            $markuparray['intAgentMarkUpAmount'] = round($agencyCommision);
            $markuparray['intAgencyMarkUpAmount'] = round($agencyMarkUp);
            $markuparray['intGTXMarkUpAmount'] = round($gtxMarkup);
            $markuparray['intTotalAmount'] = round($BaseFare - $gtxMarkup);
            $markuparray['intTax'] = 0;
            $markuparray['intTotalGTXTaxAmount'] = 0;
            $markuparray['GTXServiceTaxAmount'] = 0;
            $markuparray['AgentServiceTaxAmount'] = round($agencyMarkUpGST);
            $markuparray['AgentsCustomServiceTaxAmount'] = round($GSTAgencyTotalCommisions);
            $markuparray['Pax'] = $$totalPax;
            $markuparray['TotalDiscount'] = 0;
            $markuparray['CurrencyType'] = 1; //currency Id
            $markuparray['MarketPlaceId']= 2; //b2b or b2c
                

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

            $encryptMarkUpData = $this->getEnc(json_encode($markuparray));
            $AgentSysId  = $this->gtxAgentSysid;
            $AgencySysId = $this->gtxagencysysid;
            $intTPSysId  = json_encode($arrTrxId);
            $intCustSysId = $CustomerSysId;
            $guid = $TraceId; //$this->GUID();
            $walletCode = $this->walletCode($AgentSysId, $guid, round($publishedfare), $AgencySysId, $intTPSysId, $intCustSysId, $encryptMarkUpData);
            //$securecode = $this->secureCode($intCustSysId, $guid);
            $strReturnURL = $this->baseUrl . "flights/index/process-roundtrip-booking/id/".base64_encode($lastInsertId);   

            // Generate scurecode wallet code etc...    
            echo json_encode(["success" => true, 'guid' => $guid, 'walletCode' => $walletCode, 'stringData' => $encryptMarkUpData, 'strReturnURL' => $strReturnURL, 'TPSysId' => $intTPSysId,'UserData' => ['name'=> $arrPax[0]['firstName'],'email' => $postData['emailId'],'mobile' => $postData['mobileNumber'], 'CustSysId' => $intCustSysId]]);
            exit;
                
            
        }
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        $this->_helper->layout->setLayout('flight-book-layout');
        $this->view->baseUrl    = $this->baseUrl;
        $this->view->search_id  = $search_id = $this->getRequest()->getParam('search_id');
        $this->view->rindex1     = $rindex1 = $this->getRequest()->getParam('rindex1');
        $this->view->rindex2    = $rindex2 = $this->getRequest()->getParam('rindex2');
        $this->view->fare    = $fare = $this->getRequest()->getParam('fare');
        $this->view->isInternational       = $isInternational = $this->getRequest()->getParam('isInternational');
        $this->view->AgencySysId       = $this->gtxagencysysid;
        $this->view->AgencyUserSysId       = $this->gtxAgentSysid;
        
        
//        $JSONFileName = $_SERVER['DOCUMENT_ROOT'] . "/public/data/flight-search/flight_search_".trim($search_id).".json";
//        if (file_exists($JSONFileName)) { 
//            unlink($JSONFileName);
//        }
        
        
        
    }
    
    public function fareQuotesAction(){
        
        if ($this->_request->isXmlHttpRequest()) { 
            $this->_helper->layout->disableLayout();
            $traceId =  $this->getRequest()->getParam('traceId');
            $rindex = $this->getRequest()->getParam('rindex');
            $isInternational = !empty($this->getRequest()->getParam('isInternational'))?$this->getRequest()->getParam('isInternational'):0;
            
            if(!empty($isInternational)){
                $CountryCode = "INTERNATIONAL";
            }else{
                $CountryCode = "IN";
            }
            
//            
            $datah = [
                "TraceId"       => $traceId,
                "ResultIndex"   => $rindex
            ];
            
            try {
                $data_stringh = json_encode($datah);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->flightFareQuotesUrl);
                curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                ));
                $response = curl_exec($ch);
            } catch (Exception $error) {
                $response = $error->getMessage();
            }
            
            $arrResponse = json_decode($response,true);
            //echo "<pre>";print_r($arrResponse);exit;
            $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:'';
            if($ErrorCode == 0){
                $IsPriceChanged = isset($arrResponse['Response']['IsPriceChanged'])?$arrResponse['Response']['IsPriceChanged']:'0';
                $TraceId = isset($arrResponse['Response']['TraceId'])?$arrResponse['Response']['TraceId']:'';
                $Results = isset($arrResponse['Response']['Results'])?$arrResponse['Response']['Results']:[];
                if(count($Results)>0){
                        $arr = [];

                        $OfferedFare = $Results['Fare']['OfferedFare'];
                        $PublishedFare = $Results['Fare']['PublishedFare'];
                        
                        $arrAllCommissions = [
                            "intCommissionEarned"   => $Results['Fare']['CommissionEarned'],
                            "intPLBEarned"          => $Results['Fare']['PLBEarned'],
                            "intIncentiveEarned"    => $Results['Fare']['IncentiveEarned']
                        ];
                        
                        $totalCommissions = $Results['Fare']['CommissionEarned'] + $Results['Fare']['PLBEarned'] + $Results['Fare']['IncentiveEarned'];

                        $arrMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getApiPriceWithMarkupAndServiceTax($arrAllCommissions,$OfferedFare,$CountryCode,$this->gtxagencysysid);
                        
                        $intOfferedFare     = $arrMarkUps['intOfferedFare'];
                        $PublishFareWidAllInc    = $arrMarkUps['intPublishFare'];
                        $AgencyMarkUp      = $arrMarkUps['intAgencyFixMarkUp'];
                        $intGTXMarkUp      = $arrMarkUps['intGTXMarkUp'];
                        $intSTaxOnAgencyFixMarkUp    = $arrMarkUps['intSTaxOnAgencyFixMarkUp'];
                        $intSTaxOnGTXMarkUp    = $arrMarkUps['intSTaxOnGTXMarkUp'];
                        $TotalCommisions   = $arrMarkUps['intCommisionEarnedForAgency'];
                        
                        $intTotalEarningsForAgency     = $arrMarkUps['intTotalEarningsForAgency'];
                        $gstOnTotalEarningsForAgency   = $arrMarkUps['intGSTOnAgencyCommisionEarned'] + $arrMarkUps['intGSTOnAgencyPLBEarned'] + $arrMarkUps['intGSTOnAgencyIncentiveEarned'];
                        
                        $arr['TraceId']             = $TraceId;
                        $arr['resultindex']         = $Results['ResultIndex'];
                        $arr['lCC']                 = $Results['IsLCC'];
                        $arr['refundable']          = $Results['IsRefundable'];
                        $arr['Currency']            = $Results['Fare']['Currency'];
                        $arr['BaseFare']            = $Results['Fare']['BaseFare'];
                        $arr['Tax']                 = $Results['Fare']['Tax'];
                        $arr['YQTax']               = $Results['Fare']['YQTax'];
                        $arr['AdditionalTxnFeeOfrd']= $Results['Fare']['AdditionalTxnFeeOfrd'];
                        $arr['AdditionalTxnFeePub'] = $Results['Fare']['AdditionalTxnFeePub'];
                        $arr['OtherCharges']        = $Results['Fare']['OtherCharges'];
                        $arr['Discount']            = $Results['Fare']['Discount'];
                        $arr['publishedfare']       = $Results['Fare']['PublishedFare'];
                        $arr['CommissionEarned']    = $Results['Fare']['CommissionEarned'];
                        $arr['PLBEarned']           = $Results['Fare']['PLBEarned'];
                        $arr['IncentiveEarned']     = $Results['Fare']['IncentiveEarned'];
                        $arr['OfferedFare']         = $Results['Fare']['OfferedFare'];
                        $arr['TdsOnCommission']     = $Results['Fare']['TdsOnCommission'];
                        $arr['TdsOnPLB']            = $Results['Fare']['TdsOnPLB'];
                        $arr['TdsOnIncentive']      = $Results['Fare']['TdsOnIncentive'];
                        $arr['ServiceFee']          = $Results['Fare']['ServiceFee'];
                        
                        //$arr['FareBreakdown']       = $Results['FareBreakdown'];
                        
                        $OtherCharges        = isset($Results['Fare']['OtherCharges'])?$Results['Fare']['OtherCharges']:0;
                        
                        $arrFareBreakdown = isset($Results['FareBreakdown'])?$Results['FareBreakdown']:[];
                        
                        $AdultPassengerCount = 0;
                        $ChildPassengerCount = 0;
                        $InfantsPassengerCount = 0;
                        $TotalPassengerCount = 0;
                        $arrPaxes = [];
                        foreach($arrFareBreakdown as $paxes){
                            
                            $PassengerType = $paxes['PassengerType'];
                            
                            if($PassengerType == 1){
                                $AdultPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => 0,
                                    'Infants' => 0
                                ];
                            }else if($PassengerType == 2){
                                $ChildPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $PassengerCount
                                ];
                            }else if($PassengerType == 3){
                                $InfantsPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $InfantsPassengerCount
                                ];
                            }
                        }
                        
                        $TotalPassengerCount = $AdultPassengerCount + $ChildPassengerCount + $InfantsPassengerCount;
                        $TotalPassengerCountForDiscount = $AdultPassengerCount + $ChildPassengerCount;
                        $intDiscountPerHead = $totalCommissions/$TotalPassengerCountForDiscount;
                        
                        //echo "<pre>";print_r($arrFareBreakdown);exit;
                        
                        $intTotalOfferedForAllPax = 0;
                        foreach($arrFareBreakdown as $pax){
                            
                            
                            $intPassengerCount = isset($pax['PassengerCount'])?$pax['PassengerCount']:0;
                            $intBaseFare       = $pax['BaseFare'];
                            $intTax            = $pax['Tax'];
                            $intDiscountPerHead         = ($intDiscountPerHead*$intPassengerCount);
                            $intBaseFareCal             = $intBaseFare - $intDiscountPerHead;
                            $intFareOfferedToPax       = $intBaseFareCal + $intTax;
                            
                            $arr['FareBreakdown'][] = [
                                'Currency'      => $pax['Currency'],
                                'BaseFare'      => $pax['BaseFare'],
                                'Tax'           => $pax['Tax'],
                                'YQTax'         => $pax['YQTax'],
                                'PassengerType' => $pax['PassengerType'],
                                'PassengerCount' => $pax['PassengerCount'],
                                'PGCharge'      => $pax['PGCharge'],
                                'AdditionalTxnFeePub'   => $pax['AdditionalTxnFeePub'],
                                'AdditionalTxnFeeOfrd'  => $pax['AdditionalTxnFeeOfrd'],
                                'AgencyMarkUp'  => $AgencyMarkUp,
                                'GTXMarkUp'  => $intGTXMarkUp,
                                'FareOfferedToPax'  => $intFareOfferedToPax
                            ];
                            
                            $intTotalOfferedForAllPax += $intFareOfferedToPax;
                            
                            
                        }
                        
                        
                        $arr['TotalOfferedForAllPax']   = $intTotalOfferedForAllPax;
                        
                        
                        $totalGTXMarkup         = $TotalPassengerCount*$intGTXMarkUp;
                        $intTotalOtherCharge    = $OtherCharges + $totalGTXMarkup;
                        $intNetOfferedFare      = $intTotalOfferedForAllPax + $intTotalOtherCharge;
                        
                        $AgencyTotalMarkUp   = $TotalPassengerCount*$AgencyMarkUp;
                        $totalGST = $TotalPassengerCount*$intSTaxOnAgencyFixMarkUp;
                        $ServicesAndTaxAndAll      = round($AgencyTotalMarkUp + $totalGST + $intTotalEarningsForAgency + $gstOnTotalEarningsForAgency);
                        $CostToCustomer = round($intNetOfferedFare + $ServicesAndTaxAndAll);
                        
                        
                        $arr['NetOfferedFare']      = $intNetOfferedFare;
                        $arr['ServicesAndTax']      = $ServicesAndTaxAndAll;
                        $arr['TotalOtherCharge']    = $intTotalOtherCharge;
                        $arr['CostToCustomer']      = $CostToCustomer;
                        
                        
                        
                        $arr['GTXMarkUp']                   = $totalGTXMarkup;
                        $arr['AgencyTotalMarkUp']           = $AgencyTotalMarkUp;
                        $arr['gstonAgencyMarkup']           = $totalGST;
                        $arr['AgencyTotalCommisions']       = $intTotalEarningsForAgency;
                        $arr['GSTAgencyTotalCommisions']    = $gstOnTotalEarningsForAgency;
                        $arr['PaxCount']                    = $arrPaxes;
                        $arr['TotalPassengerCount']                    = $TotalPassengerCount;

                        $arrSegments = isset($Results['Segments'])?$Results['Segments']:[];
                        //echo "<pre>";print_r($arr);exit;
                        if(count($arrSegments)>0){
                            
                            foreach ($arrSegments as $key => $value){
                                $AirSegments = [];
                                foreach ($value as $segkey => $flightsegments){
                                    
                                    // airline logos images...
                                    $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                                    if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                        $strAirlineLogo = $strAirlineCode . ".gif";
                                    } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                        $strAirlineLogo = $strAirlineCode . ".png";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpg";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpeg";
                                    }else{
                                        $strAirlineLogo = "noimage.png";
                                    }
                                    // airline logos images ends...
                                    
                                    if($segkey == 0){
                                        $departureDate = !empty(explode("T", $flightsegments['StopPointDepartureTime']))?explode("T", $flightsegments['StopPointDepartureTime']):'';
                                        $departureDate = $departureDate[0];
                                    }
                                    
                                    $departureat = $flightsegments['StopPointDepartureTime'];
                                    $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                                    $departureat = explode(" ",$departureat);
                                    $arrivalat = $flightsegments['StopPointArrivalTime'];
                                    $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                                    $arrivalat = explode(" ",$arrivalat);
                                    
                                    $flightduration = isset($flightsegments['Duration'])?$flightsegments['Duration']:0;
                                    $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...
                                    
                                    $GroundTime = (!empty($flightsegments['GroundTime'])?$flightsegments['GroundTime']:(isset($flightsegments['AccumulatedDuration'])?$flightsegments['AccumulatedDuration']:0));
                                    $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...
                                    
                                    $AirSegments[] = [
                                        'logo'          => $strAirlineLogo,
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'airlinecode'   => $flightsegments['Airline']['AirlineCode'],
                                        'flightnumber'  => $flightsegments['Airline']['FlightNumber'],
                                        'deptime'       => end($departureat),
                                        'departuredate'   => $departureat[0]." ".$departureat[1]." ".$departureat[2],
                                        'Baggage'       => $flightsegments['Baggage'],
                                        'CabinBaggage'  => $flightsegments['CabinBaggage'],
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'fareclass'     => $flightsegments['Airline']['FareClass'],
                                        'origin'        => $flightsegments['Origin']['Airport']['AirportCode'],
                                        'originTerminal'  => $flightsegments['Origin']['Airport']['Terminal'],
                                        'origincity'    => $flightsegments['Origin']['Airport']['CityName'],
                                        'originCountryCode'   => $flightsegments['Origin']['Airport']['CountryCode'],
                                        'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                        'destination'   => $flightsegments['Destination']['Airport']['AirportCode'],
                                        'destTerminal'  => $flightsegments['Destination']['Airport']['Terminal'],
                                        'destcity'      => $flightsegments['Destination']['Airport']['CityName'],
                                        'destCountryCode'   => $flightsegments['Destination']['Airport']['CountryCode'],
                                        'destairport'   => $flightsegments['Destination']['Airport']['AirportName'],
                                        'arrtime'       => end($arrivalat),
                                        'arrivaldate'     => $arrivalat[0]." ".$arrivalat[1]." ".$arrivalat[2],
                                        'Duration'      => $strflightduration,
                                        //'GroundTime' => $GroundTime,
                                        'GroundTime' => $GroundTime
                                        
                                    ];
                                    
                                }
                                if($key == 0){
                                    $arr['Segments1'] = $AirSegments;
                                }else if($key == 1){
                                    $arr['Segments2'] = $AirSegments;
                                }
                            }
                        }
                        
                        
                        
                        $arr['Stops'] = (count($AirSegments)>1)?1:0;
                        $arr['departureDate'] = $departureDate;
                        
                        //echo "<pre>";print_r($arr);exit;
                        
                }
                
                echo json_encode(array("success" => true, "resdata" => $arr, "IsPriceChanged" => $IsPriceChanged));
                exit;
                
                
            }else{
                
                $arrCustomErrors = unserialize(CONST_FLIGHT_CUSTOM_ERRORS);
                $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:0;
                $arr['error']   = $arrCustomErrors[$ErrorCode];
                echo json_encode(array("success" => false, "resdata" => $arr));
                exit;
            }
        }
        exit;
        
    }
    
    public function processBookingAction(){
        
        
        $this->_helper->layout->setLayout('flight-book-layout');
        $this->view->baseUrl    = $this->baseUrl;
        
        $this->view->id  = $id = base64_decode($this->getRequest()->getParam('id'));
        $this->view->status  = $status = ($this->getRequest()->getParam('status'));
        $this->view->discriminator  = $discriminator = ($this->getRequest()->getParam('discriminator'));
        $this->view->mmp_txn  = $mmp_txn = ($this->getRequest()->getParam('mmp_txn'));
        $this->view->GUID  = $GUID = ($this->getRequest()->getParam('GUID'));
        
        //echo "<pre>";print_r($_REQUEST);exit;
        //&& $status == "Ok"
        if ($this->_request->isXmlHttpRequest() ) { 
            $this->_helper->layout->disableLayout();
            
            $urlId = $this->getRequest()->getParam('urlId');
            $paymentStatus = $this->getRequest()->getParam('paymentStatus');
            $mmp_txn = $this->getRequest()->getParam('mmp_txn');
            $discriminator = $this->getRequest()->getParam('discriminator');
            $GUID = $this->getRequest()->getParam('GUID');
            
            if($paymentStatus == "Ok"){
                $objTempUrl = new Flights_Model_TblTempUrl();
                $arrUrlData = $objTempUrl->getUrlData($urlId);

                $urlData = isset($arrUrlData['UrlData'])?json_decode($arrUrlData['UrlData'],true):[];
                
//                echo "<pre>";print_r($urlData);exit;
                
                $TPSysId        = isset($urlData['arrIds']['TPSysId'])?$urlData['arrIds']['TPSysId']:0;
                
                
                $resultindex        = $urlData['resultindex'];
                $traceId            = $urlData['TraceId'];
                $lCC                = $urlData['lCC'];
                $arrFareBreakdown   = $urlData['FareBreakdown'];
                $AgencyTotalMarkUp   = $urlData['AgencyTotalMarkUp'];
                $AgencyTotalCommisions   = $urlData['AgencyTotalCommisions'];


                $arrPaxPrimaryContact   = $urlData['PaxPrimaryContact'];
                $ContactNo              = $arrPaxPrimaryContact['contact'];
                $EmailId                = $arrPaxPrimaryContact['emailid'];

                $arrPaxDetails = $urlData['PaxDetails'];
                
                
                $arrIds = $urlData['arrIds'];
                $MasterTPSysId  = $arrIds['MasterTPSysId'];
                $TPSysId        = $arrIds['TPSysId'];
                $VersionId      = $arrIds['VersionId'];
                $TrxId      = $arrIds['TrxId'];
                
                
                $paxCity        = trim($arrPaxDetails[0]['paxCity']);
                $paxCountryCode = trim($arrPaxDetails[0]['paxCountryCode']);
                $paxCountryName = trim($arrPaxDetails[0]['paxCountryName']);
                $paxAddress     = trim($arrPaxDetails[0]['paxAddress']);
                
                $ARR_SALUTION = unserialize(ARR_SALUTION);
                if(count($arrPaxDetails) > 0){
                    $arrPassengers = [];
                    $arrMeal = [];
                    foreach ($arrPaxDetails as $key => $paxVal){
                        $dob = $paxVal['dob'];

                        if(!empty($dob)){
                            $arrDob = explode("/",$dob);
                            if(count($arrDob) > 0){
                                $PaxDob = $arrDob[2]."-".$arrDob[1]."-".$arrDob[0];
                            }
                        }

                        $salutation = isset($ARR_SALUTION[$paxVal['salutation']])?$ARR_SALUTION[$paxVal['salutation']]:'Mr';

                        if($lCC){
                            
                            $arrSSR = $this->flightSSRRequestAction($urlData);
                            $WayType            = isset($arrSSR['Response']['MealDynamic'][0][0]['WayType'])?trim($arrSSR['Response']['MealDynamic'][0][0]['WayType']):'2';
                            $Code               = isset($arrSSR['Response']['MealDynamic'][0][0]['Code'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Code']):'No Meal';
                            $Description        = isset($arrSSR['Response']['MealDynamic'][0][0]['Description'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Description']):'2';
                            $AirlineDescription = isset($arrSSR['Response']['MealDynamic'][0][0]['AirlineDescription'])?trim($arrSSR['Response']['MealDynamic'][0][0]['AirlineDescription']):'';
                            $Quantity           = isset($arrSSR['Response']['MealDynamic'][0][0]['Quantity'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Quantity']):'0';
                            $Currency           = isset($arrSSR['Response']['MealDynamic'][0][0]['Currency'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Currency']):'INR';
                            $Price              = isset($arrSSR['Response']['MealDynamic'][0][0]['Price'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Price']):'0';
                            $Origin             = isset($arrSSR['Response']['MealDynamic'][0][0]['Origin'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Origin']):trim($data['Origin']);
                            $Destination        = isset($arrSSR['Response']['MealDynamic'][0][0]['Destination'])?trim($arrSSR['Response']['MealDynamic'][0][0]['Destination']):($data['Destination']);


                            $WayTypeBaggage            = isset($arrSSR['Response']['Baggage'][0][0]['WayType'])?trim($arrSSR['Response']['Baggage'][0][0]['WayType']):'2';
                            $CodeBaggage               = isset($arrSSR['Response']['Baggage'][0][0]['Code'])?trim($arrSSR['Response']['Baggage'][0][0]['Code']):'No Baggage';
                            $DescriptionBaggage        = isset($arrSSR['Response']['Baggage'][0][0]['Description'])?trim($arrSSR['Response']['Baggage'][0][0]['Description']):'2';
                            $WeightBaggage             = isset($arrSSR['Response']['Baggage'][0][0]['Weight'])?trim($arrSSR['Response']['Baggage'][0][0]['Weight']):'0';
                            $CurrencyBaggage           = isset($arrSSR['Response']['Baggage'][0][0]['Currency'])?trim($arrSSR['Response']['Baggage'][0][0]['Currency']):'INR';
                            $PriceBaggage              = isset($arrSSR['Response']['Baggage'][0][0]['Price'])?trim($arrSSR['Response']['Baggage'][0][0]['Price']):'0';
                            

                            $arrPassengers[] = [
                                            'Title'     => $salutation, //Mr ,Mstr ,Mrs ,Ms ,Miss ,Master ,DR ,CHD ,MST ,PROF ,Inf.
                                            'FirstName' => $paxVal['firstName'],
                                            'LastName'  => $paxVal['lastName'],
                                            'PaxType'   => $paxVal['PassengerType'],
                                            'DateOfBirth' => $PaxDob."T00:00:00",
                                            'Gender'    => 1,
                                            'PassportNo' => '',
                                            'PassportExpiry' => '',
                                            'AddressLine1' => $paxAddress,
                                            'AddressLine2' => '',
                                            'City' => $paxCity,
                                            'CountryCode' => $paxCountryCode,
                                            'CountryName' => $paxCountryName,
                                            'ContactNo' => $ContactNo,
                                            'Email' => $EmailId,
                                            'IsLeadPax' => ($key == 0) ? 1 : 0,
                                            'FFAirline' => '',
                                            'FFNumber' => '',
                                            'Fare' =>
                                                [
                                                'BaseFare' => $arrFareBreakdown[$key]['BaseFare'],
                                                'Tax' => $arrFareBreakdown[$key]['Tax'],
                                                'TransactionFee' => "00.00",
                                                'YQTax' => $arrFareBreakdown[$key]['YQTax'],
                                                'AdditionalTxnFeeOfrd' => $arrFareBreakdown[$key]['AdditionalTxnFeeOfrd'],
                                                'AdditionalTxnFeePub' => $arrFareBreakdown[$key]['AdditionalTxnFeePub'],
                                                'AirTransFee' => "00.00"
                                            ],
                                            'MealDynamic' =>
                                                [
                                                'WayType' => $WayType,
                                                'Code' => $Code,
                                                'Description' => $Description,
                                                'AirlineDescription' => $AirlineDescription,
                                                'Quantity' => $Quantity,
                                                'Price' => $Price,
                                                'Currency' => $Currency,
                                                'Origin' => $Origin,
                                                'Destination' => $Destination
                                            ],
                                        'Baggage' =>
                                            [
                                            'WayType' => $WayTypeBaggage,
                                            'Code' => $CodeBaggage,
                                            'Description' => $DescriptionBaggage,
                                            'Weight' => $WeightBaggage,
                                            'Currency' => $CurrencyBaggage,
                                            'Price' => $PriceBaggage,
                                            'Origin' => $Origin,
                                            'Destination' => $Destination
                                            ]

                                        ];



                        }else{

                            
                            $arrSSR = $this->flightSSRRequestAction($urlData);
                            $MealCode            = isset($arrSSR['Response']['Meal'][0]['Code'])?trim($arrSSR['Response']['Meal'][0]['Code']):'VGML';
                            $MealDesc            = isset($arrSSR['Response']['Meal'][0]['Description'])?trim($arrSSR['Response']['Meal'][0]['Description']):'Veg/Non Dairy';

                            $SeatCode            = isset($arrSSR['Response']['SeatPreference'][0]['Code'])?trim($arrSSR['Response']['SeatPreference'][0]['Code']):'A';
                            $SeatDesc            = isset($arrSSR['Response']['SeatPreference'][0]['Description'])?trim($arrSSR['Response']['SeatPreference'][0]['Description']):'Window';
                            
                            $arrPassengers[] = [
                                            'Title'     => $salutation, //Mr ,Mstr ,Mrs ,Ms ,Miss ,Master ,DR ,CHD ,MST ,PROF ,Inf.
                                            'FirstName' => $paxVal['firstName'],
                                            'LastName'  => $paxVal['lastName'],
                                            'PaxType'   => $paxVal['PassengerType'],
                                            'DateOfBirth' => $PaxDob."T00:00:00",
                                            'Gender'    => 1,
                                            'PassportNo' => '',
                                            'PassportExpiry' => '',
                                            'AddressLine1' => $paxAddress,
                                            'AddressLine2' => '',
                                            'City' => $paxCity,
                                            'CountryCode' => $paxCountryCode,
                                            'CountryName' => $paxCountryName,
                                            'ContactNo' => $ContactNo,
                                            'Email' => $EmailId,
                                            'IsLeadPax' => ($key == 0) ? 1 : 0,
                                            'FFAirline' => '',
                                            'FFNumber' => '',
                                            'Fare' =>
                                                [
                                                'BaseFare' => $arrFareBreakdown[$key]['BaseFare'],
                                                'Tax' => $arrFareBreakdown[$key]['Tax'],
                                                'TransactionFee' => "00.00",
                                                'YQTax' => $arrFareBreakdown[$key]['YQTax'],
                                                'AdditionalTxnFeeOfrd' => $arrFareBreakdown[$key]['AdditionalTxnFeeOfrd'],
                                                'AdditionalTxnFeePub' => $arrFareBreakdown[$key]['AdditionalTxnFeePub'],
                                                'AirTransFee' => "00.00"
                                            ],
                                            'Meal' =>
                                            [
                                            'Code' => $MealCode,
                                            'Description' => $MealDesc
                                            ],
                                            'Seat' =>
                                                [
                                                'Code' => $SeatCode,
                                                'Description' => $SeatDesc
                                            ]

                                        ];

                        }

                    }

                }

                $datah = array(
                            "TraceId"       => $traceId,
                            "ResultIndex"   => $resultindex,
                            'Passengers'    => $arrPassengers,
                            'TrxId'         => $TrxId,
                            'AgencySysId'   => $this->gtxagencysysid,
                            'discriminator' => $discriminator,
                            'mmp_txn'       => $mmp_txn,
                            'GUID'         => $GUID
                            
                        );
                
                //echo "<pre>";print_r($datah);exit;
                
                try {
                    $data_stringh = json_encode($datah);
                    $ch = curl_init();
                    if($lCC){
                        curl_setopt($ch, CURLOPT_URL, $this->flightTicketUrl); 
                    }else{
                       curl_setopt($ch, CURLOPT_URL, $this->flightBookUrl);
                    }

                    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    ));
                    $response = curl_exec($ch);
                } catch (Exception $error) {
                    $response = $error->getMessage();
                }

//                echo "<pre>";print_r(json_decode($response,true));//exit;
                

                
                
                
                
                
                
                $arrResponse = json_decode($response, true);
                $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode']) ? $arrResponse['Response']['Error']['ErrorCode'] : '';
                $TraceId = isset($arrResponse['Response']['TraceId']) ? $arrResponse['Response']['TraceId'] : '';
                $Results = isset($arrResponse['Response']['Response']) ? $arrResponse['Response']['Response'] : [];
                $arr = [];
                if ($ErrorCode == 0) {
                    $arr['Depart']['PNR'] = $Results['PNR'];
                    $arr['Depart']['BookingId'] = $Results['BookingId'];
                    
                    
                    
                    

                    $arrSegments = isset($Results['FlightItinerary']['Segments']) ? $Results['FlightItinerary']['Segments'] : [];

                    //echo "<pre>";print_r($Results['FlightItinerary']['Segments']);exit;
                    if (count($arrSegments) > 0) {
                        $AirSegments = [];
                        foreach ($arrSegments as $key => $flightsegments) {
                            
                            // airline logos images...
                            $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                            if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                $strAirlineLogo = $strAirlineCode . ".gif";
                            } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                $strAirlineLogo = $strAirlineCode . ".png";
                            } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                $strAirlineLogo = $strAirlineCode . ".jpg";
                            } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                $strAirlineLogo = $strAirlineCode . ".jpeg";
                            } else {
                                $strAirlineLogo = "noimage.png";
                            }
                            // airline logos images ends...
                            $TripIndicator = $flightsegments['TripIndicator'];
                            $SegmentIndicator = $flightsegments['SegmentIndicator'];
                            if ($SegmentIndicator == 1) {
                                $departureDate = !empty(explode("T", $flightsegments['StopPointDepartureTime'])) ? explode("T", $flightsegments['StopPointDepartureTime']) : '';
                                $departureDate = $departureDate[0];
                            }

                            $departureat = $flightsegments['StopPointDepartureTime'];
                            $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                            $departureat = explode(" ", $departureat);
                            $arrivalat = $flightsegments['StopPointArrivalTime'];
                            $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                            $arrivalat = explode(" ", $arrivalat);

                            $flightduration = isset($flightsegments['Duration']) ? $flightsegments['Duration'] : 0;
                            $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...

                            $GroundTime = isset($flightsegments['GroundTime']) ? $flightsegments['GroundTime'] : 0;
                            $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...

                            $AirSegments[] = [
                                'TripIndicator' => $TripIndicator,
                                'SegmentIndicator' => $SegmentIndicator,
                                'logo' => $strAirlineLogo,
                                'airline' => $flightsegments['Airline']['AirlineName'],
                                'airlinecode' => $flightsegments['Airline']['AirlineCode'],
                                'flightnumber' => $flightsegments['Airline']['FlightNumber'],
                                'deptime' => end($departureat),
                                'departuredate' => $departureat[0] . " " . $departureat[1] . " " . $departureat[2],
                                'Baggage' => $flightsegments['Baggage'],
                                'CabinBaggage' => $flightsegments['CabinBaggage'],
                                'airline' => $flightsegments['Airline']['AirlineName'],
                                'fareclass' => $flightsegments['Airline']['FareClass'],
                                'origin' => $flightsegments['Origin']['Airport']['AirportCode'],
                                'originTerminal' => $flightsegments['Origin']['Airport']['Terminal'],
                                'origincity' => $flightsegments['Origin']['Airport']['CityName'],
                                'originCountryCode' => $flightsegments['Origin']['Airport']['CountryCode'],
                                'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                'destination' => $flightsegments['Destination']['Airport']['AirportCode'],
                                'destTerminal' => $flightsegments['Destination']['Airport']['Terminal'],
                                'destcity' => $flightsegments['Destination']['Airport']['CityName'],
                                'destCountryCode' => $flightsegments['Destination']['Airport']['CountryCode'],
                                'destairport' => $flightsegments['Destination']['Airport']['AirportName'],
                                'arrtime' => end($arrivalat),
                                'arrivaldate' => $arrivalat[0] . " " . $arrivalat[1] . " " . $arrivalat[2],
                                'Duration' => $strflightduration,
                                'GroundTime' => $GroundTime,
                            ];

                            
                        }
                        $arr['Depart']['Segments'] = $AirSegments;
                    }
                    
                    
                    $arr['Depart']['TotalOfferedForAllPax'] = $urlData['TotalOfferedForAllPax'];
                    $arr['Depart']['ServicesAndTax']        = $urlData['ServicesAndTax'];
                    $arr['Depart']['TotalOtherCharge']      = $urlData['TotalOtherCharge'];
                    $arr['Depart']['CostToCustomer']        = $urlData['CostToCustomer'];
                    

                    $arrPassengers = isset($Results['FlightItinerary']['Passenger']) ? $Results['FlightItinerary']['Passenger'] : [];
                    $arrFlightItinerary = isset($Results['FlightItinerary']) ? $Results['FlightItinerary'] : [];
                    if (count($arrPassengers) > 0) {
                        $arrPax = [];
                        foreach ($arrPassengers as $paxDetails) {


                            $IsLCC = isset($Results['FlightItinerary']['IsLCC']) ? $Results['FlightItinerary']['IsLCC'] : 0;
                            if ($IsLCC) {
                                $arrPax[] = [
                                    'Title' => $paxDetails['Title'],
                                    'FirstName' => $paxDetails['FirstName'],
                                    'LastName' => $paxDetails['LastName'],
                                    'DateOfBirth' => $paxDetails['DateOfBirth'],
                                    'EmailId' => $EmailId,
                                    'PNR' => $Results['FlightItinerary']['PNR'],
                                    'BookingId' => $Results['BookingId'],
                                    'TicketId' => isset($paxDetails['Ticket']['TicketId']) ? $paxDetails['Ticket']['TicketId'] : '',
                                    'TicketNumber' => isset($paxDetails['Ticket']['TicketNumber']) ? $paxDetails['Ticket']['TicketNumber'] : ''
                                ];
                            } else {
                                $arrPax[] = [
                                    'Title' => $paxDetails['Title'],
                                    'FirstName' => $paxDetails['FirstName'],
                                    'LastName' => $paxDetails['LastName'],
                                    'DateOfBirth' => $paxDetails['DateOfBirth'],
                                    'EmailId' => $EmailId,
                                    'PNR' => $Results['FlightItinerary']['PNR'],
                                    'BookingId' => $Results['BookingId'],
                                    'TicketId' => isset($paxDetails['Ticket']['TicketId']) ? $paxDetails['Ticket']['TicketId'] : '',
                                    'TicketNumber' => isset($paxDetails['Ticket']['TicketNumber']) ? $paxDetails['Ticket']['TicketNumber'] : ''
                                ];
                            }
                        }
                        $arr['Depart']['Passengers'] = $arrPax;
                    }
                    
                    


                    $FareRules = isset($Results['FlightItinerary']['FareRules'][0]['FareRuleDetail']) ? $Results['FlightItinerary']['FareRules'][0]['FareRuleDetail'] : [];
                    $arr['Depart']['FareRules'] = $FareRules;


                    $arrFareDetails = isset($Results['FlightItinerary']['Fare']) ? $Results['FlightItinerary']['Fare'] : [];

                    $arr['Depart']['FareDetails'] = [
                        "Currency" => $arrFareDetails['Currency'],
                        "BaseFare" => $arrFareDetails['BaseFare'],
                        "AgencyTotalMarkUp" => $AgencyTotalMarkUp,
                        "AgencyTotalCommisions" => $AgencyTotalCommisions,
                        "Tax" => $arrFareDetails['Tax'],
                        "YQTax" => $arrFareDetails['YQTax'],
                        "AdditionalTxnFeeOfrd" => $arrFareDetails['AdditionalTxnFeeOfrd'],
                        "AdditionalTxnFeePub" => $arrFareDetails['AdditionalTxnFeePub'],
                        "OtherCharges" => $arrFareDetails['OtherCharges'],
                        "Discount" => $arrFareDetails['Discount'],
                        "PublishedFare" => $arrFareDetails['PublishedFare']
                    ];
                    
                    
                    // Booking Email To Customer & Agent............
                    
                    
                    $arrMarkups = isset($urlData['arrMarkupsAndPrice'])?$urlData['arrMarkupsAndPrice']:[];
                    
//                    $arrMarkups = [
//                        "AgencyTotalMarkUp" => @$AgencyTotalMarkUp,
//                        "AgencyTotalCommisions" => @$AgencyTotalCommisions
//                    ];
                    
                    $arr['Depart']['arrMarkupsAndPrice'] = $arrMarkups;
                    
                    $this->bookingEmailToAgentAction($arrResponse,$arrMarkups);
                    $this->bookingEmailToCustomerAction($arrResponse,$arrMarkups);
                    // Booking Email To Customer & Agent Ends................
                    
                    
                    
                    // Update Booking Status to B2B end.........
                    try {
                        $this->postFields .= "&MasterTPSysId=" . $MasterTPSysId;
                        $this->postFields .= "&TPSysId=" . $TPSysId;
                        $this->postFields .= "&VersionId=" . $VersionId;
                        $this->postFields .= "&XRefBookingId=" . $Results['BookingId'] . "/" . $Results['PNR'];
                        $this->postFields .= "&APIBookingRes=" . json_encode($arrResponse);
                        $this->postFields .= "&ErrorCode=0";
                        $model = new Gtxwebservices_Model_Webservices();
                        $result = $model->updateFlightBookingDetails($this->postFields);
                    } catch (Exception $error) {

                    }
                    //$response = json_decode($result,true);
                    // Update Booking Status to B2B end.........


                    $responsedata = [
                        'response' => json_encode($arr),
                        'apiResponse' => $response,
                        'CreatedDate' => date('Y-m-d h:i:s')
                    ];

                    $lastInsertId = $this->objMdl->rv_insert("tbl_flight_booking", $responsedata);



                    $insertdata = [
                        'UrlData' => json_encode($arr),
                        'CreatedDate' => date('Y-m-d h:i:s')
                    ];


                    $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
                    echo json_encode(array("success" => true, "id" => base64_encode($lastInsertId)));
                    exit;
                    
                    
                    
                    
                    
                    
                } else {
                    
                    
                    
                    //$arrCustomErrors = unserialize(CONST_FLIGHT_CUSTOM_ERRORS);
                    $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode']) ? $arrResponse['Response']['Error']['ErrorCode'] : 0;
                    $arr['Depart']['error'] = isset($arrResponse['Response']['Error']['ErrorMessage']) ? $arrResponse['Response']['Error']['ErrorMessage'] : ''; 
                    
                    
                    
                    $objTempUrl = new Flights_Model_TblTempUrl();
                    $arrUrlData = $objTempUrl->getUrlData($urlId);
                    $urlData = isset($arrUrlData['UrlData'])?json_decode($arrUrlData['UrlData'],true):[];

                    

                    // Update Booking Status to B2B end.........
                    $arrIds         = $urlData['arrIds'];
                    $MasterTPSysId  = $arrIds['MasterTPSysId'];
                    $TPSysId        = $arrIds['TPSysId'];
                    $VersionId      = $arrIds['VersionId'];
                    try {
                        $this->postFields = "";
                        $this->postFields .= "&MasterTPSysId=" . $MasterTPSysId;
                        $this->postFields .= "&TPSysId=" . $TPSysId;
                        $this->postFields .= "&VersionId=" . $VersionId;
                        $this->postFields .= "&XRefBookingId=" . '';
                        $this->postFields .= "&APIBookingRes=" . '';
                        $this->postFields .= "&ErrorCode= " . '70';
                        $model = new Gtxwebservices_Model_Webservices();
                        $result = $model->updateFlightBookingDetails($this->postFields);

                    } catch (Exception $error) {

                    }
                    //$response = json_decode($result,true);
                    // Update Booking Status to B2B end.........

                    

                    $arr['UrlData'] = $urlData;
                    
                    $insertdata = [
                        'UrlData' => json_encode($arr),
                        'CreatedDate' => date('Y-m-d h:i:s')
                    ];
                    

                    $lastInsertId = $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
                    echo json_encode(array("success" => false, "id" => base64_encode($lastInsertId), "pstatus" => "BF"));
                    exit;
                    
                    
                    
                }
                
                
                
                
                
                //echo "<pre>";print_r($arr);exit;
                
                
                
                
                
                
                
            }else if($paymentStatus == "C"){ // cancelled by User
                
                $objTempUrl = new Flights_Model_TblTempUrl();
                $arrUrlData = $objTempUrl->getUrlData($urlId);
                $urlData = isset($arrUrlData['UrlData'])?json_decode($arrUrlData['UrlData'],true):[];
                
                
                
                // Update Booking Status to B2B end.........
                $arrIds = $urlData['arrIds'];
                $MasterTPSysId  = $arrIds['MasterTPSysId'];
                $TPSysId        = $arrIds['TPSysId'];
                $VersionId      = $arrIds['VersionId'];
                try {
                    $this->postFields = "";
                    $this->postFields .= "&MasterTPSysId=" . $MasterTPSysId;
                    $this->postFields .= "&TPSysId=" . $TPSysId;
                    $this->postFields .= "&VersionId=" . $VersionId;
                    $this->postFields .= "&XRefBookingId=" . '';
                    $this->postFields .= "&APIBookingRes=" . '';
                    $this->postFields .= "&ErrorCode=" . '6';
                    $model = new Gtxwebservices_Model_Webservices();
                    $result = $model->updateFlightBookingDetails($this->postFields);
                    
                } catch (Exception $error) {
                    
                }
                //$response = json_decode($result,true);
                // Update Booking Status to B2B end.........
                
                
                
                $arr['UrlData'] = $urlData;
                
                $insertdata = [
                        'UrlData' => json_encode($arr),
                        'CreatedDate' => date('Y-m-d h:i:s')
                    ];
                
                $lastInsertId = $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
                echo json_encode(array("success" => false, "pstatus" => $paymentStatus));
                exit;
                
                
            }else{

                $objTempUrl = new Flights_Model_TblTempUrl();
                $arrUrlData = $objTempUrl->getUrlData($urlId);
                $urlData = isset($arrUrlData['UrlData'])?json_decode($arrUrlData['UrlData'],true):[];
                
                //echo "<pre>";print_r($urlData);exit;
                
                // Update Booking Status to B2B end.........
                $arrIds = $urlData['arrIds'];
                $MasterTPSysId  = $arrIds['MasterTPSysId'];
                $TPSysId        = $arrIds['TPSysId'];
                $VersionId      = $arrIds['VersionId'];
                try {
                    $this->postFields = "";
                    $this->postFields .= "&MasterTPSysId=" . $MasterTPSysId;
                    $this->postFields .= "&TPSysId=" . $TPSysId;
                    $this->postFields .= "&VersionId=" . $VersionId;
                    $this->postFields .= "&XRefBookingId=" . '';
                    $this->postFields .= "&APIBookingRes=" . '';
                    $this->postFields .= "&ErrorCode=" . '6';
                    $model = new Gtxwebservices_Model_Webservices();
                    $result = $model->updateFlightBookingDetails($this->postFields);
                    
                } catch (Exception $error) {
                    
                }
                //$response = json_decode($result,true);
                // Update Booking Status to B2B end.........
                
                
                
                $search_id  = $urlData['TraceId'];
                $rindex     = $urlData['resultindex'];
                
                //$arr['UrlData'] = $urlData;
                
                
                $insertdata = [
                        'UrlData' => json_encode($urlData),
                        'CreatedDate' => date('Y-m-d h:i:s')
                    ];
                
                $lastInsertId = $resultset = $this->objMdl->rv_insert("tbl_temp_urldata", $insertdata);
                echo json_encode(array("success" => false, "pstatus" => $paymentStatus));
                exit;
            
            }
        }
        
        
    }
    
    public function bookingDetailsAction(){
        $this->_helper->layout->setLayout('flight-book-layout');
        $this->view->baseUrl    = $this->baseUrl;
        $this->view->id  = $id = $this->getRequest()->getParam('id');
        
        if ($this->_request->isXmlHttpRequest()) { 
            $this->_helper->layout->disableLayout();
            $urlId = base64_decode($this->getRequest()->getParam('urlId'));
            $objTempUrl = new Flights_Model_TblTempUrl();
            $arrUrlData = $objTempUrl->getUrlData($urlId);
            $arrResponse = isset($arrUrlData['UrlData'])?json_decode($arrUrlData['UrlData'],true):[];
            
            
            $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:'';
            
            
            $Results = isset($arrResponse['Response']['Response']['FlightItinerary'])?$arrResponse['Response']['Response']['FlightItinerary']:[];
            //echo "<pre>";print_r($arrResponse);exit;
            $arr = [];
            if(count($Results)>0){
                    
                    
                    $arr['NonRefundable']       = $Results['NonRefundable'];
                    $arr['PNR']                 = $Results['PNR'];
                    $arr['BookingId']           = $Results['BookingId'];
                    $arr['LastTicketDate']      = $Results['LastTicketDate'];
                    $arr['Currency']            = $Results['Fare']['Currency'];
                    $arr['BaseFare']            = $Results['Fare']['BaseFare'];
                    $arr['Tax']                 = $Results['Fare']['Tax'];
                    $arr['YQTax']               = $Results['Fare']['YQTax'];
                    $arr['AdditionalTxnFeeOfrd']= $Results['Fare']['AdditionalTxnFeeOfrd'];
                    $arr['AdditionalTxnFeePub'] = $Results['Fare']['AdditionalTxnFeePub'];
                    $arr['OtherCharges']        = $Results['Fare']['OtherCharges'];
                    $arr['Discount']            = $Results['Fare']['Discount'];
                    $arr['publishedfare']       = $Results['Fare']['PublishedFare'];
                    $arr['CommissionEarned']    = $Results['Fare']['CommissionEarned'];
                    $arr['PLBEarned']           = $Results['Fare']['PLBEarned'];
                    $arr['IncentiveEarned']     = $Results['Fare']['IncentiveEarned'];
                    $arr['OfferedFare']         = $Results['Fare']['OfferedFare'];
                    $arr['TdsOnCommission']     = $Results['Fare']['TdsOnCommission'];
                    $arr['TdsOnPLB']            = $Results['Fare']['TdsOnPLB'];
                    $arr['TdsOnIncentive']      = $Results['Fare']['TdsOnIncentive'];
                    $arr['ServiceFee']          = $Results['Fare']['ServiceFee'];
                    $arr['FareBreakdown']       = $Results['FareBreakdown'];
                    
                    
                    
                    
                    
//                    "Currency": "INR", 
//                    "PassengerType": 1, 
//                    "PassengerCount": 1, 
//                    "BaseFare": 4350, 
//                    "Tax": 1267, 
//                    "YQTax": 0, 
//                    "AdditionalTxnFeeOfrd": 0, 
//                    "AdditionalTxnFeePub": 0, 
                    
                    $arrPassenger = isset($Results['Passenger'])?$Results['Passenger']:[];
                    
                    if(isset($arrPassenger) && count($arrPassenger)>0){
                        $arrPass = [];
                        foreach($arrPassenger as $val){
                            $arrPass[] = [
                                'Title'     => $val['Title'],
                                'FirstName' => $val['FirstName'],
                                'LastName'  => $val['LastName'],
                                'ContactNo' => $val['ContactNo'],
                                'Email'     => $val['Email']
                            ];
                        }
                    }
                    
                    //echo "<pre>";print_r($arrPass);exit;
                    
                    
                    $arrSegments = isset($Results['Segments'])?$Results['Segments']:[];
                        if(count($arrSegments)>0){
                            $AirSegments1 = [];
                            $AirSegments2 = [];
                            foreach ($arrSegments as $key => $flightsegments){
                               // foreach ($value as $flightsegments){
                                 //   echo "<pre>";print_r($value);exit;

                                    if($flightsegments['TripIndicator'] == 1){
                                        
                                        
                                        // airline logos images...
                                        $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                                        if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                            $strAirlineLogo = $strAirlineCode . ".gif";
                                        } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                            $strAirlineLogo = $strAirlineCode . ".png";
                                        }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                            $strAirlineLogo = $strAirlineCode . ".jpg";
                                        }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                            $strAirlineLogo = $strAirlineCode . ".jpeg";
                                        }else{
                                            $strAirlineLogo = "noimage.png";
                                        }
                                        // airline logos images ends...


                                        $departureat = $flightsegments['StopPointDepartureTime'];
                                        $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                                        $departureat = explode(" ",$departureat);
                                        $arrivalat = $flightsegments['StopPointArrivalTime'];
                                        $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                                        $arrivalat = explode(" ",$arrivalat);

                                        $flightduration = isset($flightsegments['Duration'])?$flightsegments['Duration']:0;
                                        $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...

                                        $GroundTime = isset($flightsegments['GroundTime'])?$flightsegments['GroundTime']:0;
                                        $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...

                                        $AirSegments1[] = [
                                            'logo'          => $strAirlineLogo,
                                            'airline'       => $flightsegments['Airline']['AirlineName'],
                                            'airlinecode'   => $flightsegments['Airline']['AirlineCode'],
                                            'flightnumber'  => $flightsegments['Airline']['FlightNumber'],
                                            'deptime'       => end($departureat),
                                            'departuredate'   => $departureat[0]." ".$departureat[1]." ".$departureat[2],
                                            'Baggage'       => !empty($flightsegments['Baggage'])?$flightsegments['Baggage']:'NA',
                                            'CabinBaggage'  => !empty($flightsegments['CabinBaggage'])?$flightsegments['CabinBaggage']:'NA',
                                            'airline'       => $flightsegments['Airline']['AirlineName'],
                                            'fareclass'     => $flightsegments['Airline']['FareClass'],
                                            'origin'        => $flightsegments['Origin']['Airport']['AirportCode'],
                                            'originTerminal'  => $flightsegments['Origin']['Airport']['Terminal'],
                                            'origincity'    => $flightsegments['Origin']['Airport']['CityName'],
                                            'originCountryCode'   => $flightsegments['Origin']['Airport']['CountryCode'],
                                            'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                            'destination'   => $flightsegments['Destination']['Airport']['AirportCode'],
                                            'destTerminal'  => $flightsegments['Destination']['Airport']['Terminal'],
                                            'destcity'      => $flightsegments['Destination']['Airport']['CityName'],
                                            'destCountryCode'   => $flightsegments['Destination']['Airport']['CountryCode'],
                                            'destairport'   => $flightsegments['Destination']['Airport']['AirportName'],
                                            'arrtime'       => end($arrivalat),
                                            'arrivaldate'     => $arrivalat[0]." ".$arrivalat[1]." ".$arrivalat[2],
                                            'Duration'      => $strflightduration,
                                            'GroundTime' => $GroundTime,
                                        ];
                                        
                                        
                                    }elseif ($flightsegments['TripIndicator'] == 2) {
                                        
                                        
                                        // airline logos images...
                                        $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                                        if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                            $strAirlineLogo = $strAirlineCode . ".gif";
                                        } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                            $strAirlineLogo = $strAirlineCode . ".png";
                                        }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                            $strAirlineLogo = $strAirlineCode . ".jpg";
                                        }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                            $strAirlineLogo = $strAirlineCode . ".jpeg";
                                        }else{
                                            $strAirlineLogo = "noimage.png";
                                        }
                                        // airline logos images ends...


                                        $departureat = $flightsegments['StopPointDepartureTime'];
                                        $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                                        $departureat = explode(" ",$departureat);
                                        $arrivalat = $flightsegments['StopPointArrivalTime'];
                                        $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                                        $arrivalat = explode(" ",$arrivalat);

                                        $flightduration = isset($flightsegments['Duration'])?$flightsegments['Duration']:0;
                                        $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...

                                        $GroundTime = isset($flightsegments['GroundTime'])?$flightsegments['GroundTime']:0;
                                        $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...

                                        $AirSegments2[] = [
                                            'logo'          => $strAirlineLogo,
                                            'airline'       => $flightsegments['Airline']['AirlineName'],
                                            'airlinecode'   => $flightsegments['Airline']['AirlineCode'],
                                            'flightnumber'  => $flightsegments['Airline']['FlightNumber'],
                                            'deptime'       => end($departureat),
                                            'departuredate'   => $departureat[0]." ".$departureat[1]." ".$departureat[2],
                                            'Baggage'       => !empty($flightsegments['Baggage'])?$flightsegments['Baggage']:'NA',
                                            'CabinBaggage'  => !empty($flightsegments['CabinBaggage'])?$flightsegments['CabinBaggage']:'NA',
                                            'airline'       => $flightsegments['Airline']['AirlineName'],
                                            'fareclass'     => $flightsegments['Airline']['FareClass'],
                                            'origin'        => $flightsegments['Origin']['Airport']['AirportCode'],
                                            'originTerminal'  => $flightsegments['Origin']['Airport']['Terminal'],
                                            'origincity'    => $flightsegments['Origin']['Airport']['CityName'],
                                            'originCountryCode'   => $flightsegments['Origin']['Airport']['CountryCode'],
                                            'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                            'destination'   => $flightsegments['Destination']['Airport']['AirportCode'],
                                            'destTerminal'  => $flightsegments['Destination']['Airport']['Terminal'],
                                            'destcity'      => $flightsegments['Destination']['Airport']['CityName'],
                                            'destCountryCode'   => $flightsegments['Destination']['Airport']['CountryCode'],
                                            'destairport'   => $flightsegments['Destination']['Airport']['AirportName'],
                                            'arrtime'       => end($arrivalat),
                                            'arrivaldate'     => $arrivalat[0]." ".$arrivalat[1]." ".$arrivalat[2],
                                            'Duration'      => $strflightduration,
                                            'GroundTime' => $GroundTime,
                                        ];
                                        
                                        
                                    }
                                    
                                    
                                    
                                //}
                            }
                        }
                        
                        
                        $arr['Segments1']   = $AirSegments1;
                        $arr['Segments2']   = $AirSegments2;
                        $arr['Stops']       = (count($AirSegments)>1)?1:0;
                        $arr['Passengers']  = $arrPass;
                    
            }
            
//            echo "<pre>";print_r($arr);
//            echo "<pre>";print_r($arrResponse);exit;
            
            echo json_encode(array("success" => true, "resdata" => $arr));
            exit;
            
            
        }
        
        
        
    }
    
    public function paymentFailedAction(){
        
        $this->_helper->layout->setLayout('flight-book-layout');
        $this->view->baseUrl    = $this->baseUrl;
        $this->view->search_id  = $search_id = $this->getRequest()->getParam('search_id');
        $this->view->rindex     = $rindex = $this->getRequest()->getParam('rindex');
        $this->view->status     = $status = !empty($this->getRequest()->getParam('status'))?$this->getRequest()->getParam('status'):'';
        
    }
    
    public function returnFareQuotesAction(){
        
        if ($this->_request->isXmlHttpRequest()) { 
            $this->_helper->layout->disableLayout();
            $traceId =  $this->getRequest()->getParam('traceId');
            $rindex1 = $this->getRequest()->getParam('rindex1');
            $rindex2 = $this->getRequest()->getParam('rindex2');
            $isInternational = !empty($this->getRequest()->getParam('isInternational'))?$this->getRequest()->getParam('isInternational'):0;
            
            
            if(!empty($isInternational)){
                $CountryCode = "INTERNATIONAL";
            }else{
                $CountryCode = "IN";
            }
            
//           
            $arr = [];
            
            if(!empty($rindex1)){
                $datah = [
                    "TraceId"       => $traceId,
                    "ResultIndex"   => $rindex1
                ];
            
            try {
                $data_stringh = json_encode($datah);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->flightFareQuotesUrl);
                curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                ));
                $response = curl_exec($ch);
            } catch (Exception $error) {
                $response = $error->getMessage();
            }
            
                $arrResponse = json_decode($response,true);
                //echo "<pre>";print_r($arrResponse);exit;
                
            $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:'';
            if($ErrorCode == 0){
                $IsPriceChanged = isset($arrResponse['Response']['IsPriceChanged'])?$arrResponse['Response']['IsPriceChanged']:'0';
                $TraceId = isset($arrResponse['Response']['TraceId'])?$arrResponse['Response']['TraceId']:'';
                $Results = isset($arrResponse['Response']['Results'])?$arrResponse['Response']['Results']:[];
                if(count($Results)>0){
                        
                    
                        $OfferedFare = $Results['Fare']['OfferedFare'];
                        $PublishedFare = $Results['Fare']['PublishedFare'];
                        
                        $arrAllCommissions = [
                            "intCommissionEarned"   => $Results['Fare']['CommissionEarned'],
                            "intPLBEarned"          => $Results['Fare']['PLBEarned'],
                            "intIncentiveEarned"    => $Results['Fare']['IncentiveEarned']
                        ];
                        
                        $totalCommissions = $Results['Fare']['CommissionEarned'] + $Results['Fare']['PLBEarned'] + $Results['Fare']['IncentiveEarned'];

                        $arrMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getApiPriceWithMarkupAndServiceTax($arrAllCommissions,$OfferedFare,$CountryCode,$this->gtxagencysysid);
                        
                        $intOfferedFare     = $arrMarkUps['intOfferedFare'];
                        $PublishFareWidAllInc    = $arrMarkUps['intPublishFare'];
                        $AgencyMarkUp      = $arrMarkUps['intAgencyFixMarkUp'];
                        $intGTXMarkUp      = $arrMarkUps['intGTXMarkUp'];
                        $intSTaxOnAgencyFixMarkUp    = $arrMarkUps['intSTaxOnAgencyFixMarkUp'];
                        $intSTaxOnGTXMarkUp    = $arrMarkUps['intSTaxOnGTXMarkUp'];
                        $TotalCommisions   = $arrMarkUps['intCommisionEarnedForAgency'];
                        
                        $intTotalEarningsForAgency     = $arrMarkUps['intTotalEarningsForAgency'];
                        $gstOnTotalEarningsForAgency   = $arrMarkUps['intGSTOnAgencyCommisionEarned'] + $arrMarkUps['intGSTOnAgencyPLBEarned'] + $arrMarkUps['intGSTOnAgencyIncentiveEarned'];
                    
                    
                        $arr['TraceId']                       = $TraceId;
                        $arr['Depart']['IsPriceChanged']      = $IsPriceChanged;
                        $arr['Depart']['resultindex']         = $Results['ResultIndex'];
                        $arr['Depart']['lCC']                 = $Results['IsLCC'];
                        $arr['Depart']['refundable']          = $Results['IsRefundable'];
                        $arr['Depart']['Currency']            = $Results['Fare']['Currency'];
                        $arr['Depart']['BaseFare']            = $Results['Fare']['BaseFare'];
                        $arr['Depart']['Tax']                 = $Results['Fare']['Tax'];
                        $arr['Depart']['YQTax']               = $Results['Fare']['YQTax'];
                        $arr['Depart']['AdditionalTxnFeeOfrd']= $Results['Fare']['AdditionalTxnFeeOfrd'];
                        $arr['Depart']['AdditionalTxnFeePub'] = $Results['Fare']['AdditionalTxnFeePub'];
                        $arr['Depart']['OtherCharges']        = $Results['Fare']['OtherCharges'];
                        $arr['Depart']['Discount']            = $Results['Fare']['Discount'];
                        $arr['Depart']['publishedfare']       = $Results['Fare']['PublishedFare'];
                        $arr['Depart']['CommissionEarned']    = $Results['Fare']['CommissionEarned'];
                        $arr['Depart']['PLBEarned']           = $Results['Fare']['PLBEarned'];
                        $arr['Depart']['IncentiveEarned']     = $Results['Fare']['IncentiveEarned'];
                        $arr['Depart']['OfferedFare']         = $Results['Fare']['OfferedFare'];
                        $arr['Depart']['TdsOnCommission']     = $Results['Fare']['TdsOnCommission'];
                        $arr['Depart']['TdsOnPLB']            = $Results['Fare']['TdsOnPLB'];
                        $arr['Depart']['TdsOnIncentive']      = $Results['Fare']['TdsOnIncentive'];
                        $arr['Depart']['ServiceFee']          = $Results['Fare']['ServiceFee'];
                        
                        $OtherCharges        = isset($Results['Fare']['OtherCharges'])?$Results['Fare']['OtherCharges']:0;
                        
                        $arrFareBreakdown = isset($Results['FareBreakdown'])?$Results['FareBreakdown']:[];
                        
                        
                        
                        $AdultPassengerCount = 0;
                        $ChildPassengerCount = 0;
                        $InfantsPassengerCount = 0;
                        $TotalPassengerCount = 0;
                        $arrPaxes = [];
                        foreach($arrFareBreakdown as $paxes){
                            
                            $PassengerType = $paxes['PassengerType'];
                            
                            if($PassengerType == 1){
                                $AdultPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => 0,
                                    'Infants' => 0
                                ];
                            }else if($PassengerType == 2){
                                $ChildPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $PassengerCount
                                ];
                            }else if($PassengerType == 3){
                                $InfantsPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $InfantsPassengerCount
                                ];
                            }
                        }
                        
                        $TotalPassengerCount = $AdultPassengerCount + $ChildPassengerCount + $InfantsPassengerCount;
                        $TotalPassengerCountForDiscount = $AdultPassengerCount + $ChildPassengerCount;
                        $intDiscountPerHead = $totalCommissions/$TotalPassengerCountForDiscount;
                        
                        
                        
                        
                        
                        $TotalPassengerCount = $AdultPassengerCount + $ChildPassengerCount + $InfantsPassengerCount;
                        $TotalPassengerCountForDiscount = $AdultPassengerCount + $ChildPassengerCount;
                        $intDiscountPerHead = $totalCommissions/$TotalPassengerCountForDiscount;
                        
                        //echo "<pre>";print_r($arrFareBreakdown);exit;
                        
                        $intTotalOfferedForAllPax = 0;
                        foreach($arrFareBreakdown as $pax){
                            
                            
                            $intPassengerCount = isset($pax['PassengerCount'])?$pax['PassengerCount']:0;
                            $intBaseFare       = $pax['BaseFare'];
                            $intTax            = $pax['Tax'];
                            $intDiscountPerHead         = ($intDiscountPerHead*$intPassengerCount);
                            $intBaseFareCal             = $intBaseFare - $intDiscountPerHead;
                            $intFareOfferedToPax       = $intBaseFareCal + $intTax;
                            
                            $arr['FareBreakdown'][] = [
                                'Currency'      => $pax['Currency'],
                                'BaseFare'      => $pax['BaseFare'],
                                'Tax'           => $pax['Tax'],
                                'YQTax'         => $pax['YQTax'],
                                'PassengerType' => $pax['PassengerType'],
                                'PassengerCount' => $pax['PassengerCount'],
                                'PGCharge'      => $pax['PGCharge'],
                                'AdditionalTxnFeePub'   => $pax['AdditionalTxnFeePub'],
                                'AdditionalTxnFeeOfrd'  => $pax['AdditionalTxnFeeOfrd'],
                                'AgencyMarkUp'  => $AgencyMarkUp,
                                'GTXMarkUp'  => $intGTXMarkUp,
                                'FareOfferedToPax'  => $intFareOfferedToPax
                            ];
                            
                            $intTotalOfferedForAllPax += $intFareOfferedToPax;
                            
                            
                        }
                        
                        
                        $arr['Depart']['FareBreakdown']             = $arr['FareBreakdown'];
                        $arr['Depart']['TotalOfferedForAllPax']     = $intTotalOfferedForAllPax;
                        
                        
                        $totalGTXMarkup         = $TotalPassengerCount*$intGTXMarkUp;
                        $intTotalOtherCharge    = $OtherCharges + $totalGTXMarkup;
                        $intNetOfferedFare      = $intTotalOfferedForAllPax + $intTotalOtherCharge;
                        
                        $AgencyTotalMarkUp   = $TotalPassengerCount*$AgencyMarkUp;
                        $totalGST = $TotalPassengerCount*$intSTaxOnAgencyFixMarkUp;
                        $ServicesAndTaxAndAll      = round($AgencyTotalMarkUp + $totalGST + $intTotalEarningsForAgency + $gstOnTotalEarningsForAgency);
                        $CostToCustomer = round($intNetOfferedFare + $ServicesAndTaxAndAll);
                        
                        
                        $arr['Depart']['NetOfferedFare']      = $intNetOfferedFare;
                        $arr['Depart']['ServicesAndTax']      = $ServicesAndTaxAndAll;
                        $arr['Depart']['TotalOtherCharge']    = $intTotalOtherCharge;
                        $arr['Depart']['CostToCustomer']      = $CostToCustomer;
                        
                        
                        
                        $arr['Depart']['GTXMarkUp']                   = $totalGTXMarkup;
                        $arr['Depart']['AgencyTotalMarkUp']           = $AgencyTotalMarkUp;
                        $arr['Depart']['gstonAgencyMarkup']           = $totalGST;
                        $arr['Depart']['AgencyTotalCommisions']       = $intTotalEarningsForAgency;
                        $arr['Depart']['GSTAgencyTotalCommisions']    = $gstOnTotalEarningsForAgency;
                        $arr['Depart']['PaxCount']                    = $arrPaxes;
                        $arr['Depart']['TotalPassengerCount']         = $TotalPassengerCount;
                        $arr['Depart']['PaxCount']                    = $arrPaxes;
                        
                        
                        
                        
                        $arrSegments = isset($Results['Segments'])?$Results['Segments']:[];
                        //echo "<pre>";print_r($arr);exit;
                        if(count($arrSegments)>0){
                            
                            foreach ($arrSegments as $key => $value){
                                $AirSegments = [];
                                foreach ($value as $segkey => $flightsegments){
                                    
                                    // airline logos images...
                                    $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                                    if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                        $strAirlineLogo = $strAirlineCode . ".gif";
                                    } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                        $strAirlineLogo = $strAirlineCode . ".png";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpg";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpeg";
                                    }else{
                                        $strAirlineLogo = "noimage.png";
                                    }
                                    // airline logos images ends...
                                    
                                    if($segkey == 0){
                                        $departureDate = !empty(explode("T", $flightsegments['StopPointDepartureTime']))?explode("T", $flightsegments['StopPointDepartureTime']):'';
                                        $departureDate = $departureDate[0];
                                        $departFrom = $flightsegments['Origin']['Airport']['AirportCode'];
                                        
                                    }
                                    
                                    $departTo = $flightsegments['Destination']['Airport']['AirportCode'];
                                    
                                    $departureat = $flightsegments['StopPointDepartureTime'];
                                    $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                                    $departureat = explode(" ",$departureat);
                                    $arrivalat = $flightsegments['StopPointArrivalTime'];
                                    $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                                    $arrivalat = explode(" ",$arrivalat);
                                    
                                    $flightduration = isset($flightsegments['Duration'])?$flightsegments['Duration']:0;
                                    $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...
                                    
                                    $GroundTime = isset($flightsegments['GroundTime'])?$flightsegments['GroundTime']:0;
                                    $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...
                                    
                                    $AirSegments[] = [
                                        'logo'          => $strAirlineLogo,
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'airlinecode'   => $flightsegments['Airline']['AirlineCode'],
                                        'flightnumber'  => $flightsegments['Airline']['FlightNumber'],
                                        'deptime'       => end($departureat),
                                        'departuredate'   => $departureat[0]." ".$departureat[1]." ".$departureat[2],
                                        'Baggage'       => $flightsegments['Baggage'],
                                        'CabinBaggage'  => $flightsegments['CabinBaggage'],
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'fareclass'     => $flightsegments['Airline']['FareClass'],
                                        'origin'        => $flightsegments['Origin']['Airport']['AirportCode'],
                                        'originTerminal'  => $flightsegments['Origin']['Airport']['Terminal'],
                                        'origincity'    => $flightsegments['Origin']['Airport']['CityName'],
                                        'originCountryCode'   => $flightsegments['Origin']['Airport']['CountryCode'],
                                        'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                        'destination'   => $flightsegments['Destination']['Airport']['AirportCode'],
                                        'destTerminal'  => $flightsegments['Destination']['Airport']['Terminal'],
                                        'destcity'      => $flightsegments['Destination']['Airport']['CityName'],
                                        'destCountryCode'   => $flightsegments['Destination']['Airport']['CountryCode'],
                                        'destairport'   => $flightsegments['Destination']['Airport']['AirportName'],
                                        'arrtime'       => end($arrivalat),
                                        'arrivaldate'     => $arrivalat[0]." ".$arrivalat[1]." ".$arrivalat[2],
                                        'Duration'      => $strflightduration,
                                        'GroundTime' => $GroundTime,
                                    ];
                                    
                                }
                                $arr['Depart']['Segments1'] = $AirSegments;
                                
                            }
                        }
                        
                        
                        
                        $arr['Depart']['Stops'] = (count($AirSegments)>1)?1:0;
                        $arr['Depart']['departureDate'] = $departureDate;
                        $arr['Depart']['departureFrom'] = $departFrom;
                        $arr['Depart']['departureTo'] = $departTo;
                        
                        
                }
                
                
            }else{
                
                $arrCustomErrors = unserialize(CONST_FLIGHT_CUSTOM_ERRORS);
                $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:0;
                $arr['error']    = $arrCustomErrors[$ErrorCode];
                echo json_encode(array("success" => false, "resdata" => $arr));
                exit;
            }
                
            }// Departure if ends here ...
            
            
            
            if(!empty($rindex2)){
                $datah = [
                    "TraceId"       => $traceId,
                    "ResultIndex"   => $rindex2
                ];
            
            try {
                $data_stringh = json_encode($datah);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->flightFareQuotesUrl);
                curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                ));
                $response = curl_exec($ch);
            } catch (Exception $error) {
                $response = $error->getMessage();
            }
            
                $arrResponse = json_decode($response,true);
                
                
            $ErrorCode = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:'';
            if($ErrorCode == 0){
                $IsPriceChanged = isset($arrResponse['Response']['IsPriceChanged'])?$arrResponse['Response']['IsPriceChanged']:'0';
                $Results = isset($arrResponse['Response']['Results'])?$arrResponse['Response']['Results']:[];
                if(count($Results)>0){
                    
                    
                        $OfferedFare = $Results['Fare']['OfferedFare'];
                        $PublishedFare = $Results['Fare']['PublishedFare'];
                        
                        $arrAllCommissions = [
                            "intCommissionEarned"   => $Results['Fare']['CommissionEarned'],
                            "intPLBEarned"          => $Results['Fare']['PLBEarned'],
                            "intIncentiveEarned"    => $Results['Fare']['IncentiveEarned']
                        ];
                        
                        $totalCommissions = $Results['Fare']['CommissionEarned'] + $Results['Fare']['PLBEarned'] + $Results['Fare']['IncentiveEarned'];

                        $arrMarkUps = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getApiPriceWithMarkupAndServiceTax($arrAllCommissions,$OfferedFare,$CountryCode,$this->gtxagencysysid);
                        
                        $intOfferedFare     = $arrMarkUps['intOfferedFare'];
                        $PublishFareWidAllInc    = $arrMarkUps['intPublishFare'];
                        $AgencyMarkUp      = $arrMarkUps['intAgencyFixMarkUp'];
                        $intGTXMarkUp      = $arrMarkUps['intGTXMarkUp'];
                        $intSTaxOnAgencyFixMarkUp    = $arrMarkUps['intSTaxOnAgencyFixMarkUp'];
                        $intSTaxOnGTXMarkUp    = $arrMarkUps['intSTaxOnGTXMarkUp'];
                        $TotalCommisions   = $arrMarkUps['intCommisionEarnedForAgency'];
                        
                        $intTotalEarningsForAgency     = $arrMarkUps['intTotalEarningsForAgency'];
                        $gstOnTotalEarningsForAgency   = $arrMarkUps['intGSTOnAgencyCommisionEarned'] + $arrMarkUps['intGSTOnAgencyPLBEarned'] + $arrMarkUps['intGSTOnAgencyIncentiveEarned'];
                        
                    

                        $arr['Return']['IsPriceChanged']      = $IsPriceChanged;
                        $arr['Return']['resultindex']         = $Results['ResultIndex'];
                        $arr['Return']['lCC']                 = $Results['IsLCC'];
                        $arr['Return']['refundable']          = $Results['IsRefundable'];
                        $arr['Return']['Currency']            = $Results['Fare']['Currency'];
                        $arr['Return']['BaseFare']            = $Results['Fare']['BaseFare'];
                        $arr['Return']['Tax']                 = $Results['Fare']['Tax'];
                        $arr['Return']['YQTax']               = $Results['Fare']['YQTax'];
                        $arr['Return']['AdditionalTxnFeeOfrd']= $Results['Fare']['AdditionalTxnFeeOfrd'];
                        $arr['Return']['AdditionalTxnFeePub'] = $Results['Fare']['AdditionalTxnFeePub'];
                        $arr['Return']['OtherCharges']        = $Results['Fare']['OtherCharges'];
                        $arr['Return']['Discount']            = $Results['Fare']['Discount'];
                        $arr['Return']['publishedfare']       = $Results['Fare']['PublishedFare'];
                        $arr['Return']['CommissionEarned']    = $Results['Fare']['CommissionEarned'];
                        $arr['Return']['PLBEarned']           = $Results['Fare']['PLBEarned'];
                        $arr['Return']['IncentiveEarned']     = $Results['Fare']['IncentiveEarned'];
                        $arr['Return']['OfferedFare']         = $Results['Fare']['OfferedFare'];
                        $arr['Return']['TdsOnCommission']     = $Results['Fare']['TdsOnCommission'];
                        $arr['Return']['TdsOnPLB']            = $Results['Fare']['TdsOnPLB'];
                        $arr['Return']['TdsOnIncentive']      = $Results['Fare']['TdsOnIncentive'];
                        $arr['Return']['ServiceFee']          = $Results['Fare']['ServiceFee'];
                        $arr['Return']['FareBreakdown']       = $Results['FareBreakdown'];
                        
                        $OtherCharges        = isset($Results['Fare']['OtherCharges'])?$Results['Fare']['OtherCharges']:0;
                        
                        $arrFareBreakdown = isset($Results['FareBreakdown'])?$Results['FareBreakdown']:[];
                        
                        
                        $AdultPassengerCount = 0;
                        $ChildPassengerCount = 0;
                        $InfantsPassengerCount = 0;
                        $TotalPassengerCount = 0;
                        $arrPaxes = [];
                        foreach($arrFareBreakdown as $paxes){
                            
                            $PassengerType = $paxes['PassengerType'];
                            
                            if($PassengerType == 1){
                                $AdultPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => 0,
                                    'Infants' => 0
                                ];
                            }else if($PassengerType == 2){
                                $ChildPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $PassengerCount
                                ];
                            }else if($PassengerType == 3){
                                $InfantsPassengerCount = $paxes['PassengerCount'];
                                $arrPaxes = [
                                    'adults' => $AdultPassengerCount,
                                    'Childs' => $ChildPassengerCount,
                                    'Infants' => $InfantsPassengerCount
                                ];
                            }
                        }
                        
                        $TotalPassengerCount = $AdultPassengerCount + $ChildPassengerCount + $InfantsPassengerCount;
                        $TotalPassengerCountForDiscount = $AdultPassengerCount + $ChildPassengerCount;
                        $intDiscountPerHead = $totalCommissions/$TotalPassengerCountForDiscount;
                        

                        
                        $TotalPassengerCount = $AdultPassengerCount + $ChildPassengerCount + $InfantsPassengerCount;
                        $TotalPassengerCountForDiscount = $AdultPassengerCount + $ChildPassengerCount;
                        $intDiscountPerHead = $totalCommissions/$TotalPassengerCountForDiscount;
                        
                        //echo "<pre>";print_r($arrFareBreakdown);exit;
                        
                        $intTotalOfferedForAllPax = 0;
                        $arr['FareBreakdown'] = [];
                        foreach($arrFareBreakdown as $pax){
                            
                            
                            $intPassengerCount = isset($pax['PassengerCount'])?$pax['PassengerCount']:0;
                            $intBaseFare       = $pax['BaseFare'];
                            $intTax            = $pax['Tax'];
                            $intDiscountPerHead         = ($intDiscountPerHead*$intPassengerCount);
                            $intBaseFareCal             = $intBaseFare - $intDiscountPerHead;
                            $intFareOfferedToPax       = $intBaseFareCal + $intTax;
                            
                            $arr['FareBreakdown'][] = [
                                'Currency'      => $pax['Currency'],
                                'BaseFare'      => $pax['BaseFare'],
                                'Tax'           => $pax['Tax'],
                                'YQTax'         => $pax['YQTax'],
                                'PassengerType' => $pax['PassengerType'],
                                'PassengerCount' => $pax['PassengerCount'],
                                'PGCharge'      => $pax['PGCharge'],
                                'AdditionalTxnFeePub'   => $pax['AdditionalTxnFeePub'],
                                'AdditionalTxnFeeOfrd'  => $pax['AdditionalTxnFeeOfrd'],
                                'AgencyMarkUp'  => $AgencyMarkUp,
                                'GTXMarkUp'  => $intGTXMarkUp,
                                'FareOfferedToPax'  => $intFareOfferedToPax
                            ];
                            
                            $intTotalOfferedForAllPax += $intFareOfferedToPax;
                            
                            
                        }
                        
                        
                        $arr['Return']['FareBreakdown']             = $arr['FareBreakdown'];
                        $arr['Return']['TotalOfferedForAllPax']     = $intTotalOfferedForAllPax;
                        
                        
                        $totalGTXMarkup         = $TotalPassengerCount*$intGTXMarkUp;
                        $intTotalOtherCharge    = $OtherCharges + $totalGTXMarkup;
                        $intNetOfferedFare      = $intTotalOfferedForAllPax + $intTotalOtherCharge;
                        
                        $AgencyTotalMarkUp   = $TotalPassengerCount*$AgencyMarkUp;
                        $totalGST = $TotalPassengerCount*$intSTaxOnAgencyFixMarkUp;
                        $ServicesAndTaxAndAll      = round($AgencyTotalMarkUp + $totalGST + $intTotalEarningsForAgency + $gstOnTotalEarningsForAgency);
                        $CostToCustomer = round($intNetOfferedFare + $ServicesAndTaxAndAll);
                        
                        
                        $arr['Return']['NetOfferedFare']      = $intNetOfferedFare;
                        $arr['Return']['ServicesAndTax']      = $ServicesAndTaxAndAll;
                        $arr['Return']['TotalOtherCharge']    = $intTotalOtherCharge;
                        $arr['Return']['CostToCustomer']      = $CostToCustomer;
                        
                        
                        
                        $arr['Return']['GTXMarkUp']                   = $totalGTXMarkup;
                        $arr['Return']['AgencyTotalMarkUp']           = $AgencyTotalMarkUp;
                        $arr['Return']['gstonAgencyMarkup']           = $totalGST;
                        $arr['Return']['AgencyTotalCommisions']       = $intTotalEarningsForAgency;
                        $arr['Return']['GSTAgencyTotalCommisions']    = $gstOnTotalEarningsForAgency;
                        $arr['Return']['PaxCount']                    = $arrPaxes;
                        $arr['Return']['TotalPassengerCount']         = $TotalPassengerCount;
                        $arr['Return']['PaxCount']                    = $arrPaxes;
                        
                        
                        
                        
                        $arrSegments = isset($Results['Segments'])?$Results['Segments']:[];
                        //echo "<pre>";print_r($arrSegments);exit;
                        if(count($arrSegments)>0){
                            
                            foreach ($arrSegments as $key => $value){
                                $AirSegments = [];
                                foreach ($value as $segkey => $flightsegments){
                                    
                                    // airline logos images...
                                    $strAirlineCode = $flightsegments['Airline']['AirlineCode'];
                                    if (file_exists($this->flightLogoPath . $strAirlineCode . ".gif")) {
                                        $strAirlineLogo = $strAirlineCode . ".gif";
                                    } elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".png")) {
                                        $strAirlineLogo = $strAirlineCode . ".png";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpg";
                                    }elseif (file_exists($this->flightLogoPath . $strAirlineCode . ".jpeg")) {
                                        $strAirlineLogo = $strAirlineCode . ".jpeg";
                                    }else{
                                        $strAirlineLogo = "noimage.png";
                                    }
                                    // airline logos images ends...
                                    
                                    if($segkey == 0){
                                        $departureDate = !empty(explode("T", $flightsegments['StopPointDepartureTime']))?explode("T", $flightsegments['StopPointDepartureTime']):'';
                                        $departureDate = $departureDate[0];
                                        $departFrom = $flightsegments['Origin']['Airport']['AirportCode'];
                                        
                                    }
                                    
                                    $departTo = $flightsegments['Destination']['Airport']['AirportCode'];
                                    
                                    $departureat = $flightsegments['StopPointDepartureTime'];
                                    $departureat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($departureat); // API time format...
                                    $departureat = explode(" ",$departureat);
                                    $arrivalat = $flightsegments['StopPointArrivalTime'];
                                    $arrivalat = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getDateTimeFormatString($arrivalat); // API time format...
                                    $arrivalat = explode(" ",$arrivalat);
                                    
                                    $flightduration = isset($flightsegments['Duration'])?$flightsegments['Duration']:0;
                                    $strflightduration = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($flightduration); // minutes to hours...
                                    
                                    $GroundTime = isset($flightsegments['GroundTime'])?$flightsegments['GroundTime']:0;
                                    $GroundTime = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->convertMinutesToHoursFormat($GroundTime); // minutes to hours...
                                    
                                    $AirSegments[] = [
                                        'logo'          => $strAirlineLogo,
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'airlinecode'   => $flightsegments['Airline']['AirlineCode'],
                                        'flightnumber'  => $flightsegments['Airline']['FlightNumber'],
                                        'deptime'       => end($departureat),
                                        'departuredate'   => $departureat[0]." ".$departureat[1]." ".$departureat[2],
                                        'Baggage'       => $flightsegments['Baggage'],
                                        'CabinBaggage'  => $flightsegments['CabinBaggage'],
                                        'airline'       => $flightsegments['Airline']['AirlineName'],
                                        'fareclass'     => $flightsegments['Airline']['FareClass'],
                                        'origin'        => $flightsegments['Origin']['Airport']['AirportCode'],
                                        'originTerminal'  => $flightsegments['Origin']['Airport']['Terminal'],
                                        'origincity'    => $flightsegments['Origin']['Airport']['CityName'],
                                        'originCountryCode'   => $flightsegments['Origin']['Airport']['CountryCode'],
                                        'Originairport' => $flightsegments['Origin']['Airport']['AirportName'],
                                        'destination'   => $flightsegments['Destination']['Airport']['AirportCode'],
                                        'destTerminal'  => $flightsegments['Destination']['Airport']['Terminal'],
                                        'destcity'      => $flightsegments['Destination']['Airport']['CityName'],
                                        'destCountryCode'   => $flightsegments['Destination']['Airport']['CountryCode'],
                                        'destairport'   => $flightsegments['Destination']['Airport']['AirportName'],
                                        'arrtime'       => end($arrivalat),
                                        'arrivaldate'     => $arrivalat[0]." ".$arrivalat[1]." ".$arrivalat[2],
                                        'Duration'      => $strflightduration,
                                        'GroundTime' => $GroundTime,
                                    ];
                                    
                                }
                                $arr['Return']['Segments2'] = $AirSegments;
                            }
                        }
                        
                        
                        
                        $arr['Return']['Stops'] = (count($AirSegments)>1)?1:0;
                        $arr['Return']['departureDate'] = $departureDate;
                        $arr['Return']['departureFrom'] = $departFrom;
                        $arr['Return']['departureTo'] = $departTo;
                        
                        
                        
                }
                
                
                

                
                
            }else{
                
                $arrCustomErrors = unserialize(CONST_FLIGHT_CUSTOM_ERRORS);
                $ErrorCode       = isset($arrResponse['Response']['Error']['ErrorCode'])?$arrResponse['Response']['Error']['ErrorCode']:0;
                $arr['error']    = $arrCustomErrors[$ErrorCode];
                echo json_encode(array("success" => false, "resdata" => $arr));
                exit;
            }
                
                
                
            } //Retrun if ends here ...
            
            $IsPriceChanged = '';
            if(($arr['Depart']['IsPriceChanged'] == 1) || ($arr['Return']['IsPriceChanged'] == 1)){
               $IsPriceChanged = 1;
            }
            
            
            
            echo json_encode(array("success" => true, "resdata" => $arr,"IsPriceChanged" => $IsPriceChanged));
            exit;
            
            
            
            
        }
        exit;
        
    }
    
    public function flightSSRRequestAction($data){

            $datah = array(
                "TraceId"       => $data['TraceId'],
                "ResultIndex"   => $data['resultindex']
            );

            try {
                $data_stringh = json_encode($datah);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->flightSSRUrl);
                curl_setopt($ch, CURLOPT_ENCODING, "gzip");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datah));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                ));
                $response = curl_exec($ch);
            } catch (Exception $error) {
                $response = $error->getMessage();
            }

            return json_decode($response,true);
        
    }
    
    public function generateFlightProposalAction($data,$arrMarkupsAndPrice){
        
        //echo "<pre>";print_r($arrMarkupsAndPrice);exit;
        $AgentCommisionEarned = $arrMarkupsAndPrice['AgentCommisionEarned'];
        $AgentCommisionEarnedGST = $arrMarkupsAndPrice['AgentCommisionEarnedGST'];
        $AgencyMarkUp = $arrMarkupsAndPrice['AgencyMarkUp'];
        $AgencyMarkUpGST = $arrMarkupsAndPrice['AgencyMarkUpGST'];
        $GTXMarkUp = $arrMarkupsAndPrice['GTXMarkUp'];
        $GTXMarkUpGST = $arrMarkupsAndPrice['GTXMarkUpGST'];
        $BaseAmount = $arrMarkupsAndPrice['BaseAmount'];
        $TotalCost = $arrMarkupsAndPrice['TotalCost'];
        
        
        $arrProposalData = isset($data['fare-quote'])?json_decode($data['fare-quote'],true):[];
        
        $Mobile = $data['mobileNumber'];
        $emailId = $data['emailId'];
        $adultCount = $arrProposalData['PaxCount']['adults'];
        $childCount = $arrProposalData['PaxCount']['Childs'];
        $infantCount = $arrProposalData['PaxCount']['Infants'];
        
        
        $arrSegments1 = isset($arrProposalData['Segments1'])?$arrProposalData['Segments1']:[];
        
        $arrCurrentSegments1 = current($arrSegments1);
        $arrEndSegments1 = end($arrSegments1);
        
        $OriginCity = ($arrCurrentSegments1['origincity']);
        $Destcity = ($arrEndSegments1['destcity']);
        
        $originAirCode = ($arrCurrentSegments1['origin']);
        $destinationAirCode = ($arrEndSegments1['destination']);
        
        $airlinecode = ($arrCurrentSegments1['airlinecode']);
        $flightnumber = ($arrCurrentSegments1['flightnumber']);
        
        $departuredate = ($arrCurrentSegments1['departuredate']);
        $departuredate = date('Y-m-d', strtotime($departuredate));
        $deptime = ($arrCurrentSegments1['deptime']);
        
        $arrivaldate = ($arrEndSegments1['arrivaldate']);
        $arrivaldate = date('Y-m-d', strtotime($arrivaldate));
        $arrtime = ($arrEndSegments1['arrtime']);
        
        
        
        $arrPax = [];
        for($i=0;$i<count($data['PassengerType']);$i++){
            $arrPax[] = [
                "PassengerType" => $data['PassengerType'][$i],
                "salutation" => $data['salutation'][$i],
                "fname" => $data['firstName'][$i],
                "lname" => $data['lastName'][$i],
                "dob" => $data['dob'][$i],
                "address" => $data['paxaddress']
            ];
        }
        
        $jsonPaxDetails = json_encode($arrPax);
        
        
        $roomjson=array();
        $roomjson[1]['Adult']  = $adultCount;
        $roomjson[1]['Child']  = $childCount;
        $roomjson[1]['Infant']  = $infantCount;
        $roomjson[1]['bedtype'] = '';
        $roomjson[1]['departuredate'] = date('d/m/Y', strtotime($departuredate));
        $roomjson[1]['returndate'] = '';
        $roomjson[1]['fromaircode'] = $originAirCode;
        $roomjson[1]['toaircode'] = $destinationAirCode;
        $roomjson[1]['airclass'] = '';
        
        
        for($c=1;$c<=$childCount;$c++){
            $childsage = $infantCount;
            $roomjson[$c]['Adult']  = $adultCount;
            $roomjson[$c]['Child']  = $childCount;
            $roomjson[$c]['ChildAge_'.$c]  = $childsage;
            $roomjson[$c]['bedtype'] = '';
            $roomjson[$c]['departuredate'] = date('d/m/Y', strtotime($departuredate));
            $roomjson[$c]['returndate'] = '';
            $roomjson[$c]['fromaircode'] = $originAirCode;
            $roomjson[$c]['toaircode'] = $destinationAirCode;
            $roomjson[$c]['airclass'] = '';
        }
        $RoomInfoJson= json_encode($roomjson);
        
        $AgencyTotalMarkUp = $arrProposalData['AgencyTotalCommisions'];
        $AgencyTotalCommisions = $arrProposalData['AgencyTotalMarkUp'];
        $PublishedFare = $arrProposalData['publishedfare'];
        
        
        
        
        $this->postFields = "";
        $this->postFields .= "&AgencySysId=$this->gtxagencysysid";
        $this->postFields .= "&AgentSysId=$this->gtxAgentSysid";
        $this->postFields .= "&Email=" . $emailId;
        $this->postFields .= "&mobile=" . $Mobile;
        $this->postFields .= "&jsonPaxDetails=" . $jsonPaxDetails;
        $this->postFields .= "&SourcePlaceSysId=" . '';
        $this->postFields .= "&DestinationPlacesSysId=" . '';
        $this->postFields .= "&SourcePlaces=" . $OriginCity;
        $this->postFields .= "&DestinationPlaces=" . $Destcity;
        $this->postFields .= "&SourceAirportCode=" . $originAirCode;
        $this->postFields .= "&DestAirportCode=" . $destinationAirCode;
        $this->postFields .= "&FlightNumber=" . $airlinecode."-".$flightnumber;
        $this->postFields .= "&departuredate=" . $departuredate." ".$deptime;
        $this->postFields .= "&arrivaldate=" . $arrivaldate." ".$arrtime;

        $this->postFields .= "&AdultPax=" . $adultCount;
        $this->postFields .= "&ChildPax=" . $childCount;
        $this->postFields .= "&InfantPax=" . $infantCount;

//        $this->postFields .= "&PNR=" . $PNR;
//        $this->postFields .= "&BookingId=" . $BookingId;
//        $this->postFields .= "&TicketId=" . $TicketId;
//        $this->postFields .= "&TicketNumber=" . $TicketNumber;



        $this->postFields .= "&Cities=" . $OriginCity.'-'.$Destcity;
        $this->postFields .= "&IsHotelFromApi=1";
        $this->postFields .= "&roominfojson=" .$RoomInfoJson;


        
        $this->postFields .= "&AgentCommisionEarned=" . $AgentCommisionEarned;
        $this->postFields .= "&AgentCommisionEarnedGST=" . $AgentCommisionEarnedGST;
        $this->postFields .= "&AgencyMarkUp=" . $AgencyMarkUp;
        $this->postFields .= "&AgencyMarkUpGST=" . $AgencyMarkUpGST;
        $this->postFields .= "&GTXMarkUp=" . $GTXMarkUp;
        $this->postFields .= "&GTXMarkUpGST=" . $GTXMarkUpGST;
        $this->postFields .= "&BaseAmount=" . $BaseAmount;
        $this->postFields .= "&PublishedFare=" . $TotalCost;
        
        

        //echo "<pre>"; print_r($this->postFields); exit;
        $model = new Gtxwebservices_Model_Webservices();
        $result = $model->genrateFlightQuery($this->postFields);
        $response = json_decode($result,true);
        //echo "<pre>";print_r($response);exit;
        return $response;
     
        //Flight Lead Generation Code Ends Here :- 
        
    }
    
    public function generateReturnFlightProposalAction($data,$arrMarkupsAndPrice){
        
        
        $AgentCommisionEarned = $arrMarkupsAndPrice['Depart']['AgentCommisionEarned'];
        $AgentCommisionEarnedGST = $arrMarkupsAndPrice['Depart']['AgentCommisionEarnedGST'];
        $AgencyMarkUp = $arrMarkupsAndPrice['Depart']['AgencyMarkUp'];
        $AgencyMarkUpGST = $arrMarkupsAndPrice['Depart']['AgencyMarkUpGST'];
        $GTXMarkUp = $arrMarkupsAndPrice['Depart']['GTXMarkUp'];
        $GTXMarkUpGST = $arrMarkupsAndPrice['Depart']['GTXMarkUpGST'];
        $BaseAmount = $arrMarkupsAndPrice['Depart']['BaseAmount'];
        $TotalCost = $arrMarkupsAndPrice['Depart']['TotalCost'];
        
        
        $arrProposalData = isset($data['fare-quote'])?json_decode($data['fare-quote'],true):[];
        //echo "<pre>";print_r($arrProposalData);exit;
        $Mobile = $data['mobileNumber'];
        $emailId = $data['emailId'];
        $adultCount = $arrProposalData['Depart']['PaxCount']['adults'];
        $childCount = $arrProposalData['Depart']['PaxCount']['Childs'];
        $infantCount = $arrProposalData['Depart']['PaxCount']['Infants'];
        
        
        $arrSegments1 = isset($arrProposalData['Depart']['Segments1'])?$arrProposalData['Depart']['Segments1']:[];
        
        $arrCurrentSegments1 = current($arrSegments1);
        $arrEndSegments1 = end($arrSegments1);
        
        $OriginCity = ($arrCurrentSegments1['origincity']);
        $Destcity = ($arrEndSegments1['destcity']);
        
        $originAirCode = ($arrCurrentSegments1['origin']);
        $destinationAirCode = ($arrEndSegments1['destination']);
        
        $airlinecode = ($arrCurrentSegments1['airlinecode']);
        $flightnumber = ($arrCurrentSegments1['flightnumber']);
        
        $departuredate = ($arrCurrentSegments1['departuredate']);
        $departuredate = date('Y-m-d', strtotime($departuredate));
        $deptime = ($arrCurrentSegments1['deptime']);
        
        $arrivaldate = ($arrEndSegments1['arrivaldate']);
        $arrivaldate = date('Y-m-d', strtotime($arrivaldate));
        $arrtime = ($arrEndSegments1['arrtime']);
        
        
        
        $arrPax = [];
        for($i=0;$i<count($data['PassengerType']);$i++){
            $arrPax[] = [
                "PassengerType" => $data['PassengerType'][$i],
                "salutation" => $data['salutation'][$i],
                "fname" => $data['firstName'][$i],
                "lname" => $data['lastName'][$i],
                "dob" => $data['dob'][$i],
                "address" => $data['paxaddress']
            ];
        }
        
        $jsonPaxDetails = json_encode($arrPax);
        
        
        $roomjson=array();
        $roomjson[1]['Adult']  = $adultCount;
        $roomjson[1]['Child']  = $childCount;
        $roomjson[1]['Infant']  = $infantCount;
        $roomjson[1]['bedtype'] = '';
        $roomjson[1]['departuredate'] = date('d/m/Y', strtotime($departuredate));
        $roomjson[1]['returndate'] = '';
        $roomjson[1]['fromaircode'] = $originAirCode;
        $roomjson[1]['toaircode'] = $destinationAirCode;
        $roomjson[1]['airclass'] = '';
        
        
        for($c=1;$c<=$childCount;$c++){
            $childsage = $infantCount;
            $roomjson[$c]['Adult']  = $adultCount;
            $roomjson[$c]['Child']  = $childCount;
            $roomjson[$c]['ChildAge_'.$c]  = $childsage;
            $roomjson[$c]['bedtype'] = '';
            $roomjson[$c]['departuredate'] = date('d/m/Y', strtotime($departuredate));
            $roomjson[$c]['returndate'] = '';
            $roomjson[$c]['fromaircode'] = $originAirCode;
            $roomjson[$c]['toaircode'] = $destinationAirCode;
            $roomjson[$c]['airclass'] = '';
        }
        $RoomInfoJson= json_encode($roomjson);
        
        $AgencyTotalMarkUp = $arrProposalData['Depart']['AgencyTotalCommisions'];
        $AgencyTotalCommisions = $arrProposalData['Depart']['AgencyTotalMarkUp'];
        $PublishedFare = $arrProposalData['Depart']['publishedfare'];
        
        
        
        
        $this->postFields = "";
        $this->postFields .= "&AgencySysId=$this->gtxagencysysid";
        $this->postFields .= "&AgentSysId=$this->gtxAgentSysid";
        $this->postFields .= "&Email=" . $emailId;
        $this->postFields .= "&mobile=" . $Mobile;
        $this->postFields .= "&jsonPaxDetails=" . $jsonPaxDetails;
        $this->postFields .= "&SourcePlaceSysId=" . '';
        $this->postFields .= "&DestinationPlacesSysId=" . '';
        $this->postFields .= "&SourcePlaces=" . $OriginCity;
        $this->postFields .= "&DestinationPlaces=" . $Destcity;
        $this->postFields .= "&SourceAirportCode=" . $originAirCode;
        $this->postFields .= "&DestAirportCode=" . $destinationAirCode;
        $this->postFields .= "&FlightNumber=" . $airlinecode."-".$flightnumber;
        $this->postFields .= "&departuredate=" . $departuredate." ".$deptime;
        $this->postFields .= "&arrivaldate=" . $arrivaldate." ".$arrtime;

        $this->postFields .= "&AdultPax=" . $adultCount;
        $this->postFields .= "&ChildPax=" . $childCount;
        $this->postFields .= "&InfantPax=" . $infantCount;

//        $this->postFields .= "&PNR=" . $PNR;
//        $this->postFields .= "&BookingId=" . $BookingId;
//        $this->postFields .= "&TicketId=" . $TicketId;
//        $this->postFields .= "&TicketNumber=" . $TicketNumber;



        $this->postFields .= "&Cities=" . $OriginCity.'-'.$Destcity;
        $this->postFields .= "&IsHotelFromApi=1";
        $this->postFields .= "&roominfojson=" .$RoomInfoJson;


        $this->postFields .= "&AgentCommisionEarned=" . $AgentCommisionEarned;
        $this->postFields .= "&AgentCommisionEarnedGST=" . $AgentCommisionEarnedGST;
        $this->postFields .= "&AgencyMarkUp=" . $AgencyMarkUp;
        $this->postFields .= "&AgencyMarkUpGST=" . $AgencyMarkUpGST;
        $this->postFields .= "&GTXMarkUp=" . $GTXMarkUp;
        $this->postFields .= "&GTXMarkUpGST=" . $GTXMarkUpGST;
        $this->postFields .= "&BaseAmount=" . $BaseAmount;
        $this->postFields .= "&PublishedFare=" . $TotalCost;

        //echo "<pre>"; print_r($this->postFields); exit;
        $model = new Gtxwebservices_Model_Webservices();
        $result = $model->genrateFlightQuery($this->postFields);
        $response = json_decode($result,true);
        //echo "<pre>";print_r($response);exit;
        
        
        $ArrResponse = [];
        
        $ArrResponse['Depart']['arrIds'] = $response['arrIds'];
        $ArrResponse['Depart']['message'] = isset($response['message'])?$response['message']:'Oops! there might be some technical issue please contact administrator';
        $ArrResponse['Depart']['redirect'] = isset($response['redirect'])?$response['redirect']:false;
        $ArrResponse['Depart']['status'] = isset($response['status'])?$response['status']:false;
        
        
        
        //Return Flight.............
        
        
        $AgentCommisionEarned = $arrMarkupsAndPrice['Return']['AgentCommisionEarned'];
        $AgentCommisionEarnedGST = $arrMarkupsAndPrice['Return']['AgentCommisionEarnedGST'];
        $AgencyMarkUp = $arrMarkupsAndPrice['Return']['AgencyMarkUp'];
        $AgencyMarkUpGST = $arrMarkupsAndPrice['Return']['AgencyMarkUpGST'];
        $GTXMarkUp = $arrMarkupsAndPrice['Return']['GTXMarkUp'];
        $GTXMarkUpGST = $arrMarkupsAndPrice['Return']['GTXMarkUpGST'];
        $BaseAmount = $arrMarkupsAndPrice['Return']['BaseAmount'];
        $TotalCost = $arrMarkupsAndPrice['Return']['TotalCost'];
        
        
        
        $adultCount = $arrProposalData['Return']['PaxCount']['adults'];
        $childCount = $arrProposalData['Return']['PaxCount']['Childs'];
        $infantCount = $arrProposalData['Return']['PaxCount']['Infants'];
        
        
        $arrSegments1 = isset($arrProposalData['Return']['Segments2'])?$arrProposalData['Return']['Segments2']:[];
        
        $arrCurrentSegments1 = current($arrSegments1);
        $arrEndSegments1 = end($arrSegments1);
        
        $OriginCity = ($arrCurrentSegments1['origincity']);
        $Destcity = ($arrEndSegments1['destcity']);
        
        $originAirCode = ($arrCurrentSegments1['origin']);
        $destinationAirCode = ($arrEndSegments1['destination']);
        
        $airlinecode = ($arrCurrentSegments1['airlinecode']);
        $flightnumber = ($arrCurrentSegments1['flightnumber']);
        
        $departuredate = ($arrCurrentSegments1['departuredate']);
        $departuredate = date('Y-m-d', strtotime($departuredate));
        $deptime = ($arrCurrentSegments1['deptime']);
        
        $arrivaldate = ($arrEndSegments1['arrivaldate']);
        $arrivaldate = date('Y-m-d', strtotime($arrivaldate));
        $arrtime = ($arrEndSegments1['arrtime']);
        
        
        
        $arrPax = [];
        for($i=0;$i<count($data['PassengerType']);$i++){
            $arrPax[] = [
                "PassengerType" => $data['PassengerType'][$i],
                "salutation" => $data['salutation'][$i],
                "fname" => $data['firstName'][$i],
                "lname" => $data['lastName'][$i],
                "dob" => $data['dob'][$i],
                "address" => $data['paxaddress']
            ];
        }
        
        $jsonPaxDetails = json_encode($arrPax);
        
        
        $roomjson=array();
        $roomjson[1]['Adult']  = $adultCount;
        $roomjson[1]['Child']  = $childCount;
        $roomjson[1]['Infant']  = $infantCount;
        $roomjson[1]['bedtype'] = '';
        $roomjson[1]['departuredate'] = date('d/m/Y', strtotime($departuredate));
        $roomjson[1]['returndate'] = '';
        $roomjson[1]['fromaircode'] = $originAirCode;
        $roomjson[1]['toaircode'] = $destinationAirCode;
        $roomjson[1]['airclass'] = '';
        
        
        for($c=1;$c<=$childCount;$c++){
            $childsage = $infantCount;
            $roomjson[$c]['Adult']  = $adultCount;
            $roomjson[$c]['Child']  = $childCount;
            $roomjson[$c]['ChildAge_'.$c]  = $childsage;
            $roomjson[$c]['bedtype'] = '';
            $roomjson[$c]['departuredate'] = date('d/m/Y', strtotime($departuredate));
            $roomjson[$c]['returndate'] = '';
            $roomjson[$c]['fromaircode'] = $originAirCode;
            $roomjson[$c]['toaircode'] = $destinationAirCode;
            $roomjson[$c]['airclass'] = '';
        }
        $RoomInfoJson= json_encode($roomjson);
        
        $AgencyTotalMarkUp = $arrProposalData['Return']['AgencyTotalCommisions'];
        $AgencyTotalCommisions = $arrProposalData['Return']['AgencyTotalMarkUp'];
        $PublishedFare = $arrProposalData['Return']['publishedfare'];
        
        
        
        
        $this->postFields = "";
        $this->postFields .= "&AgencySysId=$this->gtxagencysysid";
        $this->postFields .= "&AgentSysId=$this->gtxAgentSysid";
        $this->postFields .= "&Email=" . $emailId;
        $this->postFields .= "&mobile=" . $Mobile;
        $this->postFields .= "&jsonPaxDetails=" . $jsonPaxDetails;
        $this->postFields .= "&SourcePlaceSysId=" . '';
        $this->postFields .= "&DestinationPlacesSysId=" . '';
        $this->postFields .= "&SourcePlaces=" . $OriginCity;
        $this->postFields .= "&DestinationPlaces=" . $Destcity;
        $this->postFields .= "&SourceAirportCode=" . $originAirCode;
        $this->postFields .= "&DestAirportCode=" . $destinationAirCode;
        $this->postFields .= "&FlightNumber=" . $airlinecode."-".$flightnumber;
        $this->postFields .= "&departuredate=" . $departuredate." ".$deptime;
        $this->postFields .= "&arrivaldate=" . $arrivaldate." ".$arrtime;

        $this->postFields .= "&AdultPax=" . $adultCount;
        $this->postFields .= "&ChildPax=" . $childCount;
        $this->postFields .= "&InfantPax=" . $infantCount;

//        $this->postFields .= "&PNR=" . $PNR;
//        $this->postFields .= "&BookingId=" . $BookingId;
//        $this->postFields .= "&TicketId=" . $TicketId;
//        $this->postFields .= "&TicketNumber=" . $TicketNumber;



        $this->postFields .= "&Cities=" . $OriginCity.'-'.$Destcity;
        $this->postFields .= "&IsHotelFromApi=1";
        $this->postFields .= "&roominfojson=" .$RoomInfoJson;


        $this->postFields .= "&AgentCommisionEarned=" . $AgentCommisionEarned;
        $this->postFields .= "&AgentCommisionEarnedGST=" . $AgentCommisionEarnedGST;
        $this->postFields .= "&AgencyMarkUp=" . $AgencyMarkUp;
        $this->postFields .= "&AgencyMarkUpGST=" . $AgencyMarkUpGST;
        $this->postFields .= "&GTXMarkUp=" . $GTXMarkUp;
        $this->postFields .= "&GTXMarkUpGST=" . $GTXMarkUpGST;
        $this->postFields .= "&BaseAmount=" . $BaseAmount;
        $this->postFields .= "&PublishedFare=" . $TotalCost;

        //echo "<pre>"; print_r($this->postFields); exit;
        $model = new Gtxwebservices_Model_Webservices();
        $result = $model->genrateFlightQuery($this->postFields);
        $response = json_decode($result,true);
        
        
        
        
        
        
       $ArrResponse['Return']['arrIds'] = $response['arrIds']; 
       $ArrResponse['Return']['message'] = isset($response['message'])?$response['message']:'Oops! there might be some technical issue please contact administrator';
       $ArrResponse['Return']['redirect'] = isset($response['redirect'])?$response['redirect']:false;
       $ArrResponse['Return']['status'] = isset($response['status'])?$response['status']:false;
        
        
       
        
        
        return $ArrResponse;
     
        //Flight Lead Generation Code Ends Here :- 
        
    }
    
    public function bookingEmailToAgentAction($data = [],$arrMarkups = []){
        
        $arrSegments = isset($data['Response']['Response']['FlightItinerary']['Segments'])?$data['Response']['Response']['FlightItinerary']['Segments']:[];
        $arrOrigin = current($arrSegments);
        $OriginCityName = isset($arrOrigin['Origin']['Airport']['CityName'])?$arrOrigin['Origin']['Airport']['CityName']:'';
        $arrDestination = end($arrSegments);
        $DestCityName = isset($arrDestination['Destination']['Airport']['CityName'])?$arrDestination['Destination']['Airport']['CityName']:'';       
        //Mail Booking Itenary To Customer
        $html = new Zend_View();
        $html->setScriptPath(APPLICATION_PATH . '/modules/flights/views/scripts/search/');
        $html->assign('arrResponse', $data);
        $html->assign('arrMarkups', $arrMarkups);
        $html->assign('baseUrl',$this->baseUrl);
        $html->assign('siteName',$this->siteName);
        $html->assign('tollfreenumber',$this->tollfreenumber);
        $bodyText = $html->render('booking-email-to-agent.phtml');
        $subject = "Flight Booking Itinerary From ".$OriginCityName." To ".$DestCityName;
        $emailData = array('fromEmail'=>$this->superAdminEmail,'fromName'=>$this->siteName,'subject'=> $subject,'to'=>array($this->superAdminEmail,"gaurav@hellogtx.com"),'bodyHtml'=>$bodyText,'bodyText'=>'');
//        $emailData = array('fromEmail'=>$this->superAdminEmail,'fromName'=>$this->siteName,'subject'=> $subject,'to'=>array("tpiyush684@gmail.com","piyush@catpl.co.in"),'bodyHtml'=>$bodyText,'bodyText'=>'');
        try {
            $this->mailSentByElastice($emailData);
        } catch (Exception $err) {
            print_r($err, true);
        }
        //Mail Booking Itenary To Customer             
    }
    
    public function bookingEmailToCustomerAction($data = [],$arrMarkups = []){
        
        
        $arrPassenger = isset($data['Response']['Response']['FlightItinerary']['Passenger'])?$data['Response']['Response']['FlightItinerary']['Passenger']:[];
        $ToEmailId = isset($arrPassenger[0]['Email'])?$arrPassenger[0]['Email']:'';
        
        $arrSegments = isset($data['Response']['Response']['FlightItinerary']['Segments'])?$data['Response']['Response']['FlightItinerary']['Segments']:[];
        $arrOrigin = current($arrSegments);
        $OriginCityName = isset($arrOrigin['Origin']['Airport']['CityName'])?$arrOrigin['Origin']['Airport']['CityName']:'';
        $arrDestination = end($arrSegments);
        $DestCityName = isset($arrDestination['Destination']['Airport']['CityName'])?$arrDestination['Destination']['Airport']['CityName']:'';
        
        //Mail Booking Itenary To Customer

        $html = new Zend_View();
        $html->setScriptPath(APPLICATION_PATH . '/modules/flights/views/scripts/search/');
        $html->assign('arrResponse', $data);
        $html->assign('arrMarkups', $arrMarkups);
        $html->assign('baseUrl',$this->baseUrl);
        $html->assign('siteName',$this->siteName);
        $html->assign('tollfreenumber',$this->tollfreenumber);
        $bodyText = $html->render('mail-booking-content.phtml');
        $subject = "Flight Booking Itinerary From ".$OriginCityName." To ".$DestCityName;
        $emailData = array('fromEmail'=>$this->superAdminEmail,'fromName'=>$this->siteName,'subject'=> $subject,'to'=>array($ToEmailId),'bodyHtml'=>$bodyText,'bodyText'=>'');
        try {
            $this->mailSentByElastice($emailData);
        } catch (Exception $err) {
            print_r($err, true);
        }
        //Mail Booking Itenary To Customer       
    }
  
}

Youez - 2016 - github.com/yon3zu
LinuXploit