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/b2c.hellogtx.com/library/Helper/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/b2c.hellogtx.com/library/Helper/Flight.php_15_01_2024
<?php

/* * *************************************************************
 * Catabatic Technology Pvt. Ltd.
 * File Name     : Hotel.php
 * File Desc.    : Hotel helper to including supporting functions/methods for Hotels
 * Created By    : Pardeep Panchal <pardeep@catpl.co.in>
 * Created Date  : 24 Nov 2017
 * Updated Date  : 24 Nov 2017
 * ************************************************************* */

class Zend_Controller_Action_Helper_Flight extends Zend_Controller_Action_Helper_Abstract
{

    public $baseUrl;
    public $pluginLoader;
    public $db;
    public $siteName;
    public $IsTBOFlightAPI;
    public $IsTJFlightAPI;
    public $gtxBtoBsite;
    public $IsSeriesFare ;
    public $getTemplateId;
    public $gtxagencysysid;
    public $gtxagentsysid;
    public $Series_Fare_Url;

    public function __construct()
    {

        $this->pluginLoader = new Zend_Loader_PluginLoader();
        $this->db = Zend_Db_Table::getDefaultAdapter();
        $BootStrap = $this->config();
        $this->siteName = $BootStrap['siteName'];
        $this->baseUrl = $BootStrap['siteUrl'];
        $this->IsTBOFlightAPI = $BootStrap['IsTBOFlightAPI'];
        $this->IsTJFlightAPI = $BootStrap['IsTJFlightAPI'];
        $this->gtxBtoBsite  = $BootStrap['gtxBtoBsite'];
        $this->IsSeriesFare  = $BootStrap['IsSeriesFare'];
        $this->getTemplateId = isset($BootStrap["TemplateType"]) ? $BootStrap["TemplateType"] : 0;

        $this->gtxagencysysid       = $BootStrap['gtxagencysysid']; // get gtxagencysysid from application config
        $this->gtxagentsysid       = $BootStrap['gtxagentsysid']; // get gtxagentsysid from application config
        $this->Series_Fare_Url = 'https://gtxapi.hellogtx.com/api/v2/';
    }

    public function config()
    {
        $front = $this->getFrontController();
        $bootstrap = $front->getParam('bootstrap');
        if (null === $bootstrap) {
            throw new Exception('Unable to find bootstrap');
        }
        return $bootstrap->getOptions()['bootstrap'];
    }

    public function getFlightClasses()
    {
        //return array('1' => 'Economy', '2' => 'Premium Economy', '3' => 'Business');
        return array('1' => 'All', '2' => 'Economy', '3' => 'Premium Economy', '4' => 'Business', '5' => 'Premium Business', '6' => 'First');
    }
    public function getFlightClassesTripJack()
    {
        //return array('1' => 'Economy', '2' => 'Premium Economy', '3' => 'Business');
        return array('2' => 'Economy', '3' => 'Premium Economy', '4' => 'Business', '5' => 'Premium Business', '6' => 'First');
    }
    public function getCustomerDetails($tablename, $CustomerSysId)
    {
        $select = $this->db->select()->from("$tablename", "*");
        $select->where("GTX_customerSysId=?", "$CustomerSysId");
        $select->where("IsMarkForDel", 0);
        $select->where("IsActive", 1);
        $select->order("paxType", 'ASC');
        $result = $this->db->fetchRow($select);
        return $result;
    }

    public function sortArrayByColumn(&$arr = [], $col = 0, $order = SORT_ASC)
    {
        $sort_col = array();

        if (count($arr) > 0) {
            foreach ($arr as $key => $row) {
                @$sort_col[$key] = $row[$col];
            }
        }

        @array_multisort($sort_col, $order, $arr);
    }

    public function getDateTimeFormatString($string, $type = 1)
    {  // supplied 2017-12-20T21:10:00 format
        if (empty($string))
            return '';

        if ($type == 1) {
            $arr = explode("T", $string);
            $date = new DateTime($arr[0]);
            return $date->format('D, d M') . ' ' . substr(@$arr[1], 0, 5);
        } elseif ($type == 2) {  // supplied  2017/12/20 format
            $date = new DateTime($string);
            return $date->format('D, d M');
        } elseif ($type == 3) {  // supplied  2017/12/20 format
            $arr = explode("T", $string);
            return substr(@$arr[1], 0, 5);
        }
    }

    public function convertMinutesToHoursFormat($minutes)
    {
        if ($minutes < 1) {
            //return;
        }
        // echo($minutes); die();
        $hours = floor((float)$minutes / 60);
        $minutes = ((float)$minutes % 60);
        return $hours . 'h ' . $minutes . 'm';
    }

    public function CalculateTotalTime($time1, $time2)
    {
        $diff = abs(strtotime($time1) - strtotime($time2));

        $tmins = $diff / 60;
        $hours = floor($tmins / 60);
        $mins = $tmins % 60;
        return $hours . 'h ' . $mins . 'm';
    }

    public function agencyMarkUpAndCommisions($data = [])
    {

        $intCommissionEarned = !empty($data['CommissionEarned']) ? $data['CommissionEarned'] : 0;
        $intIncentiveEarned = !empty($data['IncentiveEarned']) ? $data['IncentiveEarned'] : 0;
        $intPLBEarned = !empty($data['PLBEarned']) ? $data['PLBEarned'] : 0;

        $IsInternational = !empty($data['IsInternational']) ? $data['IsInternational'] : 0;
        if ($IsInternational == 1) {
            $intAirType = 2;
        } else {
            $intAirType = 1;
        }

        $AgencySysId = !empty($data['AgencySysId']) ? $data['AgencySysId'] : 0;

        $objTblMPAirMarkup = new Flights_Model_TblMPAirMarkup();
        $arrAgencyMarkups = $objTblMPAirMarkup->getAgencyMarkupsAir($intAirType, $AgencySysId);

        if (count($arrAgencyMarkups) > 0) {

            $intAgencyCurrencySysId = $arrAgencyMarkups[0]['Currency'];
            $intAgencyMarkUpType = $arrAgencyMarkups[0]['MarkUpType'];
            $intAgencyMarkUp = $arrAgencyMarkups[0]['StdMarkUpPer']; // Agency Fix Mark UP...
            $percentAgencySTax = $arrAgencyMarkups[0]['TaxPer'];

            $intCommssionType = $arrAgencyMarkups[0]['CommssionType']; // 2 For percentage
            $intCommssionVal = $arrAgencyMarkups[0]['CommssionVal']; // Percntage Value For Agency Commision From Actual Commision Retuned From API...

            if ($intCommssionType == 2) { // For Agency Commision In Percentage Only...
                $intAgencyCommisionEarnedFromAcutalCommision = ($intCommissionEarned * $intCommssionVal) / 100;
                $intAgencyPLBEarnedFromAcutalPLB = ($intPLBEarned * $intCommssionVal) / 100;
                $intAgencyIncentiveEarnedFromAcutalIncentive = ($intIncentiveEarned * $intCommssionVal) / 100;

                $TotalCommisions = $intAgencyCommisionEarnedFromAcutalCommision + $intAgencyPLBEarnedFromAcutalPLB + $intAgencyIncentiveEarnedFromAcutalIncentive;
            }


            $arrMarkUps = [
                'CommissionEarned' => $intAgencyCommisionEarnedFromAcutalCommision,
                'IncentiveEarned' => $intAgencyIncentiveEarnedFromAcutalIncentive,
                'PLBEarned' => $intAgencyPLBEarnedFromAcutalPLB,
                'TotalCommisions' => $TotalCommisions,
                'MarkUp' => $intAgencyMarkUp
            ];
        } else {
            $arrMarkUps = [
                'CommissionEarned' => 0,
                'IncentiveEarned' => 0,
                'PLBEarned' => 0,
                'TotalCommisions' => 0,
                'MarkUp' => 0
            ];
        }

        return $arrMarkUps;
    }

    public function CreateSessionSearchParams($getData, $TraceId)
    {

        Zend_Session::namespaceUnset('sessionFlightSearchParams');
        Zend_Session::namespaceUnset('recentSearch');
        if (!empty($getData)) {
            $uri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
            $uriExp = explode('?', $uri);
            $recentSearch = new Zend_Session_Namespace('recentSearch');
            $recentSearch->params = [];
            $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');

            $sessionFlightSearchParams->params = $getData;  // Putting all form data to Session
            // echo "<pre>";print_r($getData);die;
            $departure_dates = $getData['departure_date'];
            $return_dates = $getData['return_date'];
            if (!empty($departure_dates)) {
                $arrDepatureDate = explode("/", $departure_dates);
                if (count($arrDepatureDate) > 0) {
                    $strDepatureDate = $arrDepatureDate[2] . "-" . $arrDepatureDate[1] . "-" . $arrDepatureDate[0];
                }
            }
            if (!empty($return_dates)) {
                $arrReturnDepatureDate = explode("/", $return_dates);
                if (count($arrReturnDepatureDate) > 0) {
                    $strReturnDate = $arrReturnDepatureDate[2] . "-" . $arrReturnDepatureDate[1] . "-" . $arrReturnDepatureDate[0];
                }
            }
            $url = $this->baseUrl . "public/data/dynamic/flight_destinations.json";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $str = curl_exec($ch);
            //            $str = file_get_contents($this->baseUrl . 'public/data/dynamic/flight_destinations.json',FILE_USE_INCLUDE_PATH);
            $Destinationjson = json_decode($str, true);
            $filterByFrom = $getData['source_city']; // or DEL,BLR etc.
            $filterByTo = $getData['destination_city']; // or DEL,BLR etc.
            $PreferredAirline = $getData['PreferredAirline'];
            $arrSourceCityId_ = array_filter($Destinationjson, function ($var) use ($filterByFrom) {
                return ($var['AirportCode'] == $filterByFrom);
            });

            $arrdestinationCityId_ = array_filter($Destinationjson, function ($var) use ($filterByTo) {
                return ($var['AirportCode'] == $filterByTo);
            });

            $arrSourceCityId = array_values($arrSourceCityId_);
            $arrdestinationCityId = array_values($arrdestinationCityId_);
            if (count($arrSourceCityId) > 0) {
                $intSourceCityId = $arrSourceCityId[0]['CityID'];
                $intCountryCode = trim($arrSourceCityId[0]['CountryCode']);
                $intOriginCountryCode = trim($arrSourceCityId[0]['CountryCode']);
            } else {
                $intSourceCityId = "";
                $intCountryCode = "";
            }

            if (count($arrdestinationCityId) > 0) {
                $intdestinationCityId = $arrdestinationCityId[0]['CityID'];
                $intdestinationCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
                $intDestinaionCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
            } else {
                $intdestinationCityId = "";
                $intdestinationCountryCode = "";
            }

            if ($intCountryCode == $intdestinationCountryCode) {
                $intCountryCode = 'IN';
            } else {
                $intCountryCode = 'INT';
            }

            if ($intOriginCountryCode != "IN" || empty($intOriginCountryCode)) {
                $sessionFlightSearchParams->params['interNationalSearch'] = true;
            } else if ($intdestinationCountryCode != "IN" || empty($intdestinationCountryCode)) {
                $sessionFlightSearchParams->params['interNationalSearch'] = true;
            } else {
                $sessionFlightSearchParams->params['interNationalSearch'] = false;
            }
            if ($getData['route'] == 3) {
                $source_city = $getData['source_city']; // or DEL,BLR etc.
                $destination_city = $getData['destination_city']; // or DEL,BLR etc.
                $intSourceCityId = [];
                $intCountryCode_ = [];
                $intdestinationCityId = [];
                $interNationalSearchArray = [];
                if ($source_city) {
                    foreach ($source_city as $key => $filterByFroms) {
                        $filterByTo = $destination_city[$key];
                        $arrSourceCityId_ = array_filter($Destinationjson, function ($var) use ($filterByFroms) {
                            return ($var['AirportCode'] == $filterByFroms);
                        });
                        $arrdestinationCityId_ = array_filter($Destinationjson, function ($var) use ($filterByTo) {
                            return ($var['AirportCode'] == $filterByTo);
                        });
                        $arrSourceCityId = array_values($arrSourceCityId_);
                        $arrdestinationCityId = array_values($arrdestinationCityId_);
                        if (count($arrSourceCityId) > 0) {
                            $intSourceCityId[] = $arrSourceCityId[0]['CityID'];
                            $intCountryCode = trim($arrSourceCityId[0]['CountryCode']);
                            $intOriginCountryCode = trim($arrSourceCityId[0]['CountryCode']);
                        } else {
                            $intSourceCityId[] = "";
                            $intCountryCode = "";
                            $intOriginCountryCode = "";
                        }
                        if (count($arrdestinationCityId) > 0) {
                            $intdestinationCityId[] = $arrdestinationCityId[0]['CityID'];
                            $intdestinationCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
                            $intDestinaionCountryCode = trim($arrdestinationCityId[0]['CountryCode']);
                        } else {
                            $intdestinationCityId[] = "";
                            $intdestinationCountryCode = "";
                        }
                        if ($intCountryCode == $intdestinationCountryCode) {
                            $intCountryCode_[] = 'IN';
                        } else {
                            $intCountryCode_[] = 'INT';
                        }
                        if ($intOriginCountryCode != "IN" || empty($intOriginCountryCode)) {
                            $interNationalSearchArray[] = $sessionFlightSearchParams->params['interNationalSearch'] = true;
                        } else if ($intdestinationCountryCode != "IN" || empty($intdestinationCountryCode)) {
                            $interNationalSearchArray[] = $sessionFlightSearchParams->params['interNationalSearch'] = true;
                        } else {
                            $interNationalSearchArray[] = $sessionFlightSearchParams->params['interNationalSearch'] = false;
                        }
                    }
                }
                if (in_array(1, $interNationalSearchArray)) {
                    $sessionFlightSearchParams->params['interNationalSearch'] = true;
                }
            }

            $sessionFlightSearchParams->params['sourceCityAirportCode'] = $getData['source_city'];
            $sessionFlightSearchParams->params['destinationCityAirportCode'] = $getData['destination_city'];

            $sessionFlightSearchParams->params['from'] = $getData['source_city'];
            $sessionFlightSearchParams->params['to'] = $getData['destination_city'];

            $sessionFlightSearchParams->params['sourceCityText'] = $getData['source'];
            $sessionFlightSearchParams->params['destinationCityText'] = $getData['destination'];

            $sessionFlightSearchParams->params['sourceCityId'] = $intSourceCityId;
            $sessionFlightSearchParams->params['destinationCityId'] = $intdestinationCityId;
            $sessionFlightSearchParams->params['intCountryCode'] = $intCountryCode;
            $sessionFlightSearchParams->params['route'] = ($getData['flight_type'] == 2) ? $getData['flight_type'] : $getData['route'];
            $sessionFlightSearchParams->params['flight_class'] = $getData['class'];

            $sessionFlightSearchParams->params['adults'] = $getData['adults'];
            $sessionFlightSearchParams->params['child'] = $getData['childs'];
            $sessionFlightSearchParams->params['infant'] = $getData['infants'];
            $sessionFlightSearchParams->params['departure_dates'] = $getData['departure_date'];
            $sessionFlightSearchParams->params['return_dates'] = !empty($getData['return_date']) ? $getData['return_date'] : '';

            $sessionFlightSearchParams->params['ContSysId_1'] = $getData['ContSysId_1'];
            $sessionFlightSearchParams->params['ContSysId'] = $getData['ContSysId'];
            $sessionFlightSearchParams->params['strDepatureDate'] = $strDepatureDate;
            $sessionFlightSearchParams->params['strReturnDate'] = $strReturnDate;
            $sessionFlightSearchParams->params['SearchFlightTraceId'] = $TraceId;
            $sessionFlightSearchParams->params['PreferredAirline'] = $PreferredAirline;
            $source_cityC = $sessionFlightSearchParams->params['source_city'];
            $destination_cityC = $sessionFlightSearchParams->params['destination_city'];
            $strDepatureDate = $sessionFlightSearchParams->params['strDepatureDate'];
            $departure_dates = $sessionFlightSearchParams->params['departure_dates'];
            $strReturnDate = $sessionFlightSearchParams->params['strReturnDate'];
            $return_dates = $sessionFlightSearchParams->params['return_dates'];

            if ($getData['route'] == 1) {
                $sessionFlightSearchParams->params['from_city_'] = '1__' . $source_cityC . '-' . $destination_cityC;
            } elseif ($getData['route'] == 2) {
                $sessionFlightSearchParams->params['from_city_'] = '2__' . $source_cityC . '-' . $destination_cityC . '-' . $source_cityC;
            }

            $NewArray = false;
            if (!empty($recentSearch->params)) {
                foreach ($recentSearch->params as $k => $val) {
                    $source_city = $val['source_city'];
                    $destination_city = $val['destination_city'];
                    if ($source_cityC == $source_city && $destination_cityC == $destination_city) {
                        $NewArray = false;
                        $recentSearch->params[$k] = $val;
                        $recentSearch->params[$k]['departure_dates'] = $departure_dates;
                        $recentSearch->params[$k]['return_dates'] = $return_dates;
                        $recentSearch->params[$k]['strDepatureDate'] = $strDepatureDate;
                        $recentSearch->params[$k]['strReturnDate'] = $strReturnDate;
                        $recentSearch->params[$k]['searchUrl'] = $uriExp[1];
                    } else {
                        $NewArray = true;
                        $recentSearch->params[$k] = $val;
                        $recentSearch->params[$k]['searchUrl'] = $uriExp[1];
                    }
                    //                    
                }
            } else {
                $recentSearch->params[0] = $sessionFlightSearchParams->params;
                $recentSearch->params[0]['searchUrl'] = $uriExp[1];
            }
            if ($NewArray) {
                $recentSearch->params[] = $sessionFlightSearchParams->params;
                $recentSearch->params[]['searchUrl'] = $uriExp[1];
            }

            return true;
        } else {
            die('Oops something went wrong');
        }
    }

    public function authenticateAPI($AgencySysid)
    {

        try {
            $objFlight = new Travel_Model_FlightMaster();
            $CheckFlightToken = $objFlight->CheckFlightToken('tbl_token', $AgencySysid);

            if (empty($CheckFlightToken)) {
                $data = array(
                    'ClientId' => FLIGHT_API_CLIENT_ID,
                    'UserName' => FLIGHT_API_USER,
                    'Password' => FLIGHT_API_PASSWORD,
                    'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                );

                $data_string = json_encode($data);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, TBO_AUTHENTICATE_URL);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                //  curl_setopt($ch, CURLOPT_HEADER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string),
                ));
                $output = curl_exec($ch);

                $response = json_decode($output, true);
                // if ($AgencySysid == '5905') {
                //     echo '<pre>';
                //     print_r($output);
                //     echo '<pre>';
                //     print_r($data_string);
                //     die;
                // }
                //Write Request Logs starts...
                $strFilePath = "flight/Auth/" . date('Y-m-d-H-i-s') . "_Auth_request.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_string);
                $strFilePath = "flight/Auth/" . date('Y-m-d-H-i-s') . "_Auth_response.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $output);


                if (FLIGHT_API_LOGS) {

                    $ResponseStatus = $response['Status'];
                    $ErrorMessage = isset($response['Error']['ErrorMessage']) ? $response['Error']['ErrorMessage'] : '';

                    $logParams = [
                        "user_id"      => 1,
                        "AgencySysId"      => $this->gtxagencysysid,
                        "custom_error" => ($ResponseStatus == 1) ? "TBO Auth Success" : "TBO Auth Failed",
                        'error'        => $ErrorMessage,
                        "text_udf"     => ['response' => $response], // Response
                        "char_udf"     => ['request' => $data], // Request
                        "udf1"         => 'AUTHENTICATE',
                        "status"       => ($ResponseStatus == 1) ? 2 : 1,
                    ];
                    Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
                }

                $tokenId = $response['TokenId'];
                $AgencyId = $response['Member']['AgencyId'];
                $MemberId = $response['Member']['MemberId'];
                curl_close($ch);

                $insertArr = array(
                    'token' => $tokenId,
                    'AgencySysid' => $AgencySysid,
                    'AgencyId' => $AgencyId,
                    'MemberId' => $MemberId,
                    'authresponse' => $output,
                    'created_at' => Zend_Date::now()->toString('YYYY-MM-dd HH:mm:ss'),
                );
                $objFlight->InsertFlightData('tbl_token', $insertArr);

                return $insertArr;
            } else {
                $insertArr = array(
                    'token' => $CheckFlightToken['token'],
                    'AgencyId' => $CheckFlightToken['AgencyId'],
                    'MemberId' => $CheckFlightToken['MemberId'],
                );
                return $insertArr;
            }
        } catch (Zend_Exception $e) {
            //print_r($e->getMessage());
        }
    }
    public function multiRequest($data, $options = array())
    {
        ini_set('max_execution_time', '0');
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        $SearchFlightTraceId = $sessionFlightSearchParams->params['SearchFlightTraceId'];
        $interNationalSearch = isset($sessionFlightSearchParams->params['interNationalSearch']) ? trim($sessionFlightSearchParams->params['interNationalSearch']) : 0;
        $strFlightRoute = trim($sessionFlightSearchParams->params['route']);
        // echo"<pre>";print_r($sessionFlightSearchParams->params);die();
        // array of curl handles
        $curly = array();
        // data to be returned
        $result = array();
        // multi handle
        $mh = curl_multi_init();
        // loop through $data and create curl handles
        // then add them to the multi-handle
        foreach ($data as $id => $d) {
            if ($this->IsTJFlightAPI == 1 && $id == 'TPJ') {
                $curly[$id] = curl_init();

                $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
                curl_setopt($curly[$id], CURLOPT_URL, $url);
                curl_setopt($curly[$id], CURLOPT_ENCODING, "gzip");
                curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
                //curl_setopt($curly[$id], CURLOPT_HEADER, 0);
                curl_setopt($curly[$id], CURLOPT_SSL_VERIFYPEER, false);
                // post?
                if (is_array($d)) {
                    if (!empty($d['post'])) {
                        $data_stringh = json_encode($d['post']);
                        curl_setopt($curly[$id], CURLOPT_POST, true);
                        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $data_stringh);
                        //curl_setopt($curly[$id], CURLOPT_CONNECTTIMEOUT, 10);
                        //curl_setopt($curly[$id], CURLOPT_TIMEOUT, 25); //timeout in seconds
                        if (isset($d['apikey']) && !empty($d['apikey'])) {
                            curl_setopt($curly[$id], CURLOPT_HTTPHEADER, array(
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'Accept-Encoding: gzip',
                                'apikey:' . $d['apikey'],
                                'Content-Length: ' . strlen($data_stringh)
                            ));
                        } else {
                            curl_setopt($curly[$id], CURLOPT_HTTPHEADER, array(
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'Accept-Encoding: gzip',
                                'Content-Length: ' . strlen($data_stringh)
                            ));
                        }
                    }
                }

                if (!empty($options)) {
                    curl_setopt_array($curly[$id], $options);
                }

                curl_multi_add_handle($mh, $curly[$id]);
            } elseif ($this->IsTBOFlightAPI == 1 && $id == 'TBO') {
                $curly[$id] = curl_init();

                $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
                curl_setopt($curly[$id], CURLOPT_URL, $url);
                curl_setopt($curly[$id], CURLOPT_ENCODING, "gzip");
                curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
                //curl_setopt($curly[$id], CURLOPT_HEADER, 0);
                curl_setopt($curly[$id], CURLOPT_SSL_VERIFYPEER, false);
                // post?
                if (is_array($d)) {
                    if (!empty($d['post'])) {
                        $data_stringh = json_encode($d['post']);
                        curl_setopt($curly[$id], CURLOPT_POST, true);
                        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $data_stringh);
                        //curl_setopt($curly[$id], CURLOPT_CONNECTTIMEOUT, 10);
                        //curl_setopt($curly[$id], CURLOPT_TIMEOUT, 25); //timeout in seconds
                        if (isset($d['apikey']) && !empty($d['apikey'])) {
                            curl_setopt($curly[$id], CURLOPT_HTTPHEADER, array(
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'Accept-Encoding: gzip',
                                'apikey:' . $d['apikey'],
                                'Content-Length: ' . strlen($data_stringh)
                            ));
                        } else {
                            curl_setopt($curly[$id], CURLOPT_HTTPHEADER, array(
                                'Accept: application/json',
                                'Content-Type: application/json',
                                'Accept-Encoding: gzip',
                                'Content-Length: ' . strlen($data_stringh)
                            ));
                        }
                    }
                }

                if (!empty($options)) {
                    curl_setopt_array($curly[$id], $options);
                }

                curl_multi_add_handle($mh, $curly[$id]);
            }
        }

        // execute the handles
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);


        // get content and remove handles
        foreach ($curly as $id => $c) {
            $result[$id] = curl_multi_getcontent($c);
            curl_multi_remove_handle($mh, $c);
        }

        // all done
        curl_multi_close($mh);
        // if($this->gtxagencysysid == '4932'){
        //     echo"<pre>";print_r($result);die();
        // }
        $arrFlightSearchResponse = [];
        $arrFlightSearchResponseTBO = [];
        $TPJRes = (isset($result['TPJ']) && !empty($result['TPJ'])) ? json_decode($result['TPJ'], true) : [];
        $TBORes = (isset($result['TBO']) && !empty($result['TBO'])) ? json_decode($result['TBO'], true) : [];
        // echo"<pre>";print_r($TPJRes['searchResult']['tripInfos']['ONWARD']['0']['sI']['0']);die();
        if (!empty($TPJRes) && $this->IsTJFlightAPI == 1) {
            $response = $TPJRes;
            $ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : 0;
            $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

            $logParams = [
                "user_id"                  => 1,
                "AgencySysId"              => $this->gtxagencysysid,
                "custom_error"             => ($ResponseStatus == 1) ? "Search Flight Success" : "Search Flight Failed",
                'error'                    => $ErrorMessage,
                "text_udf"                 => ['response' => $response], // Response
                "char_udf"                 => ['request' => $data['TPJ']], // Request
                "udf1"                     => $SearchFlightTraceId,
                "udf5"                     => 'search',
                "from_destination"         => ($strFlightRoute == '3') ? implode(',', $sessionFlightSearchParams->params['from']) : $sessionFlightSearchParams->params['from'],
                "to_destination"           => ($strFlightRoute == '3') ? implode(',', $sessionFlightSearchParams->params['to']) : $sessionFlightSearchParams->params['to'],
                "Pax"                      => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                "source"                   => 1,
                "flight_type"              => (int)$strFlightRoute,
                "Supplier"                 => 'TRIPJACK',
                "status"                   => ($ResponseStatus == 1) ? 2 : 1,
            ];
            // echo"<pre>";print_r($logParams['Pax']);die();
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            if ($interNationalSearch && ($strFlightRoute == 2 || $strFlightRoute == 3)) {
                $searchResult = $response['searchResult'];
                $COMBO = $searchResult['tripInfos']['COMBO'];
                $intResponseStatus = $response['status']['success'];
                $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
                $arrFlightSearchResponse['ErrorCode'] = '';
                $arrFlightSearchResponse['ErrorMessage'] = '';
                $arrFlightSearchResponse['OutBoundFlightResults'] = isset($COMBO) ? $COMBO : array();
                $arrFlightSearchResponse['InBoundFlightResults'] = array();
            } elseif ($strFlightRoute == 3) {
                $searchResult = $response['searchResult'];
                $ONWARD = $searchResult['tripInfos'];
                $intResponseStatus = $response['status']['success'];
                $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
                $arrFlightSearchResponse['TraceId'] = '';
                $arrFlightSearchResponse['ErrorCode'] = '';
                $arrFlightSearchResponse['ErrorMessage'] = '';
                $arrFlightSearchResponse['OutBoundFlightResults'] = isset($ONWARD) ? $ONWARD : array();
                $arrFlightSearchResponse['InBoundFlightResults'] =  array();
            } else {
                $searchResult = $response['searchResult'];
                $ONWARD = $searchResult['tripInfos']['ONWARD'];
                $RETURN = isset($searchResult['tripInfos']['RETURN']) ? $searchResult['tripInfos']['RETURN'] : [];
                $intResponseStatus = $response['status']['success'];
                $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
                $arrFlightSearchResponse['TraceId'] = '';
                $arrFlightSearchResponse['ErrorCode'] = '';
                $arrFlightSearchResponse['ErrorMessage'] = '';
                $arrFlightSearchResponse['OutBoundFlightResults'] = isset($ONWARD) ? $ONWARD : array();
                $arrFlightSearchResponse['InBoundFlightResults'] = isset($RETURN) ? $RETURN : array();
            }
        }
        if (!empty($TBORes) && $this->IsTBOFlightAPI == 1) {
            $response = $TBORes;
            $ResponseStatus = $response['Response']['ResponseStatus'];
            $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"                  => 1,
                "AgencySysId"              => $this->gtxagencysysid,
                "custom_error"             => ($ResponseStatus == 1) ? "Search Flight Success" : "Search Flight Failed",
                'error'                    => $ErrorMessage,
                "text_udf"                 => ['response' => $response], // Response
                "char_udf"                 => ['request' => $data['TBO']], // Request
                "udf1"                     => $SearchFlightTraceId,
                "udf5"                     => 'search',
                "from_destination"         => $sessionFlightSearchParams->params['from'][0],
                "to_destination"           => $sessionFlightSearchParams->params['to'][0],
                "Pax"                      => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                "source"                   => 1,
                "flight_type"              => (int)$strFlightRoute,
                "Supplier"                 => 'TBO',
                "status"                   => ($ResponseStatus == 1) ? 2 : 1,
            ];
            $logResult = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            // echo "logResult<pre>";print_r($logResult);die;
            if ($strFlightRoute == 1) {
                $arrFlightSearchResponseTBO['ResponseStatus'] = $response['Response']['ResponseStatus'];
                $arrFlightSearchResponseTBO['TraceId'] = $response['Response']['TraceId'];
                $arrFlightSearchResponseTBO['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
                $arrFlightSearchResponseTBO['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
                $arrFlightSearchResponseTBO['OutBoundFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
                $arrFlightSearchResponseTBO['InBoundFlightResults'] = [];
            } else {
                if ($interNationalSearch) {
                    $arrFlightSearchResponseTBO['ResponseStatus'] = $response['Response']['ResponseStatus'];
                    $arrFlightSearchResponseTBO['TraceId'] = $response['Response']['TraceId'];
                    $arrFlightSearchResponseTBO['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
                    $arrFlightSearchResponseTBO['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
                    $arrFlightSearchResponseTBO['InterNationalFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
                } else {
                    $arrFlightSearchResponseTBO['ResponseStatus'] = $response['Response']['ResponseStatus'];
                    $arrFlightSearchResponseTBO['TraceId'] = $response['Response']['TraceId'];
                    $arrFlightSearchResponseTBO['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
                    $arrFlightSearchResponseTBO['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
                    $arrFlightSearchResponseTBO['OutBoundFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
                    $arrFlightSearchResponseTBO['InBoundFlightResults'] = isset($response['Response']['Results'][1]) ? $response['Response']['Results'][1] : array();
                }
            }
        }
        Zend_Session::namespaceUnset('FlightSearchResults');
        $FlightSearchResults = new Zend_Session_Namespace('FlightSearchResults');
        $FlightSearchResults->params = ['TPJ' => $arrFlightSearchResponse, 'TBO' => $arrFlightSearchResponseTBO];
        return ['TPJ' => $arrFlightSearchResponse, 'TBO' => $arrFlightSearchResponseTBO];
    }

    public function searchApiFlights($arrSessionData = array())
    {

        $arrFlightClass = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getFlightClassesTripJack();
        $cabinClass = $arrFlightClass[$arrSessionData['flight_class']];
        $FlightTraceId = $arrSessionData['SearchFlightTraceId'];
        $interNationalSearch = isset($arrSessionData['interNationalSearch']) ? trim($arrSessionData['interNationalSearch']) : 0;
        $FareTypes = isset($arrSessionData['FareTypes']) ? trim($arrSessionData['FareTypes']) : 'REGULAR';
        // echo'<pre>';print_r($arrSessionData);die;
        $arrFlightSearchResponse = array();
        $strFlightRoute = trim($arrSessionData['route']);
        $fromCityOrAirport = ($strFlightRoute == '3') ? implode(',', $arrSessionData['from']) : $arrSessionData['from'];
        $PreferredAirline = $arrSessionData['PreferredAirline'];
        $toCityOrAirport = ($strFlightRoute == '3') ? implode(',', $arrSessionData['to']) : $arrSessionData['to'];
        $strDepatureDate = $arrSessionData['strDepatureDate'];
        $strReturnDate = $arrSessionData['strReturnDate'];
        $adultCount = $arrSessionData['adults'];
        $childCount = $arrSessionData['child'];
        $infantCount = $arrSessionData['infant'];
        $intMemberCount = $adultCount + $childCount + $infantCount;

        if (isset($arrSessionData['DirectFlight']) && $arrSessionData['DirectFlight'] == 1) {
            $DirectFlight = true;
        } else {
            $DirectFlight = false;
        }
        if (isset($arrSessionData['isConnectingFlight']) && $arrSessionData['isConnectingFlight'] == 1) {
            $isConnectingFlight = true;
        } else {
            $isConnectingFlight = false;
        }
        // 
        $routeInfo = [];
        if ($strFlightRoute == 3) {
            if ($arrSessionData['sourceCityAirportCode']) {
                foreach ($arrSessionData['sourceCityAirportCode'] as $key => $value) {
                    $origin = $arrSessionData['sourceCityAirportCode'][$key];
                    $destination = $arrSessionData['destinationCityAirportCode'][$key];
                    $preferredDepartureTime = date('Y-m-d', strtotime($arrSessionData['departure_date'][$key]));
                    $routeInfo[$key] = array(
                        'fromCityOrAirport' => array('code' => $origin),
                        'toCityOrAirport' => array('code' => $destination),
                        'travelDate' => $preferredDepartureTime,
                    );
                }
            }
        } else {
            if ($strFlightRoute) {
                for ($i = 0; $i < $strFlightRoute; $i++) {
                    if ($i == 0) {
                        $fromCity = $fromCityOrAirport;
                        $toCity = $toCityOrAirport;
                        $travelDate = $strDepatureDate;
                    } else {
                        $fromCity = $toCityOrAirport;
                        $toCity = $fromCityOrAirport;
                        $travelDate = $strReturnDate;
                    }
                    $routeInfo[] = array(
                        'fromCityOrAirport' => array('code' => $fromCity),
                        'toCityOrAirport' => array('code' => $toCity),
                        'travelDate' => $travelDate,
                    );
                }
            }
        }

        if ($strFlightRoute == 1 && $interNationalSearch == '') {
            $SearchType = 'Oneway';
        } elseif ($strFlightRoute == 2 && $interNationalSearch == '') {
            $SearchType = 'DomReturn';
        } elseif ($strFlightRoute == 1 && $interNationalSearch == 1) {
            $SearchType = 'IntOneway';
        } elseif ($strFlightRoute == 2 && $interNationalSearch == 1) {
            $SearchType = 'IntReturn';
        }

        $data = array(
            'searchQuery' => array(
                'cabinClass' => ($cabinClass == 'All') ? 'ECONOMY' : str_replace(' ', '_', strtoupper($cabinClass)),
                'paxInfo' =>  array(
                    'ADULT' => $adultCount,
                    'CHILD' => $childCount,
                    'INFANT' => $infantCount,
                ),
                'routeInfos' => $routeInfo,
                'searchModifiers' => array('isDirectFlight' => $DirectFlight, 'isConnectingFlight' => $isConnectingFlight, 'pft' => $FareTypes),
            ),
        );
        if (!empty($PreferredAirline)) {
            $AirlineArr = [];
            foreach ($PreferredAirline as $code) {
                $AirlineArr[] = array(
                    'code' => $code
                );
            }
            $data['searchQuery']['preferredAirline'] = $AirlineArr;
        }
        //echo"<pre>";print_r($data);die();
        $logFile = $SearchType . '_' . $fromCityOrAirport . '_' . $toCityOrAirport . '_' . $adultCount . 'A_' . $childCount . 'C_' . $infantCount . 'I_isDirect_' . $DirectFlight . '_isConnecting_' . $isConnectingFlight;
        $request = [];
        $request['TPJ']['post'] = $data;
        $request['TPJ']['url'] = TRIPJACK_FL_SEARCHALL_URL;
        $request['TPJ']['apikey'] = APIKEY;
        return $request;
        $data_stringh = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_SEARCHALL_URL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Accept-Encoding: gzip',
            'apikey:' . APIKEY,
            'Content-Length: ' . strlen($data_stringh)
        ));

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

        if (FLIGHT_API_LOGS) {

            $strFilePath = "flight/FlightSearch/" . date('Y-m-d-H-i-s') . "_request.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);

            $strFilePath = "flight/FlightSearch/" . date('Y-m-d-H-i-s') . "_response.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);

            $ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : 0;
            $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

            $logParams = [
                "user_id"                   => 1,
                "AgencySysId"               => $this->gtxagencysysid,
                "custom_error"              => ($ResponseStatus == 1) ? "Search Flight Success" : "Search Flight Failed",
                'error'                     => $ErrorMessage,
                "text_udf"                  => ['response' => ''], // Response
                "char_udf"                  => ['request' => $data], // Request
                "udf1"                      => $FlightTraceId,
                "udf5"                      => 'search',
                "from_destination"          => $fromCityOrAirport,
                "to_destination"            =>  $arrSessionData['to'],
                "source"                    => 1,
                "pax"                       => $intMemberCount,
                "status"                    => ($ResponseStatus == 1) ? 2 : 1,
            ];
            // echo"<pre>";print_r($logParams);die();
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }


        if ($interNationalSearch && ($strFlightRoute == 2 || $strFlightRoute == 3)) {
            $searchResult = $response['searchResult'];
            $COMBO = $searchResult['tripInfos']['COMBO'];
            $intResponseStatus = $response['status']['success'];
            $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
            $arrFlightSearchResponse['ErrorCode'] = '';
            $arrFlightSearchResponse['ErrorMessage'] = '';
            $arrFlightSearchResponse['OutBoundFlightResults'] = isset($COMBO) ? $COMBO : array();
            $arrFlightSearchResponse['InBoundFlightResults'] = array();
        } elseif ($strFlightRoute == 3) {
            $searchResult = $response['searchResult'];
            $ONWARD = $searchResult['tripInfos'];
            $intResponseStatus = $response['status']['success'];
            $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
            $arrFlightSearchResponse['TraceId'] = '';
            $arrFlightSearchResponse['ErrorCode'] = '';
            $arrFlightSearchResponse['ErrorMessage'] = '';
            $arrFlightSearchResponse['OutBoundFlightResults'] = isset($ONWARD) ? $ONWARD : array();
            $arrFlightSearchResponse['InBoundFlightResults'] =  array();
        } else {
            $searchResult = $response['searchResult'];
            $ONWARD = $searchResult['tripInfos']['ONWARD'];
            $RETURN = isset($searchResult['tripInfos']['RETURN']) ? $searchResult['tripInfos']['RETURN'] : [];
            $intResponseStatus = $response['status']['success'];
            $arrFlightSearchResponse['ResponseStatus'] = $intResponseStatus;
            $arrFlightSearchResponse['TraceId'] = '';
            $arrFlightSearchResponse['ErrorCode'] = '';
            $arrFlightSearchResponse['ErrorMessage'] = '';
            $arrFlightSearchResponse['OutBoundFlightResults'] = isset($ONWARD) ? $ONWARD : array();
            $arrFlightSearchResponse['InBoundFlightResults'] = isset($RETURN) ? $RETURN : array();
        }
        Zend_Session::namespaceUnset('FlightSearchResults');
        $FlightSearchResults = new Zend_Session_Namespace('FlightSearchResults');
        $FlightSearchResults->params = $arrFlightSearchResponse;  // store all serch result data to Session

        Zend_Session::namespaceUnset('FlightSearchLogFile');
        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $FlightSearchLogFile->params = $logFile;  // store serch data to Session
        return $arrFlightSearchResponse;
    }

    public function searchApiFlightsTBO($arrSessionData = array())
    {

        // echo"<pre>";print_r($arrSessionData);

        $strFlightRoute = trim($arrSessionData['route']);
        $FlightTraceId = $arrSessionData['SearchFlightTraceId'];
        $strSourceAirportCode = $arrSessionData['from'];
        $strDestinationAirportCode = $arrSessionData['to'];
        $strDepatureDate = $arrSessionData['departure_dates'];
        $adultCount = $arrSessionData['adults'];
        $childCount = $arrSessionData['child'];
        $infantCount = $arrSessionData['infant'];
        $intMemberCount = $adultCount + $childCount + $infantCount;
        if (isset($arrSessionData['DirectFlight']) && $arrSessionData['DirectFlight'] == 1) {
            $DirectFlight = true;
        } else {
            $DirectFlight = false;
        }
        $origin = $arrSessionData['sourceCityAirportCode'];
        $destination = $arrSessionData['destinationCityAirportCode'];
        $preferredDepartureTime = $arrSessionData['departure_dates'];
        $preferredArrivalTime = $arrSessionData['departure_dates'];
        $intSourceCityId = trim($arrSessionData['sourceCityId']);
        $intDestinationCityId = trim($arrSessionData['destinationCityId']);
        $interNationalSearch = isset($arrSessionData['interNationalSearch']) ? trim($arrSessionData['interNationalSearch']) : 0;

        $preferredDepartureTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredDepartureTime, 'd/m/y') . "T00:00:00";
        $preferredArrivalTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredArrivalTime, 'd/m/y') . "T00:00:00";

        $strReturnOrigin = $arrSessionData['destinationCityAirportCode'];
        $strReturnDestination = $arrSessionData['sourceCityAirportCode'];
        $preferredReturnDepartureTime = $arrSessionData['return_dates'];
        $preferredReturnArrivalTime = $arrSessionData['return_dates'];
        $preferredReturnDepartureTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredReturnDepartureTime, 'd/m/y') . "T00:00:00";
        $preferredReturnArrivalTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredReturnArrivalTime, 'd/m/y') . "T00:00:00";

        $preferredFlightClassType = $arrSessionData['flight_class'];


        $tokenId = $this->authenticateAPI($this->gtxagencysysid);

        if ($strFlightRoute == 1 && $interNationalSearch == '') {
            $SearchType = 'Oneway';
        } elseif ($strFlightRoute == 2 && $interNationalSearch == '') {
            $SearchType = 'DomReturn';
        } elseif ($strFlightRoute == 1 && $interNationalSearch == 1) {
            $SearchType = 'IntOneway';
        } elseif ($strFlightRoute == 2 && $interNationalSearch == 1) {
            $SearchType = 'IntReturn';
        }
        $logFile = $SearchType . '_' . $origin . '_' . $destination . '_' . $adultCount . 'A_' . $childCount . 'C_' . $infantCount . 'I_isDirect_' . $DirectFlight;
        $arrFlightSearchResponse = array();
        if ($strFlightRoute == '1') {
            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'interNationalSearch' => $interNationalSearch,
                'TokenId' => $tokenId['token'],
                "AdultCount" => $adultCount,
                "ChildCount" => $childCount,
                "InfantCount" => $infantCount,
                "DirectFlight" => $DirectFlight,
                "OneStopFlight" => "false",
                "JourneyType" => "1",
                "PreferredAirlines" => NULL, //["AI","9W","SG"]
                "Segments" => [array(
                    'Origin' => $origin, 'Destination' => $destination, 'FlightCabinClass' => $preferredFlightClassType, "PreferredDepartureTime" => $preferredDepartureTime,
                    'PreferredArrivalTime' => $preferredArrivalTime
                )],
                "Sources" => NULL
            );
        } elseif ($strFlightRoute == '2') {

            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'interNationalSearch' => $interNationalSearch,
                'TokenId' => $tokenId['token'],
                "AdultCount" => $adultCount,
                "ChildCount" => $childCount,
                "InfantCount" => $infantCount,
                "DirectFlight" => $DirectFlight,
                "OneStopFlight" => "false",
                "JourneyType" => "2",
                "ReturnDate" => $preferredReturnDepartureTime,
                "PreferredAirlines" => NULL,
                "Segments" => array(
                    "0" => array(
                        'Origin' => $origin,
                        'Destination' => $destination,
                        'FlightCabinClass' => $preferredFlightClassType,
                        "PreferredDepartureTime" => $preferredDepartureTime,
                        'PreferredArrivalTime' => $preferredArrivalTime
                    ),
                    "1" => array(
                        'Origin' => $strReturnOrigin,
                        'Destination' => $strReturnDestination,
                        'FlightCabinClass' => $preferredFlightClassType,
                        'PreferredDepartureTime' => $preferredReturnDepartureTime,
                        'PreferredArrivalTime' => $preferredReturnArrivalTime
                    )
                ),
                "Sources" => NULL
            );
        } else {
            $preferredFlightClassType = $arrSessionData['flight_class'];
            $Segments = [];
            if ($arrSessionData['sourceCityAirportCode']) {
                foreach ($arrSessionData['sourceCityAirportCode'] as $key => $value) {
                    $origin = $arrSessionData['sourceCityAirportCode'][$key];
                    $destination = $arrSessionData['destinationCityAirportCode'][$key];
                    $preferredDepartureTime = $arrSessionData['departure_date'][$key];
                    $preferredDepartureTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredDepartureTime, 'y/m/d') . "T00:00:00";
                    $preferredArrivalTime = $arrSessionData['departure_date'][$key];
                    $preferredArrivalTime = Zend_Controller_Action_HelperBroker::getStaticHelper('DateFormat')->cal2Db($preferredArrivalTime, 'y/m/d') . "T00:00:00";
                    $Segments[$key] = array(
                        'Origin' => $origin,
                        'Destination' => $destination,
                        'FlightCabinClass' => $preferredFlightClassType,
                        "PreferredDepartureTime" => date('Y-m-d', strtotime($preferredDepartureTime)) . "T00:00:00",
                        'PreferredArrivalTime' => date('Y-m-d', strtotime($preferredArrivalTime)) . "T00:00:00",
                    );
                }
            }
            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'interNationalSearch' => $interNationalSearch,
                'TokenId' => $tokenId['token'],
                "AdultCount" => $adultCount,
                "ChildCount" => $childCount,
                "InfantCount" => $infantCount,
                "DirectFlight" => $DirectFlight,
                "OneStopFlight" => "false",
                "JourneyType" => $strFlightRoute,
                "PreferredAirlines" => NULL,
                //"PreferredAirlines" => NULL, //["AI","9W","SG"]
                "Segments" => $Segments,
                "Sources" => NULL,
            );
        }
        
        $request = [];
        $request['TBO']['post'] = $datah;
        $request['TBO']['url'] = FLIGHT_API_SEARCH_URL;
        return $request;
        //echo"<pre>";print_r($datah);die;
        $data_stringh = json_encode($datah);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, FLIGHT_API_SEARCH_URL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Accept-Encoding: gzip',
            'Content-Length: ' . strlen($data_stringh)
        ));

        $outputH = curl_exec($ch);

        $response = json_decode($outputH, true);

        $ResponseStatus = $response['Response']['ResponseStatus'];
        $ErrorMessage = $response['Response']['Error']['ErrorMessage'];
        if ($ResponseStatus == 1) {
        } elseif ($ResponseStatus == 3 && $ErrorMessage == 'InValid Session') {
            $objFlight = new Travel_Model_FlightMaster();
            $objFlight->DeleteToken('tbl_token');
            $tokenId = $this->authenticateAPI($this->gtxagencysysid);
            $datah['TokenId'] = $tokenId['token'];
            $data_stringh = json_encode($datah);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_SEARCH_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            $response = json_decode($outputH, true);
        }
        if ($strFlightRoute == 1) {
            $arrFlightSearchResponse['ResponseStatus'] = $response['Response']['ResponseStatus'];
            $arrFlightSearchResponse['TraceId'] = $response['Response']['TraceId'];
            $arrFlightSearchResponse['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
            $arrFlightSearchResponse['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
            $arrFlightSearchResponse['OutBoundFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
            $arrFlightSearchResponse['InBoundFlightResults'] = [];
        } else {
            if ($interNationalSearch) {
                $arrFlightSearchResponse['ResponseStatus'] = $response['Response']['ResponseStatus'];
                $arrFlightSearchResponse['TraceId'] = $response['Response']['TraceId'];
                $arrFlightSearchResponse['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
                $arrFlightSearchResponse['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
                $arrFlightSearchResponse['InterNationalFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
            } else {
                $arrFlightSearchResponse['ResponseStatus'] = $response['Response']['ResponseStatus'];
                $arrFlightSearchResponse['TraceId'] = $response['Response']['TraceId'];
                $arrFlightSearchResponse['ErrorCode'] = $response['Response']['Error']['ErrorCode'];
                $arrFlightSearchResponse['ErrorMessage'] = $response['Response']['Error']['ErrorMessage'];
                $arrFlightSearchResponse['OutBoundFlightResults'] = isset($response['Response']['Results'][0]) ? $response['Response']['Results'][0] : array();
                $arrFlightSearchResponse['InBoundFlightResults'] = isset($response['Response']['Results'][1]) ? $response['Response']['Results'][1] : array();
            }
        }

        if (FLIGHT_API_TBO_LOGS) {

            //Write Request Logs starts...
            $strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . '_' . $logFile . "_Round_FlightSearch_request.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
            //Write Request Logs starts...
            //Write Request Logs starts...
            $strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . '_' . $logFile . "_Round_FlightSearch_response.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
            $ResponseStatus = $response['Response']['ResponseStatus'];
            $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"      => 1,
                "AgencySysId"      => $this->gtxagencysysid,
                "custom_error" => ($ResponseStatus == 1) ? "Search Flight Success" : "Search Flight Failed",
                'error'        => $ErrorMessage,
                "text_udf"     => ['response' => ''], // Response
                "char_udf"     => ['request' => $datah], // Request
                "udf1"         => $FlightTraceId,
                "status"       => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }

        Zend_Session::namespaceUnset('FlightSearchResultsTBO');
        $FlightSearchResultsTBO = new Zend_Session_Namespace('FlightSearchResultsTBO');
        $FlightSearchResultsTBO->params = $arrFlightSearchResponse;  // store all serch result data to Session

        Zend_Session::namespaceUnset('FlightSearchLogFile');
        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $FlightSearchLogFile->params = $logFile;  // store serch data to Session
        return $arrFlightSearchResponse;
    }

    public function searchApiFlightsSeriesFare($arrSessionData = array(), $tripType = '')
    {

        $FlightTraceId = $arrSessionData['SearchFlightTraceId'];
        //echo '<pre>';print_r($arrSessionData);die('T');
        $strDepatureDate = isset($arrSessionData['strDepatureDate'][0]) ? $arrSessionData['strDepatureDate'][0] : '';
        $route = isset($arrSessionData['route']) ? $arrSessionData['route'] : '';
        $flight_type = (isset($arrSessionData['flight_type']) && !empty($arrSessionData['flight_type'])) ? $arrSessionData['flight_type'] : $route;
        $interNationalSearch = isset($arrSessionData['interNationalSearch']) ? $arrSessionData['interNationalSearch'] : '';
        //echo '<pre>';print_r($arrSessionData);
        if (isset($arrSessionData['from_city_'])) {
            $from_city = isset($arrSessionData['from_city_']) ? explode('__', $arrSessionData['from_city_']) : array();
        } else {
            $from_city = isset($arrSessionData['from_city']) ? explode('__', $arrSessionData['from_city']) : array();
        }

        $from_city1 = $from_city[1];
        $SeriesFareSecotrs = isset($from_city1) ? explode('-', $from_city1) : array(0 => '', 1 => '', 2 => '');
        $FlightType = $from_city[0];
        $SECURITYKEY = SECURITYKEY;
        $SearchDate = (isset($arrSessionData['strDepatureDate']) && !empty(trim($arrSessionData['strDepatureDate']))) ? trim($arrSessionData['strDepatureDate'])  : '';
        $InwardDate = (isset($arrSessionData['strReturnDate']) && !empty(trim($arrSessionData['strReturnDate']))) ? trim($arrSessionData['strReturnDate'])  : '';
        $adults = isset($arrSessionData['adults']) ? (int)$arrSessionData['adults'] : 0;
        $childs = isset($arrSessionData['childs']) ? (int)$arrSessionData['childs'] : 0;
        $infants = isset($arrSessionData['infants']) ? (int)$arrSessionData['infants'] : 0;
        $totaltrveller = $adults + $childs + $infants;
        $CurrentSeat = !empty($totaltrveller) ? $totaltrveller : '';
        //$this->postFields .= "?SecurityKey=" . $SECURITYKEY;
        $postFields = array(
            'SecurityKey' => $SECURITYKEY,
            'FlightType' => $flight_type,
            'FromDate' => date('Y-m-d'),
            'CurrentSeat' => $CurrentSeat,
        );


        if (isset($tripType) && $tripType == 'roundtrip') {
            $postFields['OFAC'] = $SeriesFareSecotrs[1];
            $postFields['OTAC'] = $SeriesFareSecotrs[0];
            $postFields['SearchDate'] = $InwardDate;
        } else {
            $postFields['OFAC'] = $SeriesFareSecotrs[0];
            $postFields['OTAC'] = $SeriesFareSecotrs[1];
            $postFields['SearchDate'] = $SearchDate;
        }
        if ($interNationalSearch == 1 && $flight_type == 2) {
            $postFields['IFAC'] = $SeriesFareSecotrs[1];
            $postFields['ITAC'] = $SeriesFareSecotrs[0];
            $postFields['InwardDate'] = $InwardDate;
            $postFields['SearchDate'] = null;
        }

        // print_r(($arrSessionData));
        // print_r(($postFields));
        $URL = 'https://gtxapi.hellogtx.com/api/v2/index/?' . http_build_query($postFields);
        //$URL = 'http://local.hellogtx.com/api/v2/index/?' . http_build_query($postFields);

        // echo '<pre>';
        // print_r($URL);
        // echo '</pre>';die;
        //echo '<pre>';print_r($arrSessionData);
        //die;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($this->postFields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Accept-Encoding: gzip',
            'Content-Length: ' . strlen($this->postFields),
        ));

        $outputH = curl_exec($ch);
        $response = json_decode($outputH, true);
        $SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
        // if ($this->gtxagencysysid == '79137') {
        //     print_r($URL);
        //     print_r($outputH);
        // }
        if (FLIGHT_API_LOGS) {

            $ResponseStatus = $response['status']['success'];
            $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

            $logParams = [
                "user_id"                  => 1,
                "AgencySysId"              => $this->gtxagencysysid,
                "custom_error"             => ($ResponseStatus == 1) ? "Search Flight Success" : "Search Flight Failed",
                'error'                    => $ErrorMessage,
                "text_udf"                 => ['response' => ''], // Response
                "char_udf"                 => ['request' => $postFields], // Request
                "udf1"                     => $arrSessionData['SearchFlightTraceId'],
                "udf5"                     => 'search',
                "from_destination"         => $arrSessionData['from'],
                "to_destination"           => $arrSessionData['to'],
                "Pax"                      => ($arrSessionData['adults'] + $arrSessionData['childs'] + $arrSessionData['infants']),
                "source"                   => 1,
                "flight_type"              => (int) $arrSessionData['route'],
                "Supplier"                 => 'SERIESFARE',
                "status"                   => ($ResponseStatus == 1) ? 2 : 1,
            ];
            // echo"<pre>";print_r($logParams);die();
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);

            $strFilePath = "flight/FlightSearch/SeriesFare/" . date('Y-m-d-H-i-s') . "_request.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $this->postFields);

            $strFilePath = "flight/FlightSearch/SeriesFare/" . date('Y-m-d-H-i-s') . "_response.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
        }

        return $response;
    }

    public function GetApiFlightsFareRulesTripJack($arrData = array())
    {

        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        //echo"<pre>";print_r($arrData);die();
        //echo"<pre>";print_r($sessionFlightSearchParams);die(); 
        if ($arrData) {
            $FlightTraceId = $arrData['SearchFlightTraceId'];
            $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
            $logFile = $FlightSearchLogFile->params;
            $datah = array(
                'id' => $arrData['TraceId'],
                'flowType' => $arrData['flowType'],
            );

            $data_stringh = json_encode($datah);
            // echo"<pre>";print_r($datah);die();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, str_replace('v1', 'v2', TRIPJACK_FL_API_FARE_RULE_URL));
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            $response = json_decode($outputH, true);
            // echo"<pre>";print_r($response);die();
            if (FLIGHT_API_LOGS) {

                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareRules/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_FareRules_request.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
                //Write Request Logs starts...
                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareRules/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_FareRules_response.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
                //Write Request Logs starts...

                $ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : 0;
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"          => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error"     => ($ResponseStatus == 1) ? "Flight Fare Rule Success" : "Flight Fare Rule Failed",
                    'error'            => $ErrorMessage,
                    "text_udf"         => ['response' => $response], // Response
                    "char_udf"         => ['request' => $datah], // Request
                    "udf1"             => $FlightTraceId,
                    "udf5"             => 'farerule',
                    "from_destination" => $sessionFlightSearchParams->params['from'],
                    "to_destination"   => $sessionFlightSearchParams->params['to'],
                    "flight_type"      => $sessionFlightSearchParams->params['route'],
                    "source"           => 1,
                    "Pax"              => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => $arrData['FlightBookingData']['AirlineName'],
                    "status"           => ($ResponseStatus == 1) ? 2 : 1,
                ];
                //echo"<pre>";print_r($logParams);die();
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
            Zend_Session::namespaceUnset('FlightFareRulesSession');
            $FlightFareRulesSession = new Zend_Session_Namespace('FlightFareRulesSession');
            $FlightFareRulesSession->params = $response;  // store all serch result data to Session
            return $response;
        }
    }

    public function GetApiFlightsFareRules($arrData = array())
    {
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        $FlightTraceId = $arrData['SearchFlightTraceId'];
        // echo"<pre>";print_r($FlightTraceId);die();
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);
        if ($arrData) {
            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'TokenId' => $tokenId['token'],
                'TraceId' => $arrData['TraceId'],
                'ResultIndex' => $arrData['ApiResultIndex'],
            );
            $data_stringh = json_encode($datah);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_FARE_RULE_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'Content-Length: ' . strlen($data_stringh)
            ));

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

                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareRules/" . time() . "_FareRules_request.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
                //Write Request Logs starts...
                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareRules/" . time() . "_FareRules_response.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
                //Write Request Logs starts...

                $ResponseStatus = $response['Response']['ResponseStatus'];
                $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Fare Rule Success" : "Flight Fare Rule Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $datah], // Request
                    "udf1"         => $FlightTraceId,
                    "udf5"         => 'farerule',
                    "from_destination" => $sessionFlightSearchParams->params['from'],
                    "to_destination"   => $sessionFlightSearchParams->params['to'],
                    "flight_type"      => $sessionFlightSearchParams->params['route'],
                    "source"           => 1,
                    "Pax"              => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => $arrData['AirlineName'],
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
        }

        return $response;
    }

    public function GetApiFlightsFareQuoteTripJack($arrData = array())
    {
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        //echo"<pre>";print_r($sessionFlightSearchParams->params);die();

        // echo"<pre>";print_r($arrData['FlightBookingData']['AirlineName']);die();
        if ($arrData) {
            $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
            $logFile = isset($FlightSearchLogFile->params) ? $FlightSearchLogFile->params : '_';
            $SearchFlightTraceId = $arrData['SearchFlightTraceId'];
            $priceIdArr = explode(',', $arrData['TraceId']);
            $from_destination = $sessionFlightSearchParams->params['from'];
            $to_destination = $sessionFlightSearchParams->params['to'];
            $flight_type = $sessionFlightSearchParams->params['route'];
            $from_destination = ($flight_type == '3') ? implode(',', $sessionFlightSearchParams->params['from']) : $sessionFlightSearchParams->params['from'];
            $to_destination = ($flight_type == '3') ? implode(',', $sessionFlightSearchParams->params['to']) : $sessionFlightSearchParams->params['to'];


            $datah = array(
                'priceIds' => $priceIdArr,
            );

            $data_stringh = json_encode($datah);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_REVIEW_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            $response = json_decode($outputH, true);
            //echo "<pre>";print_r($response);exit;
            if (FLIGHT_API_LOGS) {

                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareReview/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_Review_request.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
                //Write Request Logs starts...
                //Write Request Logs starts...
                $strFilePath = "flight/FlightFareReview/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_Review_response.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
                //Write Request Logs starts...
                $ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : 0;
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';
                // $airline =   $response['tripInfos']['0']['sI']['0']['aI']['name'];
                // echo"<pre>";print_r($airline);die('dd');
                $logParams = [
                    "user_id"          => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error"     => ($ResponseStatus == 1) ? "Flight fare Quote Success" : "Flight fare Quote Failed",
                    'error'            => $ErrorMessage,
                    "text_udf"         => ['response' => $response], // Response
                    "char_udf"         => ['request' => $datah], // Request
                    "udf1"             => $SearchFlightTraceId,
                    "udf5"             => 'farequote',
                    "from_destination" => $from_destination,
                    "to_destination"   => $to_destination,
                    "flight_type"      => $flight_type,
                    "source"           => 1,
                    "Pax"              => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => $arrData['FlightBookingData']['AirlineName'],
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                // echo"<pre>";print_r($logParams);die();
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
        }
        if ($arrData['Inbound'] == 1) {
            Zend_Session::namespaceUnset('FlightFareQuoteSessionInb');
            $FlightFareQuoteSessionInb = new Zend_Session_Namespace('FlightFareQuoteSessionInb');
            $FlightFareQuoteSessionInb->params = $response;  // store all serch result data to Session
        } else {
            Zend_Session::namespaceUnset('FlightFareQuoteSession');
            $FlightFareQuoteSession = new Zend_Session_Namespace('FlightFareQuoteSession');
            $FlightFareQuoteSession->params = $response;  // store all serch result data to Session  
        }

        return $response;
    }

    public function GetApiFlightsFareQuote($arrData = array())
    {
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        //
        $FlightTraceId = $arrData['SearchFlightTraceId'];
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);
        $SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
        $SearchParam = $SearchFlightTraceId->params;
        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $logFile = $FlightSearchLogFile->params;

        $AirlineName = $arrData['BookingData']['AirlineName'];
        $TotalFlightMembers = $arrData['BookingData']['TotalFlightMembers'];
        $JourneyType = $arrData['BookingData']['JourneyType'];
        $SourceAirportCode = $arrData['BookingData']['SourceAirportCode'];
        $DestAirportCode = $arrData['BookingData']['DestAirportCode'];

        if ($arrData) {
            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'TokenId' => $tokenId['token'],
                'TraceId' => $arrData['TraceId'],
                'ResultIndex' => $arrData['ApiResultIndex'],
            );
            $data_stringh = json_encode($datah);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_FARE_QUOTE_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);

            $response = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['Response']['ResponseStatus'];
                $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Fare Quote Success" : "Flight Fare Quote Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $datah], // Request
                    "udf1"         => $FlightTraceId,
                    "udf5"         => 'farequote',
                    "from_destination"             => $SourceAirportCode,
                    "to_destination"             => $DestAirportCode,
                    "flight_type"                 => (int)$sessionFlightSearchParams->params['route'],
                    "source"                     => 1,
                    "Pax"                         => ($TotalFlightMembers),
                    "Supplier"                     => 'TBO',
                    "Airline"                     => $AirlineName,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
        }
        if ($arrData['Inbound'] == 1) {
            Zend_Session::namespaceUnset('FlightFareQuoteSessionInb');
            $FlightFareQuoteSessionInb = new Zend_Session_Namespace('FlightFareQuoteSessionInb');
            $FlightFareQuoteSessionInb->params = $response;  // store all serch result data to Session
        } else {
            Zend_Session::namespaceUnset('FlightFareQuoteSession');
            $FlightFareQuoteSession = new Zend_Session_Namespace('FlightFareQuoteSession');
            $FlightFareQuoteSession->params = $response;  // store all serch result data to Session  
        }

        return $response;
    }
    public function GetAgencyBalance($arrData = array())
    {
        $FlightTraceId = $arrData['SearchFlightTraceId'];
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        $route = (int)$sessionFlightSearchParams->params['route'];
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);
        if ($arrData) {
            $datah = array(
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'TokenId' => $tokenId['token'],
                'ClientId' => FLIGHT_API_CLIENT_ID,
                'TokenAgencyId' => $tokenId['AgencyId'],
                'TokenMemberId' => $tokenId['MemberId'],
            );
            $data_stringh = json_encode($datah);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TBO_AGENCYBALANCE_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            //print_r($outputH);die('bal');
            $response = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['Status'];
                $ErrorMessage = isset($response['Error']['ErrorMessage']) ? $response['Error']['ErrorMessage'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Get Balance Success" : "Flight Get Balance Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $datah], // Request
                    "udf1"         => $FlightTraceId,
                    "udf5"             => 'ticket',
                    "from_destination" => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['from']) : $sessionFlightSearchParams->params['from'],
                    "to_destination"   => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['to']) : $sessionFlightSearchParams->params['to'],
                    "flight_type"      => (int)$sessionFlightSearchParams->params['route'],
                    "source"           => 1,
                    "Pax"              => (int)($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => '',
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
        }
        return $response;
    }

    public function GetAgencyBalanceTJ($arrData = array(), $AgencySysid = null)
    {
        $FlightTraceId = $arrData['SearchFlightTraceId'];
        if ($arrData) {
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => TRIPJACK_USER_BALANCE_URL,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'apikey: ' . APIKEY . ''
                ),
            ));

            $outputH = curl_exec($curl);

            curl_close($curl);

            $response = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {

                $ResponseStatus = $response['status']['success'];
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      =>  $AgencySysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Agency Balance Success" : "Agency Balance Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => ''], // Request
                    "udf1"         => $FlightTraceId,
                    "udf5"         => 'Balance',
                    "from_destination"             => 'Balance',
                    "to_destination"             => 'Balance',
                    "flight_type"                 => 1,
                    "source"                     => 1,
                    "Pax"                         => 0,
                    "Supplier"                     => 'TRIPJACK',
                    "Airline"                     => '',
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                $dddd = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
                
            }
        }

        return $response;
    }
    public function flightSSRDetails($data)
    {
        //echo"<pre>";print_r($data);die();
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);
        $FlightTraceId = $data['SearchFlightTraceId'];

        $AirlineName = $data['BookingData']['AirlineName'];
        $TotalFlightMembers = $data['BookingData']['TotalFlightMembers'];
        $JourneyType = $data['BookingData']['JourneyType'];
        $SourceAirportCode = $data['BookingData']['SourceAirportCode'];
        $DestAirportCode = $data['BookingData']['DestAirportCode'];


        $datah = array(
            'EndUserIp' => $_SERVER['REMOTE_ADDR'],
            'TokenId' => $tokenId['token'],
            'TraceId' => $data['TraceId'],
            'ResultIndex' => $data['ApiResultIndex'],
        );
        $data_stringh = json_encode($datah);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, FLIGHT_API_SSR_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_stringh),
        ));

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

        if (FLIGHT_API_LOGS) {
            $ResponseStatus = $response['Response']['ResponseStatus'];
            $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"      => 1,
                "AgencySysId"      => $this->gtxagencysysid,
                "custom_error" => ($ResponseStatus == 1) ? "Flight SSR Success" : "Flight SSR Failed",
                'error'        => $ErrorMessage,
                "text_udf"     => ['response' => $response], // Response
                "char_udf"     => ['request' => $datah], // Request
                "udf1"         => $FlightTraceId,
                "udf5"         => 'ssr',
                "from_destination"             => $SourceAirportCode,
                "to_destination"             => $DestAirportCode,
                "flight_type"                 => (int)$JourneyType,
                "source"                     => 1,
                "Pax"                         => ($TotalFlightMembers),
                "Supplier"                     => 'TBO',
                "Airline"                     => $AirlineName,
                "status"       => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }
        return $response;
    }


    public function apiFlightTicketTripJack($data)
    {
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        // echo '<pre>';print_r($data['FlightBookingData']['0']['AirlineName']);die('T');
        $SelectedMealSessionNew = new Zend_Session_Namespace('SelectedMealSessionNew');
        $SelectedBaggSessionNew = new Zend_Session_Namespace('SelectedBaggSessionNew');
        // echo '<pre>';print_r($data);die;
        $SelectedMealSessionNewInb = new Zend_Session_Namespace('SelectedMealSessionNewInb');
        $SelectedBaggSessionNewInb = new Zend_Session_Namespace('SelectedBaggSessionNewInb');

        $flightSSRDetails = new Zend_Session_Namespace('flightSSRDetails');
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        $interNationalSearch = $sessionFlightSearchParams->params['interNationalSearch'];
        $route = (int)$sessionFlightSearchParams->params['route'];

        $selectedSeatSession = new Zend_Session_Namespace('selectedSeatSession');

        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $logFile = $FlightSearchLogFile->params;

        $MealSelected = $SelectedMealSessionNew->params;
        $BaggSelected = $SelectedBaggSessionNew->params;
        $arrSSR = $flightSSRDetails->params;
        $arrAgencyUserDetail = isset($data['arrAgencyUserDetail']) ? $data['arrAgencyUserDetail'] : [];
        $getAgencyData = isset($data['getAgencyData']) ? $data['getAgencyData'] : [];
        $bookingId = (isset($data['FlightBookingData'][0]['bookingId_TJ']) && !empty($data['FlightBookingData'][0]['bookingId_TJ'])) ? $data['FlightBookingData'][0]['bookingId_TJ'] : $data['FlightBookingData'][0]['bookingId'];
        $SearchFlightTraceId = $data['FlightBookingData'][0]['SearchFlightTraceId'];
        $isgstapply = (isset($data['CustomerSession'][0]['isgstapply']) && !empty($data['CustomerSession'][0]['isgstapply'])) ? $data['CustomerSession'][0]['isgstapply'] : 0;
        $EmailId_cus = (isset($data['CustomerSession'][0]['EmailId']) && !empty($data['CustomerSession'][0]['EmailId'])) ? $data['CustomerSession'][0]['EmailId'] : '';
        // $isgstapply = !empty($data['FlightBookingData'][0]['FairRules']['IsGSTRequired']) ? $data['FlightBookingData'][0]['FairRules']['IsGSTRequired'] : 0;
        $PrimaryEmail = isset($getAgencyData['PrimaryEmail']) ? trim($getAgencyData['PrimaryEmail']) : '';
        if (!empty($arrAgencyUserDetail) && $arrAgencyUserDetail['IsBookingEmail'] == 1) {
            $Bookingemails = trim($arrAgencyUserDetail['EmailId']);
        } else {
            $Bookingemails = $PrimaryEmail;
        }
        $isAdobrMandatory = $data['FlightBookingData'][0]['isDobAdult'];
        $isCdobrMandatory = $data['FlightBookingData'][0]['isDobChild'];
        $isIdobrMandatory = $data['FlightBookingData'][0]['isDobInfant'];
        $ICSourceSysId = $data['FlightBookingData'][0]['ICSourceSysId'];
        if ($isgstapply == 1) {
            $Bookingemails = $EmailId_cus;
        }

        $arrPassengers = [];
        $deliveryInfo = [];
        $ARR_SALUTION = unserialize(ARR_SALUTION);
        $ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);

        if ($data) {
            $SeatAmount = 0;
            if ($data['CustomerSession']) {
                foreach ($data['CustomerSession'] as $key => $value) {
                    if ($key == 0) {
                        $CustomerSysId = $value['CustomerSysId'];
                    } else {
                        $CustomerSysId = $value['CustomerMemberSysId'];
                    }
                    if ($this->getTemplateId == 7) {
                        $CustomerSysId = $value['FirstName'] . '-' . $value['LastName'];
                    }


                    if ($key == 0) {
                        $intMemberSysId = 1;
                    } else {
                        $intMemberSysId = 0;
                    }
                    if ($value['paxType'] == 1) {
                        $paxTitle = trim($ARR_SALUTION[$value['Salutation']], ".");
                        if ($key == 0) {
                            $deliveryInfo['emails'][$key] = !empty($Bookingemails) ? $Bookingemails : $value['EmailId'];
                            $deliveryInfo['contacts'][$key] = '+' . $value['countryCode'] . '' . $value['Contacts'];
                        }
                        $paxType = 'ADULT';
                    } elseif ($value['paxType'] == 2) {
                        $paxTitle = trim($ARR_SALUTION_CHILD[$value['Salutation']], ".");
                        $paxType = 'CHILD';
                    } else {
                        $paxTitle = trim($ARR_SALUTION_CHILD[$value['Salutation']], ".");
                        $paxType = 'INFANT';
                    }
                    $arrPassengers[$key] = [
                        'ti' => $paxTitle,
                        'fN' => $value['FirstName'],
                        'lN' => $value['LastName'],
                        //'dob' => $value['DOB'],
                        'pt' => $paxType,
                    ];
                    if ($isAdobrMandatory == 1) {
                        $arrPassengers[$key]['dob'] = $value['DOB'];
                    }
                    if ($isCdobrMandatory == 1) {
                        $arrPassengers[$key]['dob'] = $value['DOB'];
                    }
                    if ($isIdobrMandatory == 1) {
                        $arrPassengers[$key]['dob'] = $value['DOB'];
                    }
                    $MealArr = [];
                    if (!empty($SelectedMealSessionNew->params)) {
                        if (isset($SelectedMealSessionNew->params[$CustomerSysId]) && !empty($SelectedMealSessionNew->params[$CustomerSysId])) {
                            $meal = $SelectedMealSessionNew->params[$CustomerSysId];
                            $MealArr[] = array('key' => $meal['key'], 'code' => $meal['Code']);
                            //$arrPassengers[$key]['ssrMealInfos'] = [$MealArr];
                        }
                    }
                    if (!empty($SelectedMealSessionNewInb->params)) {
                        if (isset($SelectedMealSessionNewInb->params[$CustomerSysId]) && !empty($SelectedMealSessionNewInb->params[$CustomerSysId])) {
                            $meal2 = $SelectedMealSessionNewInb->params[$CustomerSysId];
                            $MealArr[] = array('key' => $meal2['key'], 'code' => $meal2['Code']);
                            //$arrPassengers[$key]['ssrMealInfos'] = [$MealArr];
                        }
                    }
                    $BaggArr = [];
                    if (!empty($SelectedBaggSessionNew->params)) {
                        if (isset($SelectedBaggSessionNew->params[$CustomerSysId]) && !empty($SelectedBaggSessionNew->params[$CustomerSysId])) {
                            $bagg = $SelectedBaggSessionNew->params[$CustomerSysId];
                            $BaggArr[] = array('key' => $bagg['key'], 'code' => $bagg['Code']);
                        }
                    }
                    if (!empty($SelectedBaggSessionNewInb->params)) {
                        if (isset($SelectedBaggSessionNewInb->params[$CustomerSysId]) && !empty($SelectedBaggSessionNewInb->params[$CustomerSysId])) {
                            $bagg2 = $SelectedBaggSessionNewInb->params[$CustomerSysId];
                            $BaggArr[] = array('key' => $bagg2['key'], 'code' => $bagg2['Code']);
                        }
                    }
                    $SeatArr = [];
                    if (!empty($selectedSeatSession->params)) {
                        foreach ($selectedSeatSession->params as $segmentid => $val) {
                            if (isset($val[$key + 1]) && !empty($val[$key + 1])) {
                                $Seat = $val[$key + 1];
                                $SeatArr[] = array('key' => $segmentid, 'code' => $Seat['code']);
                                $SeatAmount += $Seat['amount'];
                            }
                        }
                    }
                    if (!empty($MealArr)) {
                        $arrPassengers[$key]['ssrMealInfos'] = $MealArr;
                    }
                    if (!empty($BaggArr)) {
                        $arrPassengers[$key]['ssrBaggageInfos'] = $BaggArr;
                    }
                    if (!empty($SeatArr)) {
                        $arrPassengers[$key]['ssrSeatInfos'] = $SeatArr;
                    }

                    if ($value['paxType'] == 3) {
                        $arrPassengers[$key]['dob'] = $value['DOB'];
                    }
                    if ($interNationalSearch == 1) {
                        $arrPassengers[$key]['dob'] = $value['DOB'];
                        $arrPassengers[$key]['pNum'] = $value['PassportNo'];
                        $arrPassengers[$key]['eD'] = $value['PassportExpiry'];
                        $arrPassengers[$key]['pid'] = $value['passporIssue'];
                        $arrPassengers[$key]['pNat'] = $value['PassportNation'];
                    }
                }
            }
            if ($isgstapply == 1) {
                $gstInfo = array(
                    'gstNumber' =>   $data['CustomerSession'][0]['gstnnumber'],
                    'email' =>   $data['CustomerSession'][0]['gstemail'],
                    'registeredName' =>  $data['CustomerSession'][0]['companyname'],
                    'mobile' =>  $data['CustomerSession'][0]['gstphone'],
                    'address' => $data['CustomerSession'][0]['gstaddress'],
                );
            }
            $PublishedFare = 0;
            $baggageAmount = 0;
            $mealAmount = 0;
            $baggageAmount2 = 0;
            $mealAmount2 = 0;
            if ($data['FlightBookingData']) {
                foreach ($data['FlightBookingData'] as $amount) {
                    $PublishedFare += $amount['FairRules']['intPublishedFare'];
                }
            }

            if ($SelectedBaggSessionNew->params && !empty($SelectedBaggSessionNew->params)) {
                foreach ($SelectedBaggSessionNew->params as $baggage) {
                    $baggageAmount += $baggage['Price'];
                }
            }
            if ($SelectedMealSessionNew->params && !empty($SelectedMealSessionNew->params)) {
                foreach ($SelectedMealSessionNew->params as $meals) {
                    $mealAmount += $meals['Price'];
                }
            }
            if ($SelectedBaggSessionNewInb->params && !empty($SelectedBaggSessionNewInb->params)) {
                foreach ($SelectedBaggSessionNewInb->params as $baggage2) {
                    $baggageAmount2 += $baggage2['Price'];
                }
            }
            if ($SelectedMealSessionNewInb->params && !empty($SelectedMealSessionNewInb->params)) {
                foreach ($SelectedMealSessionNewInb->params as $meals2) {
                    $mealAmount2 += $meals2['Price'];
                }
            }
            $SeatAmount = 0;
            if ($selectedSeatSession->params && !empty($selectedSeatSession->params)) {
                foreach ($selectedSeatSession->params as $seat) {
                    foreach ($seat as $seat2) {
                        $SeatAmount += $seat2['amount'];
                    }
                }
            }


            $amount =  ($PublishedFare + $baggageAmount + $mealAmount + $baggageAmount2 + $mealAmount2 + $SeatAmount);
            $paymentInfos[] = array('amount' => number_format($amount, 2, '.', ''));
            $airline = $data['FlightBookingData'][0]['AirlineName'];

            $data = array(
                'bookingId' => $bookingId,
                'paymentInfos' => $paymentInfos,
                'travellerInfo' => $arrPassengers,
                'deliveryInfo' => $deliveryInfo,
            );

            if ($isgstapply == 1) {
                $data['gstInfo'] = $gstInfo;
            }
            // if($this->gtxagencysysid == '4539'){
            // echo '<pre>';print_r($data);die;
            //}

            $data_stringh = json_encode($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_INSTANT_BOOK_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));


            $outputH = curl_exec($ch);
            // echo '<pre>';print_r($outputH); die('hdhhdhd');

            $response = json_decode($outputH, true);

            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['status']['success'];
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"          => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error"     => ($ResponseStatus == 1) ? "Flight Ticket Success" : "Flight Ticket Failed",
                    'error'            => $ErrorMessage,
                    "text_udf"         => ['response' => $response], // Response
                    "char_udf"         => ['request' => $data], // Request
                    "udf1"             => $SearchFlightTraceId,
                    "udf5"             => 'ticket',
                    "from_destination" => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['from']) : $sessionFlightSearchParams->params['from'],
                    "to_destination"   => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['to']) : $sessionFlightSearchParams->params['to'],
                    "flight_type"      => (int)$sessionFlightSearchParams->params['route'],
                    "source"           => 1,
                    "Pax"              => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => $airline,
                    "status"           => ($ResponseStatus == 1) ? 2 : 1,
                ];

                $ddd = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
            Zend_Session::namespaceUnset('FlightBookingTicket');
            $FlightBookingTicket = new Zend_Session_Namespace('FlightBookingTicket');
            $FlightBookingTicket->params = $response;
            // echo"<pre>";print_r($response);die('ytfgfg');
            return $response;
        } else {
            return $response = [];
        }
        exit;
    }
    public function bookingDetailsTripJack($response)
    {

        $ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : '0';
        $SearchFlightTraceId = isset($response['SearchFlightTraceId']) ? $response['SearchFlightTraceId'] : '0';
        $sessionFlightSearchParams = new Zend_Session_Namespace('SessionFlightSearchParams');
        $airline = $response['BookingData'][0]['AirlineName'];
        $route = (int)$sessionFlightSearchParams->params['route'];
        //echo"<pre>";print_r($sessionFlightSearchParams->params);die('ytfgfg');
        if ($ResponseStatus == 1) {
            $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
            $logFile = $FlightSearchLogFile->params;
            $bookingId = isset($response['bookingId']) ? $response['bookingId'] : '0';
            $data = array(
                'bookingId' => $bookingId
            );

            $data_stringh = json_encode($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_BOOKINGDETAILS_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));


            $outputH = curl_exec($ch);
            //echo"<pre>";print_r($outputH);die;
            $response__ = json_decode($outputH, true);

            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response__['status']['success'];
                $ErrorMessage = isset($response__['errors'][0]['message']) ? $response__['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Booking Details Success" : "Flight Booking Details Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response__], // Response
                    "char_udf"     => ['request' => $data], // Request
                    "udf1"           => $SearchFlightTraceId,
                    "udf5"             => 'bookingdetails',
                    "from_destination" => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['from']) : $sessionFlightSearchParams->params['from'],
                    "to_destination"   => ($route == 3) ? implode(',', $sessionFlightSearchParams->params['to']) : $sessionFlightSearchParams->params['to'],
                    "flight_type"      => (int)$sessionFlightSearchParams->params['route'],
                    "source"           => 1,
                    "Pax"              => ($sessionFlightSearchParams->params['adults'] + $sessionFlightSearchParams->params['childs'] + $sessionFlightSearchParams->params['infants']),
                    "Supplier"         => 'TRIPJACK',
                    "Airline"          => $airline,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                //echo"<pre>";print_r($logParams);die();
                $fffff = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
                //echo"<pre>";print_r($fffff);
            }
            return json_decode($outputH, true);
        } else {
            return $response;
        }
    }

    public function apiFlightTicket($data, $kIndex = null)
    {
        //  echo"<pre>";print_r($data);die();
        $SelectedMealSessionNew = isset($data['SelectedMealSessionNew']) ? $data['SelectedMealSessionNew'] : [];
        $SelectedBaggSessionNew = isset($data['SelectedBaggSessionNew']) ? $data['SelectedBaggSessionNew'] : [];

        $SelectedMealSessionNewInb = isset($data['SelectedMealSessionNewInb']) ? $data['SelectedMealSessionNewInb'] : [];
        $SelectedBaggSessionNewInb = isset($data['SelectedBaggSessionNewInb']) ? $data['SelectedBaggSessionNewInb'] : [];

        $selectedSeatSession = isset($data['selectedSeatSession']) ? $data['selectedSeatSession'] : [];
        $selectedSeatSessionInb = isset($data['selectedSeatSessionInb']) ? $data['selectedSeatSessionInb'] : [];

        $flightSSRDetails = isset($data['flightSSRDetails']) ? $data['flightSSRDetails'] : [];

        $SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
        $SearchParam = $SearchFlightTraceId->params;

        $MealSelected = $SelectedMealSessionNew;
        $MealSelectedInb = $SelectedMealSessionNewInb;
        $BaggSelected = $SelectedBaggSessionNew;
        $BaggSelectedInb = $SelectedBaggSessionNewInb;
        $SeatSelected = $selectedSeatSession;
        $SeatSelectedInb = $selectedSeatSessionInb;
        $arrSSR = $flightSSRDetails;

        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $logFile = $FlightSearchLogFile->params;

        $TraceId = $data['FlightBookingData']['apiTraceId'];
        $ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
        $logParams = (isset($data['logParams']) && !empty($data['logParams'])) ? $data['logParams'] : '';

        $AirlineName = $data['FlightBookingData']['AirlineName'];
        $TotalFlightMembers = $data['FlightBookingData']['TotalFlightMembers'];
        $JourneyType = $data['FlightBookingData']['JourneyType'];
        $SourceAirportCode = $data['FlightBookingData']['SourceAirportCode'];
        $DestAirportCode = $data['FlightBookingData']['DestAirportCode'];
        $isDobAdult = $data['FlightBookingData']['isDobAdult'];
        $isDobChild = $data['FlightBookingData']['isDobChild'];
        $isDobInfant = $data['FlightBookingData']['isDobInfant'];
        // echo '<pre>';
        // print_r($data['sessionFlightSearchParams']['route']);die;
        $arrAgencyUserDetail = isset($data['arrAgencyUserDetail']) ? $data['arrAgencyUserDetail'] : [];
        $getAgencyData = isset($data['getAgencyData']) ? $data['getAgencyData'] : [];

        $isgstapply = (isset($data['CustomerSession'][0]['isgstapply']) && !empty($data['CustomerSession'][0]['isgstapply'])) ? $data['CustomerSession'][0]['isgstapply'] : 0;
        $EmailId_cus = (isset($data['CustomerSession'][0]['EmailId']) && !empty($data['CustomerSession'][0]['EmailId'])) ? $data['CustomerSession'][0]['EmailId'] : '';
        // $isgstapply = !empty($data['FlightBookingData'][0]['FairRules']['IsGSTRequired']) ? $data['FlightBookingData'][0]['FairRules']['IsGSTRequired'] : 0;
        $PrimaryEmail = isset($getAgencyData['PrimaryEmail']) ? trim($getAgencyData['PrimaryEmail']) : '';
        if (!empty($arrAgencyUserDetail) && $arrAgencyUserDetail['IsBookingEmail'] == 1) {
            $Bookingemails = trim($arrAgencyUserDetail['EmailId']);
        } else {
            $Bookingemails = $PrimaryEmail;
        }

        if ($isgstapply == 1) {
            $Bookingemails = $EmailId_cus;
        }
        $arrPassengers = [];


        $ARR_SALUTION = unserialize(ARR_SALUTIONTBO);
        $ARR_SALUTION_CHILD = unserialize(ARR_SALUTIONTBO);
        if ($TraceId && $ResultIndex && $data) {
            $FareBreakdown = $data['FlightBookingData']['FairRules']['FareBreakdown'];
            $arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
            $paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
            $paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
            $IsInternational = $data['sessionFlightSearchParams']['interNationalSearch'];
            $SearchFlightTraceId = $data['sessionFlightSearchParams']['SearchFlightTraceId'];
            $agencyEmailId = '';

            $intK = 0;
            for ($intI = 0; $intI < count($arrFairDetails); $intI++) {
                $intPassengerCount = isset($arrFairDetails[$intI]['PassengerCount']) ? trim($arrFairDetails[$intI]['PassengerCount']) : 0;
                for ($intJ = 0; $intJ < $intPassengerCount; $intJ++) {

                    $CustomerKey = $data['CustomerSession'][$intK]['FirstName'] . $data['CustomerSession'][$intK]['LastName'];
                    $MealArr = [];
                    $BaggageArr = [];
                    $SeatArr = [];
                    $isgstapply = (isset($data['CustomerSession'][0]['isgstapply']) && !empty($data['CustomerSession'][0]['isgstapply'])) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
                    if ($intK == 0) {
                        $CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
                    } else {
                        $CustomerSysId = $data['CustomerSession'][$intK]['CustomerMemberSysId'];
                    }

                    $CustomerKeyST = $CustomerSysId . '_' . $CustomerKey;

                    //echo ($intK + 1).'==';
                    if ($SeatSelected) {
                        foreach ($SeatSelected as $key => $value) {
                            // if (isset($value[$CustomerSysId]) && !empty($value[$CustomerSysId])) {
                            if (isset($value[$intK + 1]) && !empty($value[$intK + 1])) {
                                //unset($value["seatPosition"]);
                                $stdata = array(
                                    "AirlineCode" => $value[$intK + 1]['AirlineCode'],
                                    "FlightNumber" => $value[$intK + 1]['FlightNumber'],
                                    "CraftType" => $value[$intK + 1]['CraftType'],
                                    "Origin" => $value[$intK + 1]['Origin'],
                                    "Destination" => $value[$intK + 1]['Destination'],
                                    "AvailablityType" => $value[$intK + 1]['AvailablityType'],
                                    "Description" => $value[$intK + 1]['Description'],
                                    "Code" => $value[$intK + 1]['Code'],
                                    "RowNo" => $value[$intK + 1]['RowNo'],
                                    "SeatNo" => $value[$intK + 1]['SeatNo'],
                                    "SeatType" => $value[$intK + 1]['SeatType'],
                                    "SeatWayType" => $value[$intK + 1]['SeatWayType'],
                                    "Compartment" => $value[$intK + 1]['Compartment'],
                                    "Deck" => $value[$intK + 1]['Deck'],
                                    "Currency" => $value[$intK + 1]['Currency'],
                                    "Price" => $value[$intK + 1]['Price']
                                );

                                $SeatArr[] = $stdata;
                            }
                        }
                    }

                    if ($data['CustomerSession'][$intK]['paxType'] == 1) {
                        $paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
                    } else {
                        $paxTitle = trim($ARR_SALUTION_CHILD[$data['CustomerSession'][$intK]['Salutation']], ".");
                    }

                    //$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");

                    $getSalutation = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getSalutationByid($data['CustomerSession'][$intK]['Salutation']);
                    $intGender = $getSalutation['Gender_Id'];
                    $PassportNo = $data['CustomerSession'][$intK]['PassportNo'];
                    $PassportExpiry = $data['CustomerSession'][$intK]['PassportExpiry'];
                    $paxAddress = $data['CustomerSession'][$intK]['Address'];
                    $paxCityTitle = $data['CustomerSession'][$intK]['CityTitle'];
                    $paxContactNo = $data['CustomerSession'][$intK]['Contacts'];

                    $FFAirlineCode = isset($data['CustomerSession'][$intK]['FFAirlineCode'])?$data['CustomerSession'][$intK]['FFAirlineCode']:'';
					$FFNumber = isset($data['CustomerSession'][$intK]['FFNumber'])?$data['CustomerSession'][$intK]['FFNumber']:'';

                    if ($intK == 0) {
                        $intMemberSysId = true;
                    } else {
                        $intMemberSysId = false;
                    }
                    if ($arrFairDetails) {
                        foreach ($arrFairDetails as $fare) {
                            $PassengerType = $fare['PassengerType'];
                            if ($PassengerType == 1) {
                                $arrFairDetails2 = $arrFairDetails[0];
                            }
                            if ($PassengerType == 2) {
                                $arrFairDetails2 = $arrFairDetails[1];
                            }
                            if ($PassengerType == 3) {
                                $arrFairDetails2 = $arrFairDetails[2];
                            }
                        }
                    }

                    $PassengerType = $FareBreakdown[$intI]['PassengerType'];
                    $PassengerCount = $FareBreakdown[$intI]['PassengerCount'];
                    $OtherCharges = $FareBreakdown[$intI]['OtherCharges'];
                    $intBaseFare = ($FareBreakdown[$intI]['BaseFare'] / $PassengerCount);
                    $intTax = ($FareBreakdown[$intI]['Tax'] / $PassengerCount);
                    $intYQTax = ($FareBreakdown[$intI]['YQTax'] / $PassengerCount);
                    $intAdditionalTxnFeeOfrd = $FareBreakdown[$intI]['AdditionalTxnFeeOfrd'];
                    $intAdditionalTxnFeePub = $FareBreakdown[$intI]['AdditionalTxnFeePub'];
                    $intAirTransFee = "00.00";
                    $intTransactionFee = "00.00";
                    $arrPassengers[$intK] = [
                        'Title' => $paxTitle,
                        'FirstName' => $data['CustomerSession'][$intK]['FirstName'],
                        'LastName' => $data['CustomerSession'][$intK]['LastName'],
                        'PaxType' => $data['CustomerSession'][$intK]['paxType'],
                        'Gender' => $intGender,
                        'AddressLine1' => $paxAddress,
                        'AddressLine2' => '',
                        'City' => $paxCityTitle,
                        'CountryCode' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
                        'CountryName' => $paxCountryTitle,
                        'ContactNo' => $paxContactNo,
                        'Email' => !empty($Bookingemails) ? $Bookingemails : $data['CustomerSession'][$intK]['EmailId'],
                        'IsLeadPax' => $intMemberSysId,
                        'Nationality' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
                        'FFAirline' => '',
                        'FFNumber' => '',
                        'Fare' =>
                        [
                            'BaseFare' => number_format($intBaseFare, 2, '.', ''),
                            'Tax' => number_format($intTax, 2, '.', ''),
                            'TransactionFee' => $intTransactionFee,
                            'YQTax' => $intYQTax,
                            'PassengerType' => $PassengerType,
                            'PassengerCount' => $PassengerCount,
                            'AdditionalTxnFeeOfrd' => $intAdditionalTxnFeeOfrd,
                            'AdditionalTxnFeePub' => $intAdditionalTxnFeePub,
                            'AirTransFee' => $intAirTransFee,
                            'OtherCharges' => $OtherCharges,
                        ],

                    ];


                    if ($FFAirlineCode && $FFNumber) {
						$arrPassengers[$intK]['FFAirline'] = $FFAirlineCode;
						$arrPassengers[$intK]['FFNumber'] = $FFNumber;
					}

                    if ($data['CustomerSession'][$intK]['paxType'] == 1 && $isDobAdult == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }
                    if ($data['CustomerSession'][$intK]['paxType'] == 2 && $isDobChild == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }
                    if ($data['CustomerSession'][$intK]['paxType'] == 3 && $isDobInfant == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }


                    if ($IsInternational == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                        $arrPassengers[$intK]['PassportNo'] = $PassportNo;
                        $arrPassengers[$intK]['PassportExpiry'] = $PassportExpiry . 'T00:00:00';
                        $arrPassengers[$intK]['PassportIssueCountryCode'] = $data['CustomerSession'][$intK]['countryCodeISO'];
                    }
                    if ($isgstapply == 1 && $intK == 0) {
                        $arrPassengers[$intK]['GSTCompanyAddress'] = $data['CustomerSession'][$intK]['gstaddress'];
                        $arrPassengers[$intK]['GSTCompanyContactNumber'] = $data['CustomerSession'][$intK]['Contacts'];
                        $arrPassengers[$intK]['GSTCompanyName'] = $data['CustomerSession'][$intK]['companyname'];
                        $arrPassengers[$intK]['GSTNumber'] = $data['CustomerSession'][$intK]['gstnnumber'];
                        $arrPassengers[$intK]['GSTCompanyEmail'] = $data['CustomerSession'][$intK]['EmailId'];
                    }
                    if ($this->getTemplateId == 7) {
                        $CustomerSysId = $data['CustomerSession'][$intK]['FirstName'] . '-' . $data['CustomerSession'][$intK]['LastName'];
                    }
                    if ($kIndex == 0) {
                        if (isset($SeatArr) && !empty($SeatArr)) {
                            $arrPassengers[$intK]['SeatDynamic'] = $SeatArr;
                        }

                        if (isset($MealSelected[$CustomerSysId]) && !empty($MealSelected[$CustomerSysId])) {
                            $arrPassengers[$intK]['MealDynamic'] = [$MealSelected[$CustomerSysId]];
                        }
                        if (isset($BaggSelected[$CustomerSysId]) && !empty($BaggSelected[$CustomerSysId])) {
                            $arrPassengers[$intK]['Baggage'] = [$BaggSelected[$CustomerSysId]];
                        }
                    } else {
                        if (isset($SeatArr) && !empty($SeatArr)) {
                            $arrPassengers[$intK]['SeatDynamic'] = $SeatArr;
                        }

                        if (isset($MealSelectedInb[$CustomerSysId]) && !empty($MealSelectedInb[$CustomerSysId])) {
                            $arrPassengers[$intK]['MealDynamic'] = [$MealSelectedInb[$CustomerSysId]];
                        }
                        if (isset($BaggSelectedInb[$CustomerSysId]) && !empty($BaggSelectedInb[$CustomerSysId])) {
                            $arrPassengers[$intK]['Baggage'] = [$BaggSelectedInb[$CustomerSysId]];
                        }
                    }

                    $intK++;
                }
            }
            // echo '<pre>';
            // print_r(($MealSelected));
            // echo '<pre>';
            // print_r(($BaggSelected));
            // echo '<pre>';
            // print_r(($arrPassengers));
            // die('dd');
            $tokenId = $this->authenticateAPI($this->gtxagencysysid);
            $data_post = array(
                'PreferredCurrency' => 'INR',
                'IsBaseCurrencyRequired' => 'true',
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'TokenId' => $tokenId['token'],
                'TraceId' => $TraceId,
                'ResultIndex' => $ResultIndex,
                'Passengers' => $arrPassengers,

            );

            $data_stringh = json_encode($data_post);
            // echo '<pre>';
            // print_r(($data));
            // die;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_TICKET_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_stringh),
            ));

            $outputH = curl_exec($ch);

            $response = json_decode($outputH, true);

            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['Response']['ResponseStatus'];
                $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Ticket Success" : "Flight Ticket Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $data_post], // Request
                    "udf1"         => $SearchFlightTraceId,
                    "udf5"                         => 'ticket',
                    "from_destination"             => $SourceAirportCode,
                    "to_destination"               => $DestAirportCode,
                    "flight_type"                  => ((int)$data['sessionFlightSearchParams']['route']) ? $data['sessionFlightSearchParams']['route'] : 1,
                    "source"                       => 1,
                    "Pax"                          => ($TotalFlightMembers),
                    "Supplier"                     => 'TBO',
                    "Airline"                      => $AirlineName,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
            $apiFlightTicketTBO = new Zend_Session_Namespace('apiFlightTicketTBO');
            $apiFlightTicketTBO->params = $response;
            return $response;
        } else {
            return $response = [];
        }
        exit;
    }

    public function apiFlightBooking($data, $kIndex)
    {
        $SelectedMealSessionNew = isset($data['SelectedMealSessionNew']) ? $data['SelectedMealSessionNew'] : [];
        $SelectedBaggSessionNew = isset($data['SelectedBaggSessionNew']) ? $data['SelectedBaggSessionNew'] : [];

        $SelectedMealSessionNewInb = isset($data['SelectedMealSessionNewInb']) ? $data['SelectedMealSessionNewInb'] : [];
        $SelectedBaggSessionNewInb = isset($data['SelectedBaggSessionNewInb']) ? $data['SelectedBaggSessionNewInb'] : [];

        $selectedSeatSession = isset($data['selectedSeatSession']) ? $data['selectedSeatSession'] : [];
        $selectedSeatSessionInb = isset($data['selectedSeatSessionInb']) ? $data['selectedSeatSessionInb'] : [];

        $flightSSRDetails = isset($data['flightSSRDetails']) ? $data['flightSSRDetails'] : []; 
        $IsLCC = isset($data['FlightBookingData']['IsLCC']) ? $data['FlightBookingData']['IsLCC'] : false; 

        $SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
        $SearchParam = $SearchFlightTraceId->params;

        $AirlineName = $data['FlightBookingData']['AirlineName'];
        $TotalFlightMembers = $data['FlightBookingData']['TotalFlightMembers'];
        $JourneyType = $data['FlightBookingData']['JourneyType'];
        $SourceAirportCode = $data['FlightBookingData']['SourceAirportCode'];
        $DestAirportCode = $data['FlightBookingData']['DestAirportCode'];

        $isDobAdult = $data['FlightBookingData']['isDobAdult'];
        $isDobChild = $data['FlightBookingData']['isDobChild'];
        $isDobInfant = $data['FlightBookingData']['isDobInfant'];

        $MealSelected = $SelectedMealSessionNew;
        $MealSelectedInb = $SelectedMealSessionNewInb;
        $BaggSelected = $SelectedBaggSessionNew;
        $BaggSelectedInb = $SelectedBaggSessionNewInb;
        $SeatSelected = $selectedSeatSession;
        $SeatSelectedInb = $selectedSeatSessionInb;
        $arrSSR = $flightSSRDetails;
        //echo '<pre>';
        //print_r(($SelectedMealSessionNew));die;

        $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
        $logFile = $FlightSearchLogFile->params;

        //$finalFareSummary = $data['finalFareSummary'];
        //$FareBreakdown = $finalFareSummary['FairRules']['FareBreakdown'];
        $TraceId = $data['FlightBookingData']['apiTraceId'];
        $ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
        $logParams = (isset($data['logParams']) && !empty($data['logParams'])) ? $data['logParams'] : '';

        $arrPassengers = [];

        $ARR_SALUTION = unserialize(ARR_SALUTIONTBO);
        $ARR_SALUTION_CHILD = unserialize(ARR_SALUTIONTBO);
        if ($TraceId && $ResultIndex && $data) {
            $FareBreakdown = $data['FlightBookingData']['FairRules']['FareBreakdown'];
            $arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
            $paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
            $paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
            $IsInternational = $data['sessionFlightSearchParams']['interNationalSearch'];
            $SearchFlightTraceId = $data['sessionFlightSearchParams']['SearchFlightTraceId'];
            $agencyEmailId = '';
            $intK = 0;
            for ($intI = 0; $intI < count($arrFairDetails); $intI++) {
                $intPassengerCount = isset($arrFairDetails[$intI]['PassengerCount']) ? trim($arrFairDetails[$intI]['PassengerCount']) : 0;
                for ($intJ = 0; $intJ < $intPassengerCount; $intJ++) {
                    //$CustomerKeyST = $intJ + 1;
                    //echo $kIndex.'==';
                    $CustomerKey = $data['CustomerSession'][$intK]['FirstName'] . $data['CustomerSession'][$intK]['LastName'];
                    $MealArr = [];
                    $BaggageArr = [];
                    $SeatArr = [];
                    $isgstapply = (isset($data['CustomerSession'][0]['isgstapply']) && !empty($data['CustomerSession'][0]['isgstapply'])) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
                    if ($intK == 0) {
                        $CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
                    } else {
                        $CustomerSysId = $data['CustomerSession'][$intK]['CustomerMemberSysId'];
                    }
                    $CustomerKeyST = $CustomerSysId . '_' . $CustomerKey;

                    if ($kIndex == 0) {
                        if (isset($SeatSelected[$CustomerKeyST]) && !empty($SeatSelected[$CustomerKeyST])) {
                            $SeatArr = $SeatSelected[$CustomerKeyST];
                        }
                    } else {
                        if (isset($SeatSelectedInb[$CustomerKeyST]) && !empty($SeatSelectedInb[$CustomerKeyST])) {
                            $SeatArr = $SeatSelectedInb[$CustomerKeyST];
                        }
                    }

                    if ($data['CustomerSession'][$intK]['paxType'] == 1) {
                        $paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
                    } else {
                        $paxTitle = trim($ARR_SALUTION_CHILD[$data['CustomerSession'][$intK]['Salutation']], ".");
                    }

                    //$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");

                    $getSalutation = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getSalutationByid($data['CustomerSession'][$intK]['Salutation']);
                    $intGender = $getSalutation['Gender_Id'];
                    $PassportNo = $data['CustomerSession'][$intK]['PassportNo'];
                    $PassportExpiry = $data['CustomerSession'][$intK]['PassportExpiry'];
                    $paxAddress = $data['CustomerSession'][$intK]['Address'];
                    $paxCityTitle = $data['CustomerSession'][$intK]['CityTitle'];
                    $paxContactNo = $data['CustomerSession'][$intK]['Contacts'];
                    if ($intK == 0) {
                        $intMemberSysId = true;
                    } else {
                        $intMemberSysId = false;
                    }
                    if ($arrFairDetails) {
                        foreach ($arrFairDetails as $fare) {
                            $PassengerType = $fare['PassengerType'];
                            if ($PassengerType == 1) {
                                $arrFairDetails2 = $arrFairDetails[0];
                            }
                            if ($PassengerType == 2) {
                                $arrFairDetails2 = $arrFairDetails[1];
                            }
                            if ($PassengerType == 3) {
                                $arrFairDetails2 = $arrFairDetails[2];
                            }
                        }
                    }

                    $PassengerType = $FareBreakdown[$intI]['PassengerType'];
                    $PassengerCount = $FareBreakdown[$intI]['PassengerCount'];
                    $intBaseFare = ($FareBreakdown[$intI]['BaseFare'] / $PassengerCount);
                    $intTax = ($FareBreakdown[$intI]['Tax'] / $PassengerCount);
                    $intYQTax = ($FareBreakdown[$intI]['YQTax'] / $PassengerCount);
                    $intAdditionalTxnFeeOfrd = $FareBreakdown[$intI]['AdditionalTxnFeeOfrd'];
                    $intAdditionalTxnFeePub = $FareBreakdown[$intI]['AdditionalTxnFeePub'];
                    $intAirTransFee = "00.00";
                    $intTransactionFee = "00.00";
                    $arrPassengers[$intK] = [
                        'Title' => $paxTitle,
                        'FirstName' => $data['CustomerSession'][$intK]['FirstName'],
                        'LastName' => $data['CustomerSession'][$intK]['LastName'],
                        'PaxType' => $data['CustomerSession'][$intK]['paxType'],
                        'Gender' => $intGender,
                        'AddressLine1' => $paxAddress,
                        'AddressLine2' => '',
                        'City' => $paxCityTitle,
                        'CountryCode' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
                        'CountryName' => $paxCountryTitle,
                        'ContactNo' => $paxContactNo,
                        'Email' => $data['CustomerSession'][$intK]['EmailId'],
                        'IsLeadPax' => $intMemberSysId,
                        'Nationality' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
                        'FFAirline' => '',
                        'FFNumber' => '',
                        'Fare' =>
                        [
                            'BaseFare' => number_format($intBaseFare, 2, '.', ''),
                            'Tax' => number_format($intTax, 2, '.', ''),
                            'TransactionFee' => $intTransactionFee,
                            'YQTax' => $intYQTax,
                            'PassengerType' => $PassengerType,
                            'PassengerCount' => $PassengerCount,
                            'AdditionalTxnFeeOfrd' => $intAdditionalTxnFeeOfrd,
                            'AdditionalTxnFeePub' => $intAdditionalTxnFeePub,
                            'AirTransFee' => $intAirTransFee,
                        ],

                    ];


                    // if ($IsInternational == '' && $data['CustomerSession'][$intK]['paxType'] == 3 || $data['CustomerSession'][$intK]['paxType'] == 2) {
                    //     $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    // }
                    // if ($IsInternational == '') {
                    //     $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    // }

                    if ($data['CustomerSession'][$intK]['paxType'] == 1 && $isDobAdult == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }
                    if ($data['CustomerSession'][$intK]['paxType'] == 2 && $isDobChild == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }
                    if ($data['CustomerSession'][$intK]['paxType'] == 3 && $isDobInfant == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                    }


                    if ($IsInternational == 1) {
                        $arrPassengers[$intK]['DateOfBirth'] = $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00';
                        $arrPassengers[$intK]['PassportNo'] = $PassportNo;
                        $arrPassengers[$intK]['PassportExpiry'] = $PassportExpiry . 'T00:00:00';
                        $arrPassengers[$intK]['PassportIssueCountryCode'] = $data['CustomerSession'][$intK]['countryCodeISO'];
                    }
                    if ($isgstapply == 1 && $intK == 0) {
                        $arrPassengers[$intK]['GSTCompanyAddress'] = $data['CustomerSession'][$intK]['gstaddress'];
                        $arrPassengers[$intK]['GSTCompanyContactNumber'] = $data['CustomerSession'][$intK]['Contacts'];
                        $arrPassengers[$intK]['GSTCompanyName'] = $data['CustomerSession'][$intK]['companyname'];
                        $arrPassengers[$intK]['GSTNumber'] = $data['CustomerSession'][$intK]['gstnnumber'];
                        $arrPassengers[$intK]['GSTCompanyEmail'] = $data['CustomerSession'][$intK]['EmailId'];
                    }
                    if ($kIndex == 0) {
                        if (isset($SeatSelected[$CustomerKeyST]) && !empty($SeatSelected[$CustomerKeyST])) {
                            $arrPassengers[$intK]['SeatPreference'] = $SeatArr;
                        }

                        if (isset($MealSelected[$CustomerSysId]) && !empty($MealSelected[$CustomerSysId])) {
                            if($IsLCC == true){
                                $arrPassengers[$intK]['Meal'] = [$MealSelected[$CustomerSysId]];
                            }else{
                                $arrPassengers[$intK]['Meal'] = $MealSelected[$CustomerSysId];
                            }
                        }
                        if (isset($BaggSelected[$CustomerSysId]) && !empty($BaggSelected[$CustomerSysId])) {
                            $arrPassengers[$intK]['Baggage'] = [$BaggSelected[$CustomerSysId]];
                        }
                    } else {
                        if (isset($SeatSelectedInb[$CustomerKeyST]) && !empty($SeatSelectedInb[$CustomerKeyST])) {
                            $arrPassengers[$intK]['SeatPreference'] = $SeatArr;
                        }

                        if (isset($MealSelectedInb[$CustomerSysId]) && !empty($MealSelectedInb[$CustomerSysId])) {
                            $arrPassengers[$intK]['Meal'] = [$MealSelectedInb[$CustomerSysId]];
                        }
                        if (isset($BaggSelectedInb[$CustomerSysId]) && !empty($BaggSelectedInb[$CustomerSysId])) {
                            $arrPassengers[$intK]['Baggage'] = [$BaggSelectedInb[$CustomerSysId]];
                        }
                    }

                    $intK++;
                }
            }
            // echo '<pre>';
            // print_r(($arrPassengers));
            // die('dd');
            $tokenId = $this->authenticateAPI($this->gtxagencysysid);
            $data = array(
                'PreferredCurrency' => 'INR',
                'IsBaseCurrencyRequired' => 'true',
                'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                'TokenId' => $tokenId['token'],
                'TraceId' => $TraceId,
                'ResultIndex' => $ResultIndex,
                'Passengers' => $arrPassengers,

            );
            // echo '<pre>';print_r($data);die;
            $data_stringh = json_encode($data);


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_BOOKING_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_stringh),
            ));

            $outputH = curl_exec($ch);

            $response = json_decode($outputH, true);

            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['Response']['ResponseStatus'];
                $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

                $logParams = [
                    "user_id"                  => 1,
                    "AgencySysId"              => $this->gtxagencysysid,
                    "custom_error"             => ($ResponseStatus == 1) ? "Flight Booking Success" : "Flight Booking Failed",
                    'error'                    => $ErrorMessage,
                    "text_udf"                 => ['response' => $response], // Response
                    "char_udf"                 => ['request' => $data], // Request
                    "udf1"                     => $SearchFlightTraceId,
                    "udf5"                     => 'booking',
                    "from_destination"         => $SourceAirportCode,
                    "to_destination"           => $DestAirportCode,
                    "flight_type"              => (int)$data['sessionFlightSearchParams']['route'],
                    "source"                   => 1,
                    "Pax"                      => ($TotalFlightMembers),
                    "Supplier"                 => 'TBO',
                    "Airline"                  => $AirlineName,
                    "status"                   => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
            $apiFlightBooking = new Zend_Session_Namespace('apiFlightBooking');
            $apiFlightBooking->params = $response;
            return $response;
        } else {
            return $response = [];
        }
    }

    public function generateNonLccTicket($data)
    {
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);

        $AirlineName = $data['FlightBookingData']['AirlineName'];
        $TotalFlightMembers = $data['FlightBookingData']['TotalFlightMembers'];
        $JourneyType = $data['FlightBookingData']['JourneyType'];
        $SourceAirportCode = $data['FlightBookingData']['SourceAirportCode'];
        $DestAirportCode = $data['FlightBookingData']['DestAirportCode'];
        $SearchFlightTraceId = $data['FlightBookingData']['SearchFlightTraceId'];

        $datah = array(
            'EndUserIp' => $_SERVER['REMOTE_ADDR'],
            'TokenId' => $tokenId['token'],
            'TraceId' => $data['TraceId'],
            'PNR' => $data['PNR'],
            'BookingId' => $data['BookingId'],
        );
        //echo '<pre>';print_r(($data['FlightBookingData']));die;
        $data_stringh = json_encode($datah);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, FLIGHT_API_TICKET_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_stringh)
        ));
        $outputH = curl_exec($ch);
        $response = json_decode($outputH, true);

        if (FLIGHT_API_LOGS) {
            $ResponseStatus = isset($response['Response']['ResponseStatus']) ? $response['Response']['ResponseStatus'] : '0';
            $ErrorMessage = isset($response['Response']['Error']['ErrorMessage']) ? $response['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"                    => 1,
                "AgencySysId"                => $this->gtxagencysysid,
                "custom_error"               => ($ResponseStatus == 1) ? "Flight Ticket Success" : "Flight Ticket Failed",
                'error'                      => $ErrorMessage,
                "text_udf"                   => ['response' => $response], // Response
                "char_udf"                   => ['request' => $data], // Request
                "udf1"                       => $SearchFlightTraceId,
                "udf5"                       => 'ticket',
                "from_destination"           => $SourceAirportCode,
                "to_destination"             => $DestAirportCode,
                "flight_type"                => (int)$JourneyType,
                "source"                     => 1,
                "Pax"                        => ($TotalFlightMembers),
                "Supplier"                   => 'TBO',
                "Airline"                    => $AirlineName,
                "status"                     => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }
        $FlightBookingTicketSession = new Zend_Session_Namespace('FlightBookingTicketSession');
        $FlightBookingTicketSession->params = $response;
        return $response;
    }

    public function bookingDetailsSeriesFareNew($FlightBookingData, $response)
    {
        $passanger = $bookingId = $pnrDetails = array();
        $status = 'SUCCESS';
        if ($FlightBookingData) {
            foreach ($FlightBookingData as $Data) {
                $SourceAirportCode = trim($Data['SourceAirportCode']);
                $DestAirportCode = trim($Data['DestAirportCode']);
                $OnwardGroupPNR = trim($Data['OnwardGroupPNR']);
                $OnwardAutoTicket = trim($Data['OnwardAutoTicket']);
                $InwardGroupPNR = (isset($Data['InwardGroupPNR']) && !empty($Data['InwardGroupPNR'])) ? trim($Data['InwardGroupPNR']) : '';
                $InwardAutoTicket = (isset($Data['InwardAutoTicket']) && !empty($Data['InwardAutoTicket'])) ? trim($Data['InwardAutoTicket']) : false;
                $bookingId[] = trim($Data['bookingId']);
                $ARR_SALUTION = unserialize(ARR_SALUTION);
                $ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
                if ($OnwardAutoTicket || $InwardAutoTicket) {
                    $status = 'SUCCESS';
                }

                if (isset($Data['Segments']) && !empty($Data['Segments'])) {
                    foreach ($Data['Segments'] as $sskey => $ssVal) {
                        $isReturnSegment = isset($ssVal['isReturnSegment']) ? $ssVal['isReturnSegment'] : false;
                        if ($isReturnSegment) {
                            $pnrDetails[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = ($InwardGroupPNR) ? $InwardGroupPNR : '';
                        } else {
                            $pnrDetails[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = $OnwardGroupPNR;
                        }
                        //$pnrDetails[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = $OnwardGroupPNR;
                    }
                } else {
                    $pnrDetails = array($SourceAirportCode . '-' . $DestAirportCode => $OnwardGroupPNR);
                }
            }
        }

        foreach ($response as $key => $val) {
            $paxtype = $val['paxType'];
            if ($paxtype == 1) {
                $paxtypeName = 'ADULT';
                $Salutation = $ARR_SALUTION[$val['Salutation']];
            } else if ($paxtype == 2) {
                $paxtypeName = 'CHILD';
                $Salutation = $ARR_SALUTION_CHILD[$val['Salutation']];
            } else {
                $paxtypeName = 'INFANT';
                $Salutation = $ARR_SALUTION_CHILD[$val['Salutation']];
            }
            $passanger[] = array(
                'pnrDetails' => $pnrDetails,
                'ti' => $Salutation,
                'pt' => $paxtypeName,
                'fN' => $val['FirstName'],
                'lN' => $val['LastName'],
                'id' => $paxtype,
            );
        }
        $response = array(
            'status' => array('success' => 1),
            'itemInfos' => array('AIR' => array('travellerInfos' => $passanger)),
            'order' => array('bookingId' => $bookingId, 'status' => $status),
        );
        if (FLIGHT_API_LOGS) {
            //Write Request Logs starts...
            $strFilePath = "flight/BookingDetails/" . time() . "_Series_BookingDetails_response.json";
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($response));
            //Write Request Logs starts...
        }
        return $response;
    }
    public function CheckReleaseInventory($bookingId)
    {
        $SECURITYKEY = SECURITYKEY;
        $this->postFields = "?RefNo=" . $SECURITYKEY;
        $URL = 'https://gtxapi.hellogtx.com/api/v2/release-inventory/' . $this->postFields;

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
            ),
        ));
        $response = curl_exec($curl);

        $err = curl_error($curl);
        curl_close($curl);
        $resultset = json_decode($response, 1);
        return $resultset;
    }
    public function CheckSoldInventory($bookingId)
    {
        $SECURITYKEY = SECURITYKEY;
        $this->postFields = "?RefNo=" . $bookingId;
        $URL = 'https://gtxapi.hellogtx.com/api/v2/sold-inventory/' . $this->postFields;
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
            ),
        ));
        $response = curl_exec($curl);

        $err = curl_error($curl);
        curl_close($curl);
        $resultset = json_decode($response, 1);
        return $resultset;
    }

    public function CheckInventorycheckRetriveUpdateNew($FlightBookingData = array(), $sessionFlightSearchParams = array())
    {
        // echo "FlightBookingData<pre>"; print_r($sessionFlightSearchParams);die;
        $SECURITYKEY = SECURITYKEY;
        $resultset = [];
        if ($FlightBookingData) {
            foreach ($FlightBookingData as $key => $value) {
                $apiTraceId1 = explode('-', $value['FairRules']['PriceID']);
                $apiTraceId = explode('_', $apiTraceId1[0]);

                $adults = $sessionFlightSearchParams['adults'];
                $childs = $sessionFlightSearchParams['childs'];
                $infants = $sessionFlightSearchParams['infants'];
                $FromDate = explode('/', $value['FromDate']);
                $FromDate1 = trim($FromDate[2] . '-' . $FromDate[1] . '-' . $FromDate[0]);
                $this->postFields = "?SecurityKey=" . $SECURITYKEY;
                $this->postFields .= "&FlightType=" . $sessionFlightSearchParams['route'];
                $this->postFields .= "&FromDate=" . $FromDate1;
                $this->postFields .= "&id=" . $apiTraceId[1];
                $this->postFields .= "&adult=" . $adults;
                $this->postFields .= "&child=" . $childs;
                $this->postFields .= "&infant=" . $infants;
                // echo '<pre>';
                // print_r($this->postFields);
                // die;
                $URL = 'https://gtxapi.hellogtx.com/api/v2/check-retrive-update/' . $this->postFields;
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => $URL,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "GET",
                    CURLOPT_POSTFIELDS => "",
                    CURLOPT_HTTPHEADER => array(
                        "cache-control: no-cache",
                        "content-type: application/json",
                    ),
                ));
                $response = curl_exec($curl);

                $err = curl_error($curl);
                curl_close($curl);
                $resultset[$key] = json_decode($response, 1);
            }
        }
        // echo '<pre>';
        // print_r($resultset);
        //die;
        $RetriveUpdateNew = new Zend_Session_Namespace('RetriveUpdateNew');
        $RetriveUpdateNew->params = $resultset;
        return $resultset;
    }

    public function generateRoundTripRequest($data, $IsLCC)
    {
        //echo '<pre>';print_r($data['FlightBookingData']['JourneyType']);die;
        if ($IsLCC) {
            if ($data['FlightBookingData']['JourneyType'] == 1) {
                $SelectedMealSessionNew = new Zend_Session_Namespace('SelectedMealSessionNew');
                $SelectedBaggSessionNew = new Zend_Session_Namespace('SelectedBaggSessionNew');
                $flightSSRDetails = new Zend_Session_Namespace('flightSSRDetails');
                $MealSelected = $SelectedMealSessionNew->params;
                $BaggSelected = $SelectedBaggSessionNew->params;
                $arrSSR = $flightSSRDetails->params;
            } else {
                $SelectedMealSessionNewInb = new Zend_Session_Namespace('SelectedMealSessionNewInb');
                $SelectedBaggSessionNewInb = new Zend_Session_Namespace('SelectedBaggSessionNewInb');
                $flightSSRDetailsInb = new Zend_Session_Namespace('flightSSRDetailsInb');
                $MealSelected = $SelectedMealSessionNewInb->params;
                $BaggSelected = $SelectedBaggSessionNewInb->params;
                $arrSSR = $flightSSRDetailsInb->params;
            }
            //$SelectedMealSessionNew = new Zend_Session_Namespace('SelectedMealSessionNew');
            //$SelectedBaggSessionNew = new Zend_Session_Namespace('SelectedBaggSessionNew');
            //$flightSSRDetails = new Zend_Session_Namespace('flightSSRDetails');

            $TraceId = $data['FlightBookingData']['apiTraceId'];
            $ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
            $arrPassengers = [];
            $ARR_SALUTION = unserialize(ARR_SALUTION);
            if ($TraceId && $ResultIndex && $data) {
                $arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
                $IsInternational = $data['FlightBookingData']['IsInternational'];
                $paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
                $paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
                $GSTCompanyAddress = '';
                $GSTCompanyContactNumber = '';
                $GSTCompanyName = '';
                $GSTNumber = '';
                $GSTCompanyEmail = '';
                $agencyEmailId = '';
                if ($data['CustomerSession']) {
                    //$dataSSR = array('TraceId' => $TraceId, 'ResultIndex' => $ResultIndex);
                    //$arrSSR = $this->flightSSRDetails($dataSSR);
                    //                $arrSSR = [];
                    foreach ($data['CustomerSession'] as $key => $value) {
                        if ($key == 0) {
                            $CustomerSysId = $value['CustomerSysId'];
                        } else {
                            $CustomerSysId = $value['CustomerMemberSysId'];
                        }
                        if (isset($MealSelected[$CustomerSysId]) && !empty($MealSelected[$CustomerSysId])) {
                            $WayType            = $MealSelected[$CustomerSysId]['WayType'];
                            $Code               = $MealSelected[$CustomerSysId]['Code'];
                            $Description        = $MealSelected[$CustomerSysId]['Description'];
                            $AirlineDescription = $MealSelected[$CustomerSysId]['AirlineDescription'];
                            $Quantity           = $MealSelected[$CustomerSysId]['Quantity'];
                            $Currency           = $MealSelected[$CustomerSysId]['Currency'];
                            $Price              = $MealSelected[$CustomerSysId]['Price'];
                            $Origin             = $MealSelected[$CustomerSysId]['Origin'];
                            $Destination        = $MealSelected[$CustomerSysId]['Destination'];
                        } else {
                            $WayType            = isset($arrSSR['MealDynamic'][0][0]['WayType']) ? trim($arrSSR['MealDynamic'][0][0]['WayType']) : '2';
                            $Code               = isset($arrSSR['MealDynamic'][0][0]['Code']) ? trim($arrSSR['MealDynamic'][0][0]['Code']) : 'No Meal';
                            $Description        = isset($arrSSR['MealDynamic'][0][0]['Description']) ? trim($arrSSR['MealDynamic'][0][0]['Description']) : '2';
                            $AirlineDescription = isset($arrSSR['MealDynamic'][0][0]['AirlineDescription']) ? trim($arrSSR['MealDynamic'][0][0]['AirlineDescription']) : '';
                            $Quantity           = isset($arrSSR['MealDynamic'][0][0]['Quantity']) ? trim($arrSSR['MealDynamic'][0][0]['Quantity']) : '0';
                            $Currency           = isset($arrSSR['MealDynamic'][0][0]['Currency']) ? trim($arrSSR['MealDynamic'][0][0]['Currency']) : 'INR';
                            $Price              = isset($arrSSR['MealDynamic'][0][0]['Price']) ? trim($arrSSR['MealDynamic'][0][0]['Price']) : '0';
                            $Origin             = isset($arrSSR['MealDynamic'][0][0]['Origin']) ? trim($arrSSR['MealDynamic'][0][0]['Origin']) : trim($data['Origin']);
                            $Destination        = isset($arrSSR['MealDynamic'][0][0]['Destination']) ? trim($arrSSR['MealDynamic'][0][0]['Destination']) : ($data['Destination']);
                        }
                        if (isset($BaggSelected[$CustomerSysId]) && !empty($BaggSelected[$CustomerSysId])) {
                            $WayTypeBaggage            = $BaggSelected[$CustomerSysId]['WayType'];
                            $CodeBaggage               = $BaggSelected[$CustomerSysId]['Code'];
                            $DescriptionBaggage        = $BaggSelected[$CustomerSysId]['Description'];
                            $WeightBaggage             = $BaggSelected[$CustomerSysId]['Weight'];
                            $CurrencyBaggage           = $BaggSelected[$CustomerSysId]['Currency'];
                            $PriceBaggage              = $BaggSelected[$CustomerSysId]['Price'];
                        } else {
                            $WayTypeBaggage            = isset($arrSSR['Baggage'][0][0]['WayType']) ? trim($arrSSR['Baggage'][0][0]['WayType']) : '2';
                            $CodeBaggage               = isset($arrSSR['Baggage'][0][0]['Code']) ? trim($arrSSR['Baggage'][0][0]['Code']) : 'No Baggage';
                            $DescriptionBaggage        = isset($arrSSR['Baggage'][0][0]['Description']) ? trim($arrSSR['Baggage'][0][0]['Description']) : '2';
                            $WeightBaggage             = isset($arrSSR['Baggage'][0][0]['Weight']) ? trim($arrSSR['Baggage'][0][0]['Weight']) : '0';
                            $CurrencyBaggage           = isset($arrSSR['Baggage'][0][0]['Currency']) ? trim($arrSSR['Baggage'][0][0]['Currency']) : 'INR';
                            $PriceBaggage              = isset($arrSSR['Baggage'][0][0]['Price']) ? trim($arrSSR['Baggage'][0][0]['Price']) : '0';
                        }
                        $paxTitle = trim($ARR_SALUTION[$value['Salutation']], ".");
                        if ($value['Salutation'] <= 2) {
                            $intGender = $value['Salutation'];
                        } else {
                            $intGender = 2;
                        }
                        $PassportNo = $value['PassportNo'];
                        $PassportNation = $value['PassportNation'];
                        $PassportExpiry = $value['PassportExpiry'];
                        $paxAddress = $value['Address'];
                        $paxCityTitle = $value['CityTitle'];
                        $paxContactNo = $value['Contacts'];
                        if ($key == 0) {
                            $intMemberSysId = 1;
                        } else {
                            $intMemberSysId = 0;
                        }
                        if ($arrFairDetails) {
                            foreach ($arrFairDetails as $fare) {
                                $PassengerType = $fare['PassengerType'];
                                if ($PassengerType == 1) {
                                    $arrFairDetails2 = $arrFairDetails[0];
                                }
                                if ($PassengerType == 2) {
                                    $arrFairDetails2 = $arrFairDetails[1];
                                }
                                if ($PassengerType == 3) {
                                    $arrFairDetails2 = $arrFairDetails[2];
                                }
                            }
                        }
                        $intBaseFare = $arrFairDetails2['BaseFare'];
                        $intTax = $arrFairDetails2['Tax'];
                        $intYQTax = $arrFairDetails2['YQTax'];
                        $intAdditionalTxnFeeOfrd = $arrFairDetails2['AdditionalTxnFeeOfrd'];
                        $intAdditionalTxnFeePub = $arrFairDetails2['AdditionalTxnFeePub'];
                        $intAirTransFee = "00.00";
                        $intTransactionFee = "00.00";
                        $arrPassengers[] = [
                            'Title' => $paxTitle,
                            'FirstName' => $value['FirstName'],
                            'LastName' => $value['LastName'],
                            'PaxType' => $value['paxType'],
                            'DateOfBirth' => $value['DOB'],
                            'Gender' => $intGender,
                            'PassportNo' => ($IsInternational == 1) ? $PassportNo : '',
                            'PassportNation' => ($IsInternational == 1) ? $PassportNation : '',
                            'PassportExpiry' => ($IsInternational == 1) ? $PassportExpiry : '',
                            'AddressLine1' => $paxAddress,
                            'AddressLine2' => '',
                            'City' => $paxCityTitle,
                            'CountryCode' => $paxCountryCode,
                            'CountryName' => $paxCountryTitle,
                            'ContactNo' => $paxContactNo,
                            'Email' => !empty($agencyEmailId) ? $agencyEmailId : "gaurav@hellogtx.com",
                            'IsLeadPax' => $intMemberSysId,
                            'FFAirline' => '',
                            'FFNumber' => '',
                            'GSTCompanyAddress' => $GSTCompanyAddress,
                            'GSTCompanyContactNumber' => $GSTCompanyContactNumber,
                            'GSTCompanyName' => $GSTCompanyName,
                            'GSTNumber' => $GSTNumber,
                            'GSTCompanyEmail' => $GSTCompanyEmail,
                            'Fare' =>
                            [
                                'BaseFare' => $intBaseFare,
                                'Tax' => $intTax,
                                'TransactionFee' => $intTransactionFee,
                                'YQTax' => $intYQTax,
                                'AdditionalTxnFeeOfrd' => $intAdditionalTxnFeeOfrd,
                                'AdditionalTxnFeePub' => $intAdditionalTxnFeePub,
                                'AirTransFee' => $intAirTransFee
                            ],
                            '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
                            ]
                        ];
                    }
                }
                //echo "<pre>";print_r($arrPassengers);exit;
                $tokenId = $this->authenticateAPI();
                $request = array(
                    'PreferredCurrency' => 'INR',
                    'IsBaseCurrencyRequired' => 'true',
                    'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                    'TokenId' => $tokenId,
                    'TraceId' => $TraceId,
                    'ResultIndex' => $ResultIndex,
                    'Passengers' => $arrPassengers
                );
            }
        } else {
            if ($data['FlightBookingData']['JourneyType'] == 1) {
                $SelectedMealSessionNew = new Zend_Session_Namespace('SelectedMealSessionNew');
                $arrSSRSelected = $SelectedMealSessionNew->params;
                $flightSSRDetails = new Zend_Session_Namespace('flightSSRDetails');
                $arrSSR = $flightSSRDetails->params;
            } else {
                $SelectedMealSessionNewInb = new Zend_Session_Namespace('SelectedMealSessionNewInb');
                $arrSSRSelected = $SelectedMealSessionNewInb->params;
                $flightSSRDetailsInb = new Zend_Session_Namespace('flightSSRDetailsInb');
                $arrSSR = $flightSSRDetailsInb->params;
            }
            $TraceId = $data['FlightBookingData']['apiTraceId'];
            $ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
            $arrPassengers = [];
            $ARR_SALUTION = unserialize(ARR_SALUTION);
            if ($TraceId && $ResultIndex && $data) {
                $arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
                $IsInternational = $data['FlightBookingData']['IsInternational'];
                $paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
                $paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
                $GSTCompanyAddress = '';
                $GSTCompanyContactNumber = '';
                $GSTCompanyName = '';
                $GSTNumber = '';
                $GSTCompanyEmail = '';
                $agencyEmailId = '';
                if ($data['CustomerSession']) {
                    //$dataSSR = array('TraceId' => $TraceId, 'ResultIndex' => $ResultIndex);
                    //$arrSSR = $this->flightSSRDetails($dataSSR);

                    $SeatCode            = isset($arrSSR['SeatPreference'][0]['Code']) ? trim($arrSSR['SeatPreference'][0]['Code']) : 'A';
                    $SeatDesc            = isset($arrSSR['SeatPreference'][0]['Description']) ? trim($arrSSR['SeatPreference'][0]['Description']) : 'Window';
                    foreach ($data['CustomerSession'] as $key => $value) {
                        if ($key == 0) {
                            $CustomerSysId = $value['CustomerSysId'];
                        } else {
                            $CustomerSysId = $value['CustomerMemberSysId'];
                        }
                        if (isset($arrSSRSelected[$CustomerSysId]) && !empty($arrSSRSelected[$CustomerSysId])) {
                            $MealCode = $arrSSRSelected[$CustomerSysId]['Code'];
                            $MealDesc = $arrSSRSelected[$CustomerSysId]['Description'];
                        } else {
                            $MealCode = isset($arrSSR['Meal'][0]['Code']) ? trim($arrSSR['Meal'][0]['Code']) : 'VGML';
                            $MealDesc = isset($arrSSR['Meal'][0]['Description']) ? trim($arrSSR['Meal'][0]['Description']) : 'Veg/Non Dairy';
                        }
                        $paxTitle = trim($ARR_SALUTION[$value['Salutation']], ".");
                        if ($value['Salutation'] <= 2) {
                            $intGender = $value['Salutation'];
                        } else {
                            $intGender = 2;
                        }
                        $PassportNo = $value['PassportNo'];
                        $PassportNation = $value['PassportNation'];
                        $PassportExpiry = $value['PassportExpiry'];
                        $paxAddress = $value['Address'];
                        $paxCityTitle = $value['CityTitle'];
                        $paxContactNo = $value['Contacts'];
                        if ($key == 0) {
                            $intMemberSysId = 1;
                        } else {
                            $intMemberSysId = 0;
                        }
                        if ($arrFairDetails) {
                            foreach ($arrFairDetails as $fare) {
                                $PassengerType = $fare['PassengerType'];
                                if ($PassengerType == 1) {
                                    $arrFairDetails2 = $arrFairDetails[0];
                                }
                                if ($PassengerType == 2) {
                                    $arrFairDetails2 = $arrFairDetails[1];
                                }
                                if ($PassengerType == 3) {
                                    $arrFairDetails2 = $arrFairDetails[2];
                                }
                            }
                        }
                        $intBaseFare = $arrFairDetails2['BaseFare'];
                        $intTax = $arrFairDetails2['Tax'];
                        $intYQTax = $arrFairDetails2['YQTax'];
                        $intAdditionalTxnFeeOfrd = $arrFairDetails2['AdditionalTxnFeeOfrd'];
                        $intAdditionalTxnFeePub = $arrFairDetails2['AdditionalTxnFeePub'];
                        $intAirTransFee = "00.00";
                        $intTransactionFee = "00.00";
                        $arrPassengers[] = [
                            'Title' => $paxTitle,
                            'FirstName' => $value['FirstName'],
                            'LastName' => $value['LastName'],
                            'PaxType' => $value['paxType'],
                            'DateOfBirth' => $value['DOB'],
                            'Gender' => $intGender,
                            'PassportNo' => ($IsInternational == 1) ? $PassportNo : '',
                            'PassportExpiry' => ($IsInternational == 1) ? $PassportExpiry : '',
                            'AddressLine1' => $paxAddress,
                            'AddressLine2' => '',
                            'City' => $paxCityTitle,
                            'CountryCode' => $paxCountryCode,
                            'CountryName' => $paxCountryTitle,
                            'ContactNo' => $paxContactNo,
                            'Email' => !empty($agencyEmailId) ? $agencyEmailId : "gaurav@hellogtx.com",
                            'IsLeadPax' => $intMemberSysId,
                            'FFAirline' => '',
                            'FFNumber' => '',
                            'GSTCompanyAddress' => $GSTCompanyAddress,
                            'GSTCompanyContactNumber' => $GSTCompanyContactNumber,
                            'GSTCompanyName' => $GSTCompanyName,
                            'GSTNumber' => $GSTNumber,
                            'GSTCompanyEmail' => $GSTCompanyEmail,
                            'Fare' =>
                            [
                                'BaseFare' => $intBaseFare,
                                'Tax' => $intTax,
                                'TransactionFee' => $intTransactionFee,
                                'YQTax' => $intYQTax,
                                'AdditionalTxnFeeOfrd' => $intAdditionalTxnFeeOfrd,
                                'AdditionalTxnFeePub' => $intAdditionalTxnFeePub,
                                'AirTransFee' => $intAirTransFee
                            ],
                            'Meal' =>
                            [
                                'Code' => $MealCode,
                                'Description' => $MealDesc
                            ],
                            'Seat' =>
                            [
                                'Code' => $SeatCode,
                                'Description' => $SeatDesc
                            ]
                        ];
                    }
                }

                //           echo "<pre>";print_r($arrPassengers);exit;
                $tokenId = $this->authenticateAPI();
                $request = array(
                    'EndUserIp' => $_SERVER['REMOTE_ADDR'],
                    'TokenId' => $tokenId,
                    'TraceId' => $TraceId,
                    'ResultIndex' => $ResultIndex,
                    'Passengers' => $arrPassengers
                );
            }
        }
        return $request;
    }

    public function cancelFlightBooking($data)
    {
        $SearchParam = $data['apiTraceId'];
        $intCancellationType = $data['CancellationType'];
        $RequestType = $data['requestType'];
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);
        if ($RequestType == 1 || $RequestType == 2) {
            $datah = array(
                "BookingId" => $data['bookingId'],
                "RequestType" => $RequestType,
                "CancellationType" => $intCancellationType,
                "Remarks" => $data['remarks'],
                "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                "TokenId" => $tokenId['token'],
            );
            if ($RequestType == 2) {
                $datah['Sectors'] = $data['sectorsSelectors'];
                $datah['TicketId'] = $data['TicketId'];
            }
            $cURL = FLIGHT_API_BOOKING_CHANGE_REQUEST;
        } else {
            $datah = array(
                "BookingId" => $data['bookingId'],
                "Source" => $data['Source'],
                "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                "TokenId" => $tokenId['token'],
            );
            $cURL = FLIGHT_API_BOOKING_RELEASE_PNR;
        }
        // echo "<pre>";
        // print_r(json_encode($datah));
        // die('dd');

        $data_stringh = json_encode($datah);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $cURL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_stringh)
        ));
        $outputH = curl_exec($ch);
        $responseTBO = json_decode($outputH, true);
        if (FLIGHT_API_LOGS) {

            $ResponseStatus = $responseTBO['Response']['ResponseStatus'];
            $ErrorMessage = isset($responseTBO['Response']['Error']['ErrorMessage']) ? $responseTBO['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"      => 1,
                "AgencySysId"      => $this->gtxagencysysid,
                "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Submit Success" : "Flight Amen Submit Failed",
                'error'        => $ErrorMessage,
                "text_udf"     => ['response' => $responseTBO], // Response
                "char_udf"     => ['request' => $datah], // Request
                "udf1"         => $SearchParam,
                "status"       => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }

        Zend_Session::namespaceUnset('SubmitAmendment');
        $SubmitAmendment = new Zend_Session_Namespace('SubmitAmendment');
        $SubmitAmendment->params = $responseTBO;
        return $responseTBO;
    }

    public function GetAmendmentCharges($arrData = array())
    {
        if ($arrData) {
            $SearchParam = $arrData['apiTraceId'];
            $data_stringh = json_encode($arrData);
            //echo "<pre>"; print_r($data_stringh); exit; 
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_GETAMENDMENTCHARGES_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

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

            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $response['status']['success'];
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Charge Success" : "Flight Amen Charge Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $arrData], // Request
                    "udf1"         => $SearchParam,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }

            Zend_Session::namespaceUnset('AmendmentChargesSession');
            $AmendmentChargesSession = new Zend_Session_Namespace('AmendmentChargesSession');
            $AmendmentChargesSession->params = $response;  // store all serch result data to Session
            return $response;
        }
    }

    public function GetAmendmentChargesTBO($data)
    {
        $SearchParam = $data['apiTraceId'];
        $RequestType = $data['requestType'];
        $tokenId = $this->authenticateAPI($this->gtxagencysysid);

        $datah = array(
            "BookingId" => $data['bookingId'],
            "RequestType" => $RequestType,
            "BookingMode" => 5,
            "EndUserIp" => $_SERVER['REMOTE_ADDR'],
            "TokenId" => $tokenId['token'],
        );

        $cURL = FLIGHT_API_GET_CANCELLATION_CHARGE;
        $data_stringh = json_encode($datah);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $cURL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_stringh)
        ));
        $outputH = curl_exec($ch);
        $responseTBO = json_decode($outputH, true);
        if (FLIGHT_API_LOGS) {

            $ResponseStatus = $responseTBO['Response']['ResponseStatus'];
            $ErrorMessage = isset($responseTBO['Response']['Error']['ErrorMessage']) ? $responseTBO['Response']['Error']['ErrorMessage'] : '';

            $logParams = [
                "user_id"      => 1,
                "AgencySysId"      => $this->gtxagencysysid,
                "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Charge Success" : "Flight Amen Charge Failed",
                'error'        => $ErrorMessage,
                "text_udf"     => ['response' => $responseTBO], // Response
                "char_udf"     => ['request' => $datah], // Request
                "udf1"         => $SearchParam,
                "status"       => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
        }
        Zend_Session::namespaceUnset('AmendmentChargesSession');
        $AmendmentChargesSession = new Zend_Session_Namespace('AmendmentChargesSession');
        $AmendmentChargesSession->params = $responseTBO;
        return $responseTBO;
    }
    public function GetSubmitAmendment($arrData = array())
    {
        if ($arrData) {
            $SearchParam = $arrData['apiTraceId'];
            $data_stringh = json_encode($arrData);
            //echo "<pre>"; print_r($data_stringh); exit;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_SUBMITAMENDMENT_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            // echo"<pre>";print_r($outputH);die;
            $response = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {

                $ResponseStatus = $response['status']['success'];
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Submit Success" : "Flight Amen Submit Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $arrData], // Request
                    "udf1"         => $SearchParam,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }
            Zend_Session::namespaceUnset('SubmitAmendment');
            $SubmitAmendment = new Zend_Session_Namespace('SubmitAmendment');
            $SubmitAmendment->params = $response;  // store all serch result data to Session
            return $response;
        }
    }

    public function GetAmendmentDetails($arrData = array())
    {
        if ($arrData) {
            $SearchParam = $arrData['apiTraceId'];
            $data_stringh = json_encode($arrData);
            //echo "<pre>"; print_r($data_stringh); exit;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_AMENDMENTDETAILS_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

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

                $ResponseStatus = $response['status']['success'];
                $ErrorMessage = isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : '';

                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Details Success" : "Flight Amen Details Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $arrData], // Request
                    "udf1"         => $SearchParam,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }

            return $response;
        }
    }
    public function GetAmendmentDetailsTBO($arrData = array())
    {
        if ($arrData) {
            $SearchParam = $arrData['apiTraceId'];
            $tokenId = $this->authenticateAPI($this->gtxagencysysid);

            $datah = array(
                "ChangeRequestId" => $arrData['ChangeRequestId'],
                "EndUserIp" => $_SERVER['REMOTE_ADDR'],
                "TokenId" => $tokenId['token'],
            );
            $data_stringh = json_encode($datah);
            //echo "<pre>"; print_r($data_stringh); exit;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, FLIGHT_API_BOOKING_CHANGE_REQUEST_STATUS);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_stringh)
            ));
            $outputH = curl_exec($ch);
            $responseTBO = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {
                $ResponseStatus = $responseTBO['Response']['ResponseStatus'];
                $ErrorMessage = isset($responseTBO['Response']['Error']['ErrorMessage']) ? $responseTBO['Response']['Error']['ErrorMessage'] : '';
                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight Amen Details Success" : "Flight Amen Details Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $responseTBO], // Response
                    "char_udf"     => ['request' => $datah], // Request
                    "udf1"         => $SearchParam,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }

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

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

    function calculateMarkupTripJack($data)
    {
        $arrGTXMarkups = isset($data['getMarkup']['arrGTXMarkups']) ? $data['getMarkup']['arrGTXMarkups'] : [];
        $arrAgencyMarkups = isset($data['getMarkup']['arrAgencyMarkups']) ? $data['getMarkup']['arrAgencyMarkups'] : [];
        $arrApiServiceTax = isset($data['getMarkup']['arrApiServiceTax'][0]) ? $data['getMarkup']['arrApiServiceTax'][0]['Percentage'] : [];
        $intPublishedFare = isset($data['PublishedFare']) ? $data['PublishedFare'] : 0;
        $intOfferedFare = isset($data['OfferedFare']) ? $data['OfferedFare'] : 0;
        $intCommissionEarned = isset($data['intCommissionEarned']) ? $data['intCommissionEarned'] : 0;
        $intPLBEarned = isset($data['intPLBEarned']) ? $data['intPLBEarned'] : 0;
        $intIncentiveEarned = isset($data['intIncentiveEarned']) ? $data['intIncentiveEarned'] : 0;
        $intMemberCount = isset($data['intMemberCount']) ? $data['intMemberCount'] : 1;
        $intFlightRoute = isset($data['intFlightRoute']) ? $data['intFlightRoute'] : 1;
        $interNationalSearch = isset($data['interNationalSearch']) ? $data['interNationalSearch'] : 0;
        $commission = ($intPublishedFare - $intOfferedFare);
        // For GTX MarkUps...
        $intOfferedFareWithGTXCommision = 0;
        $totalGTXMarkUp = 0;
        if (count($arrGTXMarkups) > 0) {
            foreach ($arrGTXMarkups as $GTXMarkups) {
                $intGTXCurrencySysId = $GTXMarkups['Currency'];
                $intGTXMarkUpType = $GTXMarkups['MarkUpType'];
                $intGTXMarkUp = 0; //$GTXMarkups['MarkUp'];
                $totalGTXMarkUp += $intGTXMarkUp;
                if ($intGTXMarkUpType == 1) { // For Flat
                    $intGTXMarkUp = $intGTXMarkUp;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                } else { // For Percentage
                    $intGTXMarkUp = ($intOfferedFare * $intGTXMarkUp) / 100;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                }
            }
        } else {
            $intGTXMarkUp = 0;
            $intOfferedFareWithGTXCommision = $intOfferedFare + $intGTXMarkUp;
        }
        //For Agency MarkUps...
        $intCommission = 0;
        $totalAgencyMarkUp = 0;
        $intFareWithAgencyFixMarkUp = 0;
        $intAgencyCommisionEarnedFromAcutalCommision = 0;
        $intAgencyPLBEarnedFromAcutalPLB = 0;
        $intAgencyIncentiveEarnedFromAcutalIncentive = 0;
        if (count($arrAgencyMarkups) > 0) {
            foreach ($arrAgencyMarkups as $AgencyMarkups) {
                $intAgencyCurrencySysId = $AgencyMarkups['Currency'];
                $intAgencyMarkUp = $AgencyMarkups['StdMarkUpPer']; // Agency Fix Mark UP...
                $totalAgencyMarkUp += $intAgencyMarkUp;
                $intCommssionType = $AgencyMarkups['CommssionType']; // 2 For percentage
                $intCommssionVal = $AgencyMarkups['CommssionVal']; // Percntage Value For Agency Commision From Actual Commision Retuned From API...
                $intFareWithAgencyFixMarkUp += $intOfferedFareWithGTXCommision + $intAgencyMarkUp;
                if ($intCommssionType == 2) { // For Agency Commision In Percentage Only...
                    $intAgencyCommisionEarnedFromAcutalCommision    += (($intCommissionEarned * $intCommssionVal) / 100);
                    $intAgencyPLBEarnedFromAcutalPLB                += (($intPLBEarned * $intCommssionVal) / 100);
                    $intAgencyIncentiveEarnedFromAcutalIncentive    += (($intIncentiveEarned * $intCommssionVal) / 100);

                    $intCommission    += (($commission * $intCommssionVal) / 100);
                }
            }
        } else {
            $intFareWithAgencyFixMarkUp = $intOfferedFareWithGTXCommision;
            $intAgencyCommisionEarnedFromAcutalCommision = 0;
            $intAgencyPLBEarnedFromAcutalPLB = 0;
            $intAgencyIncentiveEarnedFromAcutalIncentive = 0;
        }
        //echo $intAgencyCommisionEarnedFromAcutalCommision.'=='.$intAgencyPLBEarnedFromAcutalPLB.'=='.$intAgencyIncentiveEarnedFromAcutalIncentive;
        $arrGSTOnGTXMarkUp = $this->calculateServiceTax($totalGTXMarkUp, $arrApiServiceTax);
        $intGSTOnGTXMarkUp = $arrGSTOnGTXMarkUp['serviceTaxAmount'];

        $arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
        $intGSTOnAgencyFixMarkUp = $arrGSTOnAgencyFixMarkUp['serviceTaxAmount'];

        $arrGSTOnAgencyCommisionEarned = $this->calculateServiceTax($intAgencyCommisionEarnedFromAcutalCommision, $arrApiServiceTax);
        $intGSTOnAgencyCommisionEarned = $arrGSTOnAgencyCommisionEarned['serviceTaxAmount'];

        $arrGSTOnAgencyPLBEarned = $this->calculateServiceTax($intAgencyPLBEarnedFromAcutalPLB, $arrApiServiceTax);
        $intGSTOnAgencyPLBEarned = $arrGSTOnAgencyPLBEarned['serviceTaxAmount'];

        $arrGSTOnAgencyIncentiveEarned = $this->calculateServiceTax($intAgencyIncentiveEarnedFromAcutalIncentive, $arrApiServiceTax);
        $intGSTOnAgencyIncentiveEarned = $arrGSTOnAgencyIncentiveEarned['serviceTaxAmount'];

        $intTotalEarningsForAgency = $intAgencyCommisionEarnedFromAcutalCommision + $intAgencyPLBEarnedFromAcutalPLB + $intAgencyIncentiveEarnedFromAcutalIncentive;

        $arrPriceAndMarkUps = array(
            "intOfferedFare" => $intOfferedFare,
            "intFareWithGTXMarkUp" => $intOfferedFareWithGTXCommision,
            "intFareWithAgencyFixMarkUp" => $intFareWithAgencyFixMarkUp,
            "intPublishFare" => ($intFareWithAgencyFixMarkUp + $intTotalEarningsForAgency + $intGSTOnGTXMarkUp + $intGSTOnAgencyFixMarkUp),
            "intCommissionEarned" => $intCommissionEarned,
            "intCommisionEarnedForAgency" => $intAgencyCommisionEarnedFromAcutalCommision,
            "intPLBEarned" => $intPLBEarned,
            "intPLBEarnedForAgency" => $intAgencyPLBEarnedFromAcutalPLB,
            "intIncentiveEarned" => $intIncentiveEarned,
            "intIncentiveEarnedForAgency" => $intAgencyIncentiveEarnedFromAcutalIncentive,
            "intTotalEarningsForAgency" => $intTotalEarningsForAgency,
            "intGTXMarkUp" => $intGTXMarkUp,
            "intAgencyFixMarkUp" => $intAgencyMarkUp,
            "intSTaxOnGTXMarkUp" => $intGSTOnGTXMarkUp,
            "intSTaxOnAgencyFixMarkUp" => $intGSTOnAgencyFixMarkUp,
            "intGSTOnAgencyCommisionEarned" => $intGSTOnAgencyCommisionEarned,
            "intGSTOnAgencyPLBEarned" => $intGSTOnAgencyPLBEarned,
            "intGSTOnAgencyIncentiveEarned" => $intGSTOnAgencyIncentiveEarned

        );
        return $arrPriceAndMarkUps;
        // echo '<pre>';print_r($commission + $intCommission);
        // echo '<pre>';print_r($intCommission);
        // echo '<pre>';print_r($intFareWithAgencyFixMarkUp);
        // echo '<pre>';print_r($intTotalEarningsForAgency);
        // echo '<pre>';print_r($data);

        // die;
    }
    function calculateMarkup($data, $review = 0)
    {
        $AddMarkup = isset($data['AddMarkup']) ? $data['AddMarkup'] : [];
        $markup_b2c = isset($AddMarkup['markup_b2c']) ? $AddMarkup['markup_b2c'] : 0;
        $arrGTXMarkups = isset($data['getMarkup']['arrGTXMarkups']) ? $data['getMarkup']['arrGTXMarkups'] : [];
        $arrAgencyMarkups = isset($data['getMarkup']['arrAgencyMarkups']) ? $data['getMarkup']['arrAgencyMarkups'] : [];
        $TaxSettingDetail = isset($data['getMarkup']['TaxSettingDetail']) ? $data['getMarkup']['TaxSettingDetail'] : [];
        $arrApiServiceTax = (isset($TaxSettingDetail['TaxPercentage']) && !empty($TaxSettingDetail['TaxPercentage'])) ? $TaxSettingDetail['TaxPercentage'] : 18;
        $TaxType = (isset($TaxSettingDetail['Tax']) && !empty($TaxSettingDetail['Tax'])) ? $TaxSettingDetail['Tax'] : 1;
        if ($TaxType == 2) {
            $arrApiServiceTax = 18;
        }
        //$arrApiServiceTax = isset($data['getMarkup']['arrApiServiceTax'][0]) ? $data['getMarkup']['arrApiServiceTax'][0]['Percentage'] : [];
        $intPublishedFare = isset($data['PublishedFare']) ? $data['PublishedFare'] : 0;
        $intOfferedFare = isset($data['OfferedFare']) ? $data['OfferedFare'] : 0;
        $intCommissionEarned = $TripjackCommission = isset($data['intCommissionEarned']) ? $data['intCommissionEarned'] : 0;
        $intPLBEarned = isset($data['intPLBEarned']) ? $data['intPLBEarned'] : 0;
        $TdsOnPLB = isset($data['TdsOnPLB']) ? str_replace('-', '', $data['TdsOnPLB']) : 0;
        $TripjackMarkup  = isset($data['MUFee']) ? $data['MUFee'] : 0;
        $intIncentiveEarned = isset($data['intIncentiveEarned']) ? $data['intIncentiveEarned'] : 0;
        $intMemberCount = isset($data['intMemberCount']) ? $data['intMemberCount'] : 1;
        $intFlightRoute = isset($data['intFlightRoute']) ? $data['intFlightRoute'] : 1;
        $interNationalSearch = isset($data['interNationalSearch']) ? $data['interNationalSearch'] : 0;
        $NetCommission = ($intCommissionEarned);

        $intOfferedFareWithGTXCommision = 0;
        // For GTX MarkUps... AddMarkup
        $totalGTXMarkUp = 0;
        if (count($arrGTXMarkups) > 0) {
            foreach ($arrGTXMarkups as $GTXMarkups) {
                $intGTXCurrencySysId = $GTXMarkups['Currency'];
                $intGTXMarkUpType = $GTXMarkups['MarkUpType'];
                $intGTXMarkUp = 0; //($GTXMarkups['MarkUp'] * $intMemberCount);
                $totalGTXMarkUp += $intGTXMarkUp;
                if ($intGTXMarkUpType == 1) { // For Flat
                    $intGTXMarkUp = $intGTXMarkUp;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                } else { // For Percentage
                    $intGTXMarkUp = ($intOfferedFare * $intGTXMarkUp) / 100;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                }
            }
        } else {
            $intGTXMarkUp = 0;
            $intOfferedFareWithGTXCommision = $intOfferedFare + $intGTXMarkUp;
        }

        $AdminComminAmount = 0;
        $totalAgencyMarkUp = 0;
        $TotalCommssionVal = 0;
        $intFareWithAgencyFixMarkUp = 0;
        if (count($arrAgencyMarkups) > 0) {
            foreach ($arrAgencyMarkups as $AgencyMarkups) {
                $intCommssionType = $AgencyMarkups['CommssionType']; // 2 For percentage
                $intCommssionVal = ($AgencyMarkups['CommssionVal']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
                $intAgencyMarkUp = ($AgencyMarkups['StdMarkUpPer'] * $intMemberCount); // Agency Fix Mark UP...
                $totalAgencyMarkUp += $intAgencyMarkUp;
                $TotalCommssionVal += $intCommssionVal;
                $intFareWithAgencyFixMarkUp += $intOfferedFareWithGTXCommision + $intAgencyMarkUp;
                if ($intCommssionType == 2) {
                    $AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
                }
            }
        }
        if ($interNationalSearch == 1 && $review == 0) {
            $totalAgencyMarkUp = ($totalAgencyMarkUp * $intFlightRoute);
            $intGTXMarkUp = ($intGTXMarkUp * $intFlightRoute);
            $markup_b2c = ($markup_b2c * $intFlightRoute);
        }
        $calculateReverseAdd = $this->calculateServiceTax($markup_b2c, $arrApiServiceTax);
        $AddiMarkup = $markup_b2c;
        $AddiaxOnMarkup = $calculateReverseAdd['serviceTaxAmount'];

        $calculateReverse = $this->calculateReverse($TripjackMarkup, $arrApiServiceTax);
        $apiMarkup = !empty($calculateReverse['NetPrice']) ? $calculateReverse['NetPrice'] : 0;
        $apiTaxOnMarkup = !empty($calculateReverse['TaxAmount']) ? $calculateReverse['TaxAmount'] : 0;
        $arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
        $intGSTOnAgencyFixMarkUp = ($arrGSTOnAgencyFixMarkUp['serviceTaxAmount'] +  $AddiaxOnMarkup + $apiTaxOnMarkup);

        $totalAgencyMarkUp = ($totalAgencyMarkUp + $AddiMarkup + $apiMarkup);
        $intTotalGST = $intGSTOnAgencyFixMarkUp;

        $CostToCustomer = ($intOfferedFare + $totalAgencyMarkUp + $intGSTOnAgencyFixMarkUp + $intGTXMarkUp + $AdminComminAmount);
        $intAgencyCommisionEarned = ($totalAgencyMarkUp + $AdminComminAmount);
        $CostToCompany = ($CostToCustomer - $intAgencyCommisionEarned);

        $CommisionPass = ($NetCommission - $AdminComminAmount);

        // if($TaxType == 2){
        //     $arrApiServiceTax = (isset($TaxSettingDetail['TaxPercentage']) && !empty($TaxSettingDetail['TaxPercentage'])) ? $TaxSettingDetail['TaxPercentage'] : 0;
        //     $CalAgencyMarkUp = $this->calculateServiceTax($CostToCustomer, $arrApiServiceTax);
        //     $AgencyMarkUp = $CalAgencyMarkUp['serviceTaxAmount'];
        //     $totalAgencyMarkUp = ($totalAgencyMarkUp + $AgencyMarkUp);
        //     $CostToCustomer = ($CostToCustomer + $AgencyMarkUp);
        // }
        $dataArr = array(
            'apiMarkup' => 0, //round($apiMarkup, 2),
            'apiTaxOnMarkup' => 0, //round($apiTaxOnMarkup, 2),
            'IntNetCommission' => round($NetCommission, 2), // GTX Agency Commission Retain %
            'IntCommissionValInPercentage' => round($TotalCommssionVal, 2), // GTX Agency Commission Retain %
            'IntCommission' => round($AdminComminAmount, 2), // GTX agency Comm in Amount
            'IntAgencyFixMarkUp' => round($totalAgencyMarkUp, 2),
            'IntTaxOnAgencyFixMarkUp' => round($intGSTOnAgencyFixMarkUp, 2),
            "intGTXMarkUp" => round($intGTXMarkUp, 2),
            "intSTaxOnGTXMarkUp" => 0,
            "intTotalGST" => round($intTotalGST, 2),
            "PublishFare" => round($CostToCustomer, 2),
            "CostToCustomer" => round($CostToCustomer, 2),
            "BaseFareCal" => round(($CostToCustomer - $intAgencyCommisionEarned), 2),
            "intCommisionEarnedForAgency" => round($intAgencyCommisionEarned, 2),
            "CostToCompany" => round($CostToCompany, 2),
            "intOfferedFare" => $intOfferedFare,
            "intPublishFare" => $intPublishedFare,
            "TripjackMarkup" => $TripjackMarkup,
            "TripjackCommission" => $TripjackCommission,
            "TripjackTDS" => $TdsOnPLB,
            "AddiMarkup" => $AddiMarkup,
            "CommisionPass" => $CommisionPass,
            "AddiTaxOnMarkup" => $AddiaxOnMarkup,
            "TaxSettingDetail" => $TaxSettingDetail,
            "IntAdddimarkup" => (float)$markup_b2c,
        );
        //echo '<pre>';print_r(($data));echo '</pre>';

        if ($interNationalSearch == 1) {
            // $dataArr['intGTXMarkUp'] = (($dataArr['intGTXMarkUp']) * $intFlightRoute);
            // $dataArr['IntAgencyFixMarkUp'] = round(($totalAgencyMarkUp) * $intFlightRoute,2);
            // $dataArr['IntTaxOnAgencyFixMarkUp'] = (($dataArr['IntTaxOnAgencyFixMarkUp']) * $intFlightRoute);
        }

        return $dataArr;
    }

    function calculateMarkupTBO($data)
    {
        $AddMarkup = isset($data['AddMarkup']) ? $data['AddMarkup'] : [];
        $markup_b2c = isset($AddMarkup['markup_b2c']) ? $AddMarkup['markup_b2c'] : 0;
        $arrGTXMarkups = isset($data['getMarkup']['arrGTXMarkups']) ? $data['getMarkup']['arrGTXMarkups'] : [];
        $arrAgencyMarkups = isset($data['getMarkup']['arrAgencyMarkups']) ? $data['getMarkup']['arrAgencyMarkups'] : [];
        $TaxSettingDetail = isset($data['getMarkup']['TaxSettingDetail']) ? $data['getMarkup']['TaxSettingDetail'] : [];
        $arrApiServiceTax = (isset($TaxSettingDetail['TaxPercentage']) && !empty($TaxSettingDetail['TaxPercentage'])) ? $TaxSettingDetail['TaxPercentage'] : 18;
        //$arrApiServiceTax = isset($data['getMarkup']['arrApiServiceTax'][0]) ? $data['getMarkup']['arrApiServiceTax'][0]['Percentage'] : [];
        $intPublishedFare = isset($data['PublishedFare']) ? $data['PublishedFare'] : 0;
        $intOfferedFare = isset($data['OfferedFare']) ? $data['OfferedFare'] : 0;
        $intCommissionEarned = isset($data['intCommissionEarned']) ? $data['intCommissionEarned'] : 0;
        $intPLBEarned = isset($data['intPLBEarned']) ? $data['intPLBEarned'] : 0;
        $intIncentiveEarned = isset($data['intIncentiveEarned']) ? $data['intIncentiveEarned'] : 0;
        $intMemberCount = isset($data['intMemberCount']) ? $data['intMemberCount'] : 1;
        $intFlightRoute = isset($data['intFlightRoute']) ? $data['intFlightRoute'] : 1;
        $interNationalSearch = isset($data['interNationalSearch']) ? $data['interNationalSearch'] : 0;
        $TdsOnPLB = isset($data['TdsOnPLB']) ? (float)$data['TdsOnPLB'] : 0;
        $commission = ($intPublishedFare - $intOfferedFare);
        // For GTX MarkUps...
        $intOfferedFareWithGTXCommision = 0;
        $totalGTXMarkUp = 0;
        if (count($arrGTXMarkups) > 0) {
            foreach ($arrGTXMarkups as $GTXMarkups) {
                $intGTXCurrencySysId = $GTXMarkups['Currency'];
                $intGTXMarkUpType = $GTXMarkups['MarkUpType'];
                $intGTXMarkUp = 0; //$GTXMarkups['MarkUp'];
                $totalGTXMarkUp += $intGTXMarkUp;
                if ($intGTXMarkUpType == 1) { // For Flat
                    $intGTXMarkUp = $intGTXMarkUp;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                } else { // For Percentage
                    $intGTXMarkUp = ($intOfferedFare * $intGTXMarkUp) / 100;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                }
            }
        } else {
            $intGTXMarkUp = 0;
            $intOfferedFareWithGTXCommision = $intOfferedFare + $intGTXMarkUp;
        }
        // For Agency MarkUps...
        $intCommission = 0;
        $totalAgencyMarkUp = 0;
        $intFareWithAgencyFixMarkUp = 0;
        $intAgencyCommisionEarnedFromAcutalCommision = 0;
        $intAgencyPLBEarnedFromAcutalPLB = 0;
        $intAgencyIncentiveEarnedFromAcutalIncentive = 0;
        if (count($arrAgencyMarkups) > 0) {
            foreach ($arrAgencyMarkups as $AgencyMarkups) {
                $intAgencyCurrencySysId = $AgencyMarkups['Currency'];
                $intAgencyMarkUp = $AgencyMarkups['StdMarkUpPer']; // Agency Fix Mark UP...
                $totalAgencyMarkUp += $intAgencyMarkUp;
                $intCommssionType = $AgencyMarkups['CommssionType']; // 2 For percentage
                $intCommssionVal = $AgencyMarkups['CommssionVal']; // Percntage Value For Agency Commision From Actual Commision Retuned From API...
                $intFareWithAgencyFixMarkUp += $intOfferedFareWithGTXCommision + $intAgencyMarkUp;
                if ($intCommssionType == 2) { // For Agency Commision In Percentage Only...
                    $intAgencyCommisionEarnedFromAcutalCommision    += (($intCommissionEarned * $intCommssionVal) / 100);
                    $intAgencyPLBEarnedFromAcutalPLB                += (($intPLBEarned * $intCommssionVal) / 100);
                    $intAgencyIncentiveEarnedFromAcutalIncentive    += (($intIncentiveEarned * $intCommssionVal) / 100);

                    $intCommission    += (($commission * $intCommssionVal) / 100);
                }
            }
        } else {
            $intFareWithAgencyFixMarkUp = $intOfferedFareWithGTXCommision;
            $intAgencyCommisionEarnedFromAcutalCommision = 0;
            $intAgencyPLBEarnedFromAcutalPLB = 0;
            $intAgencyIncentiveEarnedFromAcutalIncentive = 0;
        }

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

        //intCommisionEarnedForAgency echo $intAgencyCommisionEarnedFromAcutalCommision.'=='.$intAgencyPLBEarnedFromAcutalPLB.'=='.$intAgencyIncentiveEarnedFromAcutalIncentive;
        $arrGSTOnGTXMarkUp = $this->calculateServiceTax($totalGTXMarkUp, $arrApiServiceTax);
        $intGSTOnGTXMarkUp = $arrGSTOnGTXMarkUp['serviceTaxAmount'];

        $arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
        $intGSTOnAgencyFixMarkUp = $arrGSTOnAgencyFixMarkUp['serviceTaxAmount'] + $AddiaxOnMarkup;

        $arrGSTOnAgencyCommisionEarned = $this->calculateServiceTax($intAgencyCommisionEarnedFromAcutalCommision, $arrApiServiceTax);
        $intGSTOnAgencyCommisionEarned = $arrGSTOnAgencyCommisionEarned['serviceTaxAmount'];

        $arrGSTOnAgencyPLBEarned = $this->calculateServiceTax($intAgencyPLBEarnedFromAcutalPLB, $arrApiServiceTax);
        $intGSTOnAgencyPLBEarned = $arrGSTOnAgencyPLBEarned['serviceTaxAmount'];

        $arrGSTOnAgencyIncentiveEarned = $this->calculateServiceTax($intAgencyIncentiveEarnedFromAcutalIncentive, $arrApiServiceTax);
        $intGSTOnAgencyIncentiveEarned = $arrGSTOnAgencyIncentiveEarned['serviceTaxAmount'];

        $intTotalEarningsForAgency = $intAgencyCommisionEarnedFromAcutalCommision + $intAgencyPLBEarnedFromAcutalPLB + $intAgencyIncentiveEarnedFromAcutalIncentive + $TdsOnPLB;
        $CommisionPass = ($intCommissionEarned - $intAgencyCommisionEarnedFromAcutalCommision);
        $arrPriceAndMarkUps = array(
            "intOfferedFare" => $intOfferedFare,
            "intFareWithGTXMarkUp" => $intOfferedFareWithGTXCommision,
            "intFareWithAgencyFixMarkUp" => $intFareWithAgencyFixMarkUp,
            "intPublishFare" => ($intFareWithAgencyFixMarkUp + $intTotalEarningsForAgency + $intGSTOnGTXMarkUp + $intGSTOnAgencyFixMarkUp),
            "intCommssionPercentage" => $intCommssionVal,
            "intCommissionEarned" => $intCommissionEarned,
            "intCommisionEarnedForAgency" => $intAgencyCommisionEarnedFromAcutalCommision,
            "intPLBEarned" => $intPLBEarned,
            "intPLBEarnedForAgency" => $intAgencyPLBEarnedFromAcutalPLB,
            "intIncentiveEarned" => $intIncentiveEarned,
            "intIncentiveEarnedForAgency" => $intAgencyIncentiveEarnedFromAcutalIncentive,
            "intTotalEarningsForAgency" => $intTotalEarningsForAgency,
            "intGTXMarkUp" => $intGTXMarkUp,
            "intAgencyFixMarkUp" => $intAgencyMarkUp + $AddiMarkup,
            "intSTaxOnGTXMarkUp" => $intGSTOnGTXMarkUp,
            "intSTaxOnAgencyFixMarkUp" => $intGSTOnAgencyFixMarkUp,

            "intGSTOnAgencyCommisionEarned" => $intGSTOnAgencyCommisionEarned,
            "intGSTOnAgencyPLBEarned" => $intGSTOnAgencyPLBEarned,
            "intGSTOnAgencyIncentiveEarned" => $intGSTOnAgencyIncentiveEarned,
            "CommisionPass" => $CommisionPass,
            "TripjackTDS" => $TdsOnPLB,
            "TaxSettingDetail" => $TaxSettingDetail

        );
        return $arrPriceAndMarkUps;
    }

    function calculateMarkupInt($data)
    {
        $arrGTXMarkups = isset($data['getMarkup']['arrGTXMarkups']) ? $data['getMarkup']['arrGTXMarkups'] : [];
        $arrAgencyMarkups = isset($data['getMarkup']['arrAgencyMarkups']) ? $data['getMarkup']['arrAgencyMarkups'] : [];
        $arrApiServiceTax = isset($data['getMarkup']['arrApiServiceTax'][0]) ? $data['getMarkup']['arrApiServiceTax'][0]['Percentage'] : [];
        $intPublishedFare = isset($data['PublishedFare']) ? $data['PublishedFare'] : 0;
        $intOfferedFare = isset($data['OfferedFare']) ? $data['OfferedFare'] : 0;
        $intCommissionEarned = $TripjackCommission = isset($data['intCommissionEarned']) ? $data['intCommissionEarned'] : 0;
        $intPLBEarned = isset($data['intPLBEarned']) ? $data['intPLBEarned'] : 0;
        $TdsOnPLB = isset($data['TdsOnPLB']) ? str_replace('-', '', $data['TdsOnPLB']) : 0;
        $TripjackMarkup  = isset($data['MUFee']) ? $data['MUFee'] : 0;
        $intIncentiveEarned = isset($data['intIncentiveEarned']) ? $data['intIncentiveEarned'] : 0;
        $intMemberCount = isset($data['intMemberCount']) ? $data['intMemberCount'] : 1;
        $intFlightRoute = 1; //isset($data['intFlightRoute']) ? $data['intFlightRoute'] : 1;
        $interNationalSearch = isset($data['interNationalSearch']) ? $data['interNationalSearch'] : 0;
        $NetCommission = ($intCommissionEarned);

        $intOfferedFareWithGTXCommision = 0;
        // For GTX MarkUps...
        $totalGTXMarkUp = 0;
        if (count($arrGTXMarkups) > 0) {
            foreach ($arrGTXMarkups as $GTXMarkups) {
                $intGTXCurrencySysId = $GTXMarkups['Currency'];
                $intGTXMarkUpType = $GTXMarkups['MarkUpType'];
                $intGTXMarkUp = 0; //($GTXMarkups['MarkUp'] * $intMemberCount);
                $totalGTXMarkUp += $intGTXMarkUp;
                if ($intGTXMarkUpType == 1) { // For Flat
                    $intGTXMarkUp = $intGTXMarkUp;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                } else { // For Percentage
                    $intGTXMarkUp = ($intOfferedFare * $intGTXMarkUp) / 100;
                    $intOfferedFareWithGTXCommision += $intOfferedFare + $intGTXMarkUp;
                }
            }
        } else {
            $intGTXMarkUp = 0;
            $intOfferedFareWithGTXCommision = $intOfferedFare + $intGTXMarkUp;
        }

        $AdminComminAmount = 0;
        $totalAgencyMarkUp = 0;
        $TotalCommssionVal = 0;
        $intFareWithAgencyFixMarkUp = 0;
        if (count($arrAgencyMarkups) > 0) {
            foreach ($arrAgencyMarkups as $AgencyMarkups) {
                $intCommssionType = $AgencyMarkups['CommssionType']; // 2 For percentage
                $intCommssionVal = ($AgencyMarkups['CommssionVal']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
                $intAgencyMarkUp = ($AgencyMarkups['StdMarkUpPer'] * $intMemberCount); // Agency Fix Mark UP...
                $totalAgencyMarkUp += $intAgencyMarkUp;
                $TotalCommssionVal += $intCommssionVal;
                $intFareWithAgencyFixMarkUp += $intOfferedFareWithGTXCommision + $intAgencyMarkUp;
                if ($intCommssionType == 2) {
                    $AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
                }
            }
        }
        if ($interNationalSearch == 1) {
            $totalAgencyMarkUp = ($totalAgencyMarkUp * $intFlightRoute);
            $intGTXMarkUp = ($intGTXMarkUp * $intFlightRoute);
        }
        $calculateReverse = $this->calculateReverse($TripjackMarkup, $arrApiServiceTax);
        $apiMarkup = $calculateReverse['NetPrice'];
        $apiTaxOnMarkup = $calculateReverse['TaxAmount'];
        $arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
        $intGSTOnAgencyFixMarkUp = $arrGSTOnAgencyFixMarkUp['serviceTaxAmount'];
        $intTotalGST = $intGSTOnAgencyFixMarkUp + $apiTaxOnMarkup;

        $CostToCustomer = ($intOfferedFare + $apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $intGSTOnAgencyFixMarkUp + $intGTXMarkUp + $AdminComminAmount);
        $intAgencyCommisionEarned = ($apiMarkup + $totalAgencyMarkUp + $AdminComminAmount);
        $CostToCompany = ($CostToCustomer - $intAgencyCommisionEarned);
        $dataArr = array(
            'apiMarkup' => round($apiMarkup, 2),
            'apiTaxOnMarkup' => round($apiTaxOnMarkup, 2),
            'IntNetCommission' => round($NetCommission, 2), // GTX Agency Commission Retain %
            'IntCommissionValInPercentage' => round($TotalCommssionVal, 2), // GTX Agency Commission Retain %
            'IntCommission' => round($AdminComminAmount, 2), // GTX agency Comm in Amount
            'IntAgencyFixMarkUp' => round($totalAgencyMarkUp, 2),
            'IntTaxOnAgencyFixMarkUp' => round($intGSTOnAgencyFixMarkUp, 2),
            "intGTXMarkUp" => round($intGTXMarkUp, 2),
            "intSTaxOnGTXMarkUp" => 0,
            "intTotalGST" => round($intTotalGST, 2),
            "PublishFare" => round($CostToCustomer, 2),
            "CostToCustomer" => round($CostToCustomer, 2),
            "BaseFareCal" => round(($CostToCustomer - $intAgencyCommisionEarned), 2),
            "intCommisionEarnedForAgency" => round($intAgencyCommisionEarned, 2),
            "CostToCompany" => round($CostToCompany, 2),
            "intOfferedFare" => $intOfferedFare,
            "intPublishFare" => $intPublishedFare,
            "TripjackMarkup" => $TripjackMarkup,
            "TripjackCommission" => $TripjackCommission,
            "TripjackTDS" => $TdsOnPLB,
        );
        //echo '<pre>';print_r(($data));echo '</pre>';

        if ($interNationalSearch == 1) {
            // $dataArr['intGTXMarkUp'] = (($dataArr['intGTXMarkUp']) * $intFlightRoute);
            // $dataArr['IntAgencyFixMarkUp'] = round(($totalAgencyMarkUp) * $intFlightRoute,2);
            // $dataArr['IntTaxOnAgencyFixMarkUp'] = (($dataArr['IntTaxOnAgencyFixMarkUp']) * $intFlightRoute);
        }

        return $dataArr;
        // echo '<pre>';print_r($commission + $intCommission);
        // echo '<pre>';print_r($intCommission);
        // echo '<pre>';print_r($intFareWithAgencyFixMarkUp);
        // echo '<pre>';print_r($intTotalEarningsForAgency);
        // echo '<pre>';print_r($data);

        // die;
    }


    public function getArrivalDepartureIndianFormat($string)
    {
        if (empty($string))
            return '';

        $arr = explode(" ", $string);

        $date = new DateTime($arr[0]);

        return $date->format('d M Y') . ' ' . substr(@$arr[1], 0, 5);
    }

    public function getTimeFromApiString($string)
    {
        if (empty($string))
            return '';

        $arr = explode("T", $string);

        $date = new DateTime($arr[0]);

        return substr(@$arr[1], 0, 5);
    }

    public function CalculateHoursMinutes($DepTime, $ArrTime)
    {
        if (empty($DepTime))
            return '';
        if (empty($ArrTime))
            return '';

        $date1 = new DateTime($DepTime . ':00');
        $date2 = new DateTime($ArrTime . ':00');

        $diff = $date2->diff($date1);

        $hours = $diff->h;
        $minutes = $diff->i;
        $hours = $hours + ($diff->days * 24);
        $travelTime = $hours . 'h ' . $minutes . 'm';
        return $travelTime;
        // $Darr = explode("T", $DepTime);
        // $Ddate = new DateTime($Darr[0]);

        // $Aarr = explode("T", $ArrTime);
        // $Adate = new DateTime($Aarr[0]);

        // $dep = $Ddate->format('Y-m-d') . ' ' . substr(@$Darr[1], 0, 5);
        // $arr = $Adate->format('Y-m-d') . ' ' . substr(@$Aarr[1], 0, 5);

        // $t1 = strtotime($dep);
        // $t2 = strtotime($arr);
        // $delta_T = ($t2 - $t1);
        // $day = round(($delta_T % 604800) / 86400);
        // $hours = round((($delta_T % 604800) % 86400) / 3600);
        // $minutes = round(((($delta_T % 604800) % 86400) % 3600) / 60);
        // $sec = round((((($delta_T % 604800) % 86400) % 3600) % 60));
        // $hours = ($hours > 9) ? $hours : '0' . $hours;
        // $minutes = ($minutes > 9) ? $minutes : '0' . $minutes;
        // $travelTime = $hours . 'h ' . $minutes . 'm';

        // return $travelTime;
    }
    public function MinutesToHours($minutes)
    {
        if ($minutes) {
            $hours = floor($minutes / 60);
            $min = $minutes - ($hours * 60);
            $LAYOVERTime = $hours . "h " . $min . 'm';
            return $LAYOVERTime;
        }
    }
    public function getDynamicPriceSlots($minPrice = NULL, $maxPrice = NULL)
    {

        if (!empty($minPrice) && !empty($maxPrice)) {
            $intMinPrice = round($minPrice);
            $intMaxPrice = round($maxPrice);
        } else {
            $intMinPrice = round(min($arrAirFare));
            $intMaxPrice = round(max($arrAirFare));
        }


        $intStartRage = floor($intMinPrice / 100) * 100;
        $intEndRage = floor($intMaxPrice / 100) * 100;

        $rangeDifference = $intEndRage - $intStartRage;

        $intTotalSlots = 4;
        $intDifference = $rangeDifference / $intTotalSlots;
        $intDifference = floor($intDifference / 100) * 100;


        $base = $rangeDifference / $intTotalSlots;

        $arr = array();
        $minStartRange = $intStartRage;
        $arr[] = "0-" . $intStartRage;
        for ($i = 1; $i <= $intTotalSlots; $i++) {

            $baseAmount = round($i * $base);
            $baseAmount = floor($baseAmount / 100) * 100;
            //if($i > 1){
            $intNewUpRange = $baseAmount + $intDifference;
            $arr[] = $minStartRange . "-" . ($intNewUpRange - 1);

            $minStartRange = $intNewUpRange;
            //}
        }
        $arr[] = $minStartRange . "-" . ($intNewUpRange);
        return $arr;
    }

    function encrypt($sData, $secretKey)
    {
        $sResult = '';
        for ($i = 0; $i < strlen($sData); $i++) {
            $sChar = substr($sData, $i, 1);
            $sKeyChar = substr($secretKey, ($i % strlen($secretKey)) - 1, 1);
            $sChar = chr(ord($sChar) + ord($sKeyChar));
            $sResult .= $sChar;
        }
        return $this->encode_base64($sResult);
    }

    function decrypt($sData, $secretKey)
    {
        $sResult = '';
        $sData = $this->decode_base64($sData);
        for ($i = 0; $i < strlen($sData); $i++) {
            $sChar = substr($sData, $i, 1);
            $sKeyChar = substr($secretKey, ($i % strlen($secretKey)) - 1, 1);
            $sChar = chr(ord($sChar) - ord($sKeyChar));
            $sResult .= $sChar;
        }
        return $sResult;
    }

    function encode_base64($sData)
    {
        $sBase64 = base64_encode($sData);
        return str_replace('=', '', strtr($sBase64, '+/', '-_'));
    }

    function decode_base64($sData)
    {
        $sBase64 = strtr($sData, '-_', '+/');
        return base64_decode($sBase64 . '==');
    }
    function GetAgencyCurrency($gtxagencysysid)
    {
        try {
            $apiDataIV = array(
                "AgencySysId" => $gtxagencysysid,
                "SecurityKey" => SECURITYKEY
            );
            $curl_IV = curl_init(API_GET_IV_KEY);
            curl_setopt($curl_IV, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl_IV, CURLOPT_POSTFIELDS, http_build_query($apiDataIV));
            curl_setopt($curl_IV, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_IV, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_IV, CURLOPT_TIMEOUT, 300);
            $responseIV = curl_exec($curl_IV);
            curl_close($curl_IV);
            //
            $IVData   = Zend_Json::decode($responseIV, true);
            $apiData = array(
                "AgencySysId" => $gtxagencysysid,
            );
            $curl_p = curl_init(API_AGENCY_CURRENCY_RATE);
            curl_setopt($curl_p, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl_p, CURLOPT_POSTFIELDS, http_build_query($apiData));
            curl_setopt($curl_p, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_p, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_p, CURLOPT_TIMEOUT, 300);
            $response_pro = curl_exec($curl_p);
            curl_close($curl_p);
            $data   = Zend_Json::decode($response_pro, true);
            //$agencyData = new Travel_Model_Encrytion($data['Message'], $apiDataIV['SecurityKey'], $IVData['Message']);

            // echo '<pre>';
            // print_r($data);
            //echo '<pre>';print_r($data);
            //echo '<pre>';print_r(Zend_Json::decode($agencyData->decrypt(),true));
            die('wait');
        } catch (Exception $error) {
            $this->view->error_msg = $error->getMessage();
            die;
        }
    }

    function is_valid_gstin($gstin)
    {
        //$regex = "/^([0][1-9]|[1-2][0-9]|[3][0-5])([a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9a-zA-Z]{1}[zZ]{1}[0-9a-zA-Z]{1})+$/";
        $regex = "/[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9a-zA-Z]{1}/";
        return preg_match($regex, $gstin);
    }

    public function GetSeatMapFlightsTripJack($arrData = array())
    {
        if ($arrData) {
            $FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
            $logFile = $FlightSearchLogFile->params;
            $datah = array(
                'bookingId' => $arrData['bookingId'],
            );

            $data_stringh = json_encode($datah);
            //echo"<pre>";print_r(TRIPJACK_FL_API_SEAT_URL);die;    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, TRIPJACK_FL_API_SEAT_URL);
            curl_setopt($ch, CURLOPT_ENCODING, "gzip");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Accept-Encoding: gzip',
                'apikey:' . APIKEY,
                'Content-Length: ' . strlen($data_stringh)
            ));

            $outputH = curl_exec($ch);
            if ($this->gtxagencysysid == '12208') {
                // echo "<pre>";
                // print_r(TRIPJACK_FL_API_SEAT_URL);
                // echo "<pre>";
                // print_r($outputH);
                // die;
            }

            $response = json_decode($outputH, true);
            if (FLIGHT_API_LOGS) {

                //Write Request Logs starts...
                $strFilePath = "flight/FlightSeat/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_Seat_request.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
                //Write Request Logs starts...
                //Write Request Logs starts...
                $strFilePath = "flight/FlightSeat/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_Seat_response.json";
                Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
                //Write Request Logs starts...
            }
            Zend_Session::namespaceUnset('FlightSeatSession');
            $FlightSeatSession = new Zend_Session_Namespace('FlightSeatSession');
            $FlightSeatSession->params = $response;  // store all serch result data to Session
            return $response;
        }
    }

    function getAgencySupplierUserData($apiData)
    {
        if ($apiData) {
            $url = $this->gtxBtoBsite . '/webservice/agency/get-booking-agency-supplier/';
            $apiDataIV = $apiData;
            $curl_IV = curl_init($url);
            curl_setopt($curl_IV, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl_IV, CURLOPT_POSTFIELDS, http_build_query($apiDataIV));
            curl_setopt($curl_IV, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_IV, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_IV, CURLOPT_TIMEOUT, 300);
            $responseIV = curl_exec($curl_IV);
            curl_close($curl_IV);
            return Zend_Json::decode($responseIV, true);
        } else {
            return 'Bad request';
        }
    }

    function getAgencyData($gtxagencysysid)
    {
        if ($gtxagencysysid) {
            $apiDataIV = array(
                "AgencySysId" => $gtxagencysysid,
                "SecurityKey" => SECURITYKEY //'AE54AF70-3DC8-431B-BED1-FB8A92CC2FAE'
            );
            // echo '<pre>';print_r($apiDataIV); die;
            $curl_IV = curl_init(API_GET_IV_KEY);
            curl_setopt($curl_IV, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl_IV, CURLOPT_POSTFIELDS, http_build_query($apiDataIV));
            curl_setopt($curl_IV, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_IV, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_IV, CURLOPT_TIMEOUT, 300);
            $responseIV = curl_exec($curl_IV);
            curl_close($curl_IV);
            // echo '<pre>';print_r(API_GET_IV_KEY);
            // echo '<pre>';print_r($responseIV);die('hbhgvgvghvgh');
            $apiData = array(
                "AgencySysId" => $gtxagencysysid,
            );

            $curl_p = curl_init(API_GET_AGENCY_DATA);
            curl_setopt($curl_p, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl_p, CURLOPT_POSTFIELDS, http_build_query($apiData));
            curl_setopt($curl_p, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_p, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_p, CURLOPT_TIMEOUT, 300);
            $response_pro = curl_exec($curl_p);
            curl_close($curl_p);
            // if ($gtxagencysysid == '69640') {
            //     echo '<pre>';print_r($apiData);
            //     echo '<pre>';print_r(API_GET_AGENCY_DATA);
            //     echo '<pre>';print_r($responseIV);
            //     echo '<pre>';print_r($response_pro);die;
            // }

            $IVData   = Zend_Json::decode($responseIV, true);
            $data   = Zend_Json::decode($response_pro, true);
            $agencyData = new Travel_Model_Encrytion($data['Message'], $apiDataIV['SecurityKey'], $IVData['Message']);
            return Zend_Json::decode($agencyData->decrypt(), true);
            // echo '<pre>';print_r(Zend_Json::decode($agencyData->decrypt(),true));
            // die('wait');
        } else {
            return 'Bad request';
        }
    }

    public function getSalutation()
    {
        $select = $this->db->select()->from("tbl_salutation", ['id', 'Title', 'Gender_Id', 'Gender']);
        $select->where("IsMarkForDel=?", 0);
        $select->order("id", 'ASC');
        $result = $this->db->fetchAll($select);
        return $result;
    }
    public function getSalutationByid($id)
    {
        $select = $this->db->select()->from("tbl_salutation", ['id', 'Title', 'Gender_Id', 'Gender']);
        $select->where("id=?", "$id");
        $select->where("IsMarkForDel=?", 0);
        $select->order("id", 'ASC');
        $result = $this->db->fetchRow($select);
        return $result;
    }

    public function getAdditionalMarkup()
    {
        if ($this->IsSeriesFare == 1) {
            $select = $this->db->select()->from("tbl_manage_fare", ['id', 'faretype', 'faretype_rename as fareIdentifier', 'markup_b2c', 'markup_b2b', 'showhide_b2b', 'showhide_b2c', 'ApiRoundTrip', 'remarks', 'IsSeriesFareAllow']);
        } else {
            $select = $this->db->select()->from("tbl_manage_fare", ['id', 'faretype', 'faretype_rename as fareIdentifier', 'markup_b2c', 'markup_b2b', 'showhide_b2b', 'showhide_b2c', 'ApiRoundTrip', 'remarks']);
        }
        // echo"<pre>";print_r($select);die();
        $select->where("status=?", 1);
        $select->order("id", 'ASC');
        $result = $this->db->fetchAll($select);

        $finalArr = [];
        $faretypeArr = [];
        $ApiRoundTrip = isset($result[0]['ApiRoundTrip']) ? $result[0]['ApiRoundTrip'] : 7;
        if ($this->IsSeriesFare == 1) {
            $IsSeriesFareAllow = isset($result[0]['IsSeriesFareAllow']) ? $result[0]['IsSeriesFareAllow'] : 0;
        } else {
            $IsSeriesFareAllow = 0;
        }
        if ($result) {
            foreach ($result as $key => $value) {
                $finalArr[strtoupper($value['faretype'])] = $value;
                $finalArr[strtoupper($value['faretype'])]['faretype'] = strtoupper($value['faretype']);
                if ($value['showhide_b2c'] == 1) {
                    $faretypeArr[] = strtoupper($value['faretype']);
                }
            }
        }
        return ['finalArr' => $finalArr, 'faretypeArr' => $faretypeArr, 'ApiRoundTrip' => $ApiRoundTrip, 'IsSeriesFareAllow' => $IsSeriesFareAllow];
    }

    public function getMarkup($intCountryCode)
    {
        if ($intCountryCode) {
            $this->postFields = "";
            $this->postFields .= "&AgencySysId=$this->gtxagencysysid";
            $this->postFields .= "&AgentSysId=$this->gtxagentsysid";
            $this->postFields .= "&intCountryCode=$intCountryCode";
            $this->postFields .= "&PlanType=2";
            $model = new Gtxwebservices_Model_Webservices();
            //echo"<pre>";print_r($this->postFields);exit;
            $result = $model->getMarkupAndServiceTax($this->postFields);
            $response = json_decode($result, true);
            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid country code');
            return ($data);
        }
    }

    public function couponApply($data)
    {
        if ($data) {
            $COUPON_CODE_API = "https://api.hellogtx.com/api/v1/coupon/coupons/";
            $apiData = array(
                "AgencySysId" => $this->gtxagencysysid,
                "SecurityKey" => SECURITYKEY,
                "DiscountCode" => $data['couponval'],
                "CriteriaValue" => 0,
                "CreateDate" => date('Y-m-d'),
                "ServiceFee" => 0,
            );
            echo "<pre>";
            print_r($apiData);
            $curl_IV = curl_init($COUPON_CODE_API);
            curl_setopt($curl_IV, CURLOPT_POST, true);
            curl_setopt($curl_IV, CURLOPT_POSTFIELDS, http_build_query($apiData));
            curl_setopt($curl_IV, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_IV, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_IV, CURLOPT_TIMEOUT, 300);
            $responseIV = curl_exec($curl_IV);
            curl_close($curl_IV);

            //$url = $COUPON_CODE_API . '?SecurityKey=' . $SecurityKey . '&DiscountCode=' . $DiscountCode . '&CriteriaValue=' . $CriteriaValue . '&CreateDate=' . $CreateDate . '&ServiceFee=' . $ServiceFee;

            echo "<pre>";
            print_r($responseIV);
            exit;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }
    public function InvoiceCreate($data, $BookingData)
    {
        if ($data) {
            $AirlineName = $BookingData[0]['AirlineName'];
            $TotalFlightMembers = $BookingData[0]['TotalFlightMembers'];
            $JourneyType = $BookingData[0]['JourneyType'];
            $SourceAirportCode = $BookingData[0]['SourceAirportCode'];
            $DestAirportCode = $BookingData[0]['DestAirportCode'];
            $SearchFlightTraceId = $BookingData[0]['SearchFlightTraceId'];
            $ICSourceSysId = $BookingData[0]['ICSourceSysId'];
            if ($ICSourceSysId == '3') {
                $Supplier = 'TBO';
            } elseif ($ICSourceSysId == '7') {
                $Supplier = 'TRIPJACK';
            } else {
                $Supplier = 'SERIESFARE';
            }

            $API_URL = $this->gtxBtoBsite . "gtxwebservices/create-invoice/";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_URL);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            //curl_setopt($ch, CURLOPT_PORT, 443);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'SecurityKey:' . SECURITYKEY,
            ));
            $output = curl_exec($ch);
            curl_close($ch);
            // print_r($output);
            // die('ssss');
            $response = json_decode($output, true);
            $ResponseStatus = $response['statue'];
            $ErrorMessage = isset($response['message']) ? $response['message'] : '';

            $logParams = [
                "user_id"      => 1,
                "AgencySysId"      => $this->gtxagencysysid,
                "custom_error" => ($ResponseStatus == 1) ? "Flight Invoice Success" : "Flight Invoice Failed",
                'error'        => $ErrorMessage,
                "text_udf"     => ['response' => $response], // Response
                "char_udf"     => ['request' => $data], // Request
                "udf1"         => $SearchFlightTraceId,
                "udf5"         => 'invoice',
                "from_destination"             => $SourceAirportCode,
                "to_destination"             => $DestAirportCode,
                "flight_type"                 => (int)$JourneyType,
                "source"                     => 1,
                "Pax"                         => ($TotalFlightMembers),
                "Supplier"                     => ($Supplier),
                "Airline"                     => $AirlineName,
                "status"       => ($ResponseStatus == 1) ? 2 : 1,
            ];
            Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }

    public function availableCoupon($data)
    {
        if ($data) {
            $API_URL = Catabatic_Helper::gtxBtoBsite() . "gtxwebservices/coupon/available-coupon-codes/";
            $apiData = array(
                "SecurityKey" => SECURITYKEY,
                'AgencySysId' => $data['AgencySysId'],
                'ServiceFee' => $data['ServiceFee'],
                'CriteriaValue' => $data['CriteriaValue'],
                'ProductType' => $data['ProductType'],
                'TravelDate' => date('Y-m-d'),
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_URL);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
            //curl_setopt($ch, CURLOPT_PORT, 443);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            $output = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($output, true);
            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }

    public function validateCoupon($data)
    {
        if ($data) {
            $API_URL = Catabatic_Helper::gtxBtoBsite() . "gtxwebservices/coupon/validate-apply-coupon-code/";
            $apiData = array(
                "SecurityKey" => SECURITYKEY,
                'AgencySysId' => $data['AgencySysId'],
                'ServiceFee' => $data['ServiceFee'],
                'CriteriaValue' => $data['CriteriaValue'],
                'couponcode' => $data['couponcode'],
                'ProductType' => $data['ProductType'],
                'TravelDate' => $data['TravelDate'],
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_URL);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
            //curl_setopt($ch, CURLOPT_PORT, 443);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            $output = curl_exec($ch);

            curl_close($ch);
            $response = json_decode($output, true);
            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }
    public function applyCoupon($data)
    {
        if ($data) {
            $API_URL = Catabatic_Helper::gtxBtoBsite() . "gtxwebservices/coupon/apply-coupon-code/";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_URL);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            //curl_setopt($ch, CURLOPT_PORT, 443);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            $output = curl_exec($ch);
            curl_close($ch);
            $response = json_decode($output, true);
            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }
    public function gstvalidate($clientgst, $agencygst = null)
    {
        if ($clientgst && $agencygst) {
            $tin_client = substr($clientgst, 0, 2);
            $tin_agency = substr($agencygst, 0, 2);

            $url = $this->baseUrl . "public/data/dynamic/gst-state-code-list.json";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $output = curl_exec($ch);
            curl_close($ch);
            $response = json_decode($output, true);
            if ($tin_client && $tin_agency) {
                $tin_clientId = array_filter($response, function ($var) use ($tin_client) {
                    return ($var['tin'] == $tin_client);
                });
                $tin_agencyId = array_filter($response, function ($var) use ($tin_agency) {
                    return ($var['tin'] == $tin_agency);
                });
                $tin_clientId = array_values($tin_clientId);
                $tin_agencyId = array_values($tin_agencyId);
                $tin_clientId = (isset($tin_clientId[0]['tin']) && !empty($tin_clientId[0]['tin'])) ? $tin_clientId[0]['tin'] : '';
                $tin_agencyId = (isset($tin_agencyId[0]['tin']) && !empty($tin_agencyId[0]['tin'])) ? $tin_agencyId[0]['tin'] : '';
                if ($tin_clientId == $tin_agencyId) {
                    $data = array('SGST' => true, 'CGST' => true, 'IGST' => false, 'client' => $tin_clientId, 'agency' => $tin_agencyId);
                } else {
                    $data = array('SGST' => false, 'CGST' => false, 'IGST' => true, 'client' => $tin_clientId, 'agency' => $tin_agencyId);
                }
            }
            return $data;
        } else {
            $data = array('SGST' => true, 'CGST' => true, 'IGST' => false, 'client' => 0, 'agency' => 0);
            return ($data);
        }
    }

    public function WhatsappMessage($data, $BookingData)
    {
        if ($data) {
            foreach ($data as $key => $value) {
                $AirlineName = $BookingData[$key]['AirlineName'];
                $TotalFlightMembers = $BookingData[$key]['TotalFlightMembers'];
                $JourneyType = $BookingData[$key]['JourneyType'];
                $SourceAirportCode = $BookingData[$key]['SourceAirportCode'];
                $DestAirportCode = $BookingData[$key]['DestAirportCode'];
                $SearchFlightTraceId = $BookingData[$key]['apiTraceId'];
                $ICSourceSysId = $BookingData[$key]['ICSourceSysId'];
                if ($ICSourceSysId == '3') {
                    $Supplier = 'TBO';
                } elseif ($ICSourceSysId == '7') {
                    $Supplier = 'TRIPJACK';
                } else {
                    $Supplier = 'SERIESFARE';
                }


                $API_URL = $this->gtxBtoBsite . "whatsapp/api/flight-ticket-success";

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $API_URL);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($value));
                //curl_setopt($ch, CURLOPT_PORT, 443);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'SecurityKey:' . SECURITYKEY,
                ));
                $output = curl_exec($ch);
                curl_close($ch);

                $response = json_decode($output, true);
                $ResponseStatus = isset($response['result']) ? $response['result'] : false;
                $ErrorMessage = 'Not available';


                $logParams = [
                    "user_id"      => 1,
                    "AgencySysId"      => $this->gtxagencysysid,
                    "custom_error" => ($ResponseStatus == 1) ? "Flight whatsapp Success" : "Flight whatsapp Failed",
                    'error'        => $ErrorMessage,
                    "text_udf"     => ['response' => $response], // Response
                    "char_udf"     => ['request' => $value], // Request
                    "udf1"         => $SearchFlightTraceId,
                    "udf5"         => 'whatsapp',
                    "from_destination"             => $SourceAirportCode,
                    "to_destination"             => $DestAirportCode,
                    "flight_type"                 => (int)$JourneyType,
                    "source"                     => 1,
                    "Pax"                         => ($TotalFlightMembers),
                    "Supplier"                     => ($Supplier),
                    "Airline"                     => $AirlineName,
                    "status"       => ($ResponseStatus == 1) ? 2 : 1,
                ];

                $dd = Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
            }

            return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }

    function getCurrencyRate($FCurrencyType, $TCurrencyType, $AgencySysId)
    {
        if ($FCurrencyType && $TCurrencyType) {
            try {
                $apiData = ["AgencySysId" => $AgencySysId];
                // $URL = $this->baseUrl . "webservice/currency/rate";
                $URL = "https://globaltravelexchange.com/webservice/currency/rate";
                $curl = curl_init($URL);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiData));
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                $curl_response = curl_exec($curl);
                curl_close($curl);
                $response = json_decode($curl_response, true);
                $RateList = [];
                $MasterData = [];
                // if ($AgencySysId == '36328') {
                //     echo "<pre>";
                //     print_r($apiData);
                //     echo "<pre>";
                //     print_r($FCurrencyType);
                //     echo "<pre>";
                //     print_r($TCurrencyType);
                //     echo "<pre>";
                //     print_r($response);
                //     die('dd');
                // }
                if ($response['RateList']) {
                    foreach ($response['RateList'] as $key => $value) {
                        if ($FCurrencyType == $value['FCurrencyType'] && $TCurrencyType == $value['TCurrencyType']) {
                            $RateList[$TCurrencyType] = $value;
                        }
                    }
                }
                if ($response['MasterData']) {
                    foreach ($response['MasterData'] as $key => $value) {
                        $MasterData[$value['CurrencyType']] = $value['Symbol'];
                    }
                }
                $Rate = isset($RateList[$TCurrencyType]['Rate']) ? $RateList[$TCurrencyType]['Rate'] : 1;
                $Symbol = isset($MasterData[$TCurrencyType]) ? trim($MasterData[$TCurrencyType]) : 'INR';
                return ['Rate' => $Rate, 'Symbol' => $Symbol, 'CurrencyId' => $TCurrencyType, 'MasterData' => $MasterData];
            } catch (Exception $error) {
                echo $error->getMessage();
                die;
            }
        } else {
            return 'Bad request';
        }
    }

    function CurrencyData($AgencySysId, $id = 1)
    {
        Zend_Session::namespaceUnset('CurrencyRate');
        Zend_Session::namespaceUnset('CurrencyTitle');
        Zend_Session::namespaceUnset('CurrencyId');
        Zend_Session::namespaceUnset('MasterData');
        $TCurrencyType = $id;
        $FCurrencyType = 1;
        $apiResponse = $this->getCurrencyRate($FCurrencyType, $TCurrencyType, $AgencySysId);

        $CurrencyRate_ = isset($apiResponse['Rate']) ? $apiResponse['Rate'] : 1;
        $CurrencyTitle_ = isset($apiResponse['Symbol']) ? $apiResponse['Symbol'] : 'INR';
        $CurrencyId_ = isset($apiResponse['CurrencyId']) ? $apiResponse['CurrencyId'] : 1;
        $MasterData_ = isset($apiResponse['MasterData']) ? $apiResponse['MasterData'] : [];

        $CurrencyRate = new Zend_Session_Namespace('CurrencyRate');
        $CurrencyRate->params = $CurrencyRate_;
        $CurrencyTitle = new Zend_Session_Namespace('CurrencyTitle');
        $CurrencyTitle->params = $CurrencyTitle_;
        $CurrencyId = new Zend_Session_Namespace('CurrencyId');
        $CurrencyId->params = $CurrencyId_;
        $MasterData = new Zend_Session_Namespace('MasterData');
        $MasterData->params = $MasterData_;
        return $apiResponse;
    }
    public function isLeapYear($year)
    {
        if ($year % 4 == 0) {
            if ($year % 100 == 0) return ($year % 400 == 0) ? true : false;
            return true;
        }
        return false;
    }
    public function GetJulianDate($date)
    {

        $days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        $month = (date('m', strtotime($date)) - 1);
        $day = date('d', strtotime($date));
        $year = date('Y', strtotime($date));
        $time = time();
        $zone = 7; // PDT Zone
        if ($this->isLeapYear($year)) $days[1] += 1;
        $jDate = 0;
        for ($i = 0; $i < $month; $i++) $jDate += $days[$i];
        $jDate += $day;

        if (strlen($jDate) < 100) $jDate = sprintf("%03d", $jDate);
        if (strlen($jDate) < 10) $jDate = sprintf("%03d", $jDate);
        return $jDate;
    }
    public function FlightNumberPadded($SegFlightNumber_)
    {

        if (strlen($SegFlightNumber_) == 2) {
            $FlightNumber_ = sprintf("%04d", $SegFlightNumber_) . ' ';
        } elseif (strlen($SegFlightNumber_) == 3) {
            $FlightNumber_ = sprintf("%04d", $SegFlightNumber_) . ' ';
        } elseif (strlen($SegFlightNumber_) == 4) {
            $FlightNumber_ = sprintf("%04d", $SegFlightNumber_) . ' ';
        } elseif (strlen($SegFlightNumber_) == 5) {
            $FlightNumber_ = $SegFlightNumber_;
        } else {
            $FlightNumber_ = sprintf("%05d", $SegFlightNumber_);
        }
        return $FlightNumber_;
    }
    public function GetAgencyInventorySector($FlightType)
    {
        // echo $FlightType;die;
        $SECURITYKEY = SECURITYKEY;
        $this->postFields = "?SecurityKey=" . $SECURITYKEY;
        $this->postFields .= "&FlightType=" . $FlightType;
        $URL = $this->Series_Fare_Url . 'get-inventory/' . $this->postFields;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_POST, false);
        //curl_setopt($ch, CURLOPT_POSTFIELDS, ($this->postFields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Accept-Encoding: gzip',
            //'Content-Length: ' . strlen($this->postFields),
        ));

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

        return $response;
    }

    public function getAirlinesName()
    {

        $url = $this->baseUrl . "public/data/dynamic/airlinesName.json";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($output, true);

        return $response;
    }

    public function SendWhatsapp($data)
    {
        // if($this->gtxagencysysid == '2656'){
        //     $SecurityKey = 'DD893E56-D9DE-4EA6-B593-02FBF0ECB5CB';
        // }else{
            $SecurityKey = SECURITYKEY;
        //}
        if ($data) {

            $curl = curl_init();
            $API_URL = $this->gtxBtoBsite . "gtxwebservices/whatsapp/index/";
            curl_setopt_array($curl, array(
                CURLOPT_URL => $API_URL,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_SSL_VERIFYPEER => FALSE,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => array(
                    'SecurityKey: '.$SecurityKey
                ),
            ));

            $output = curl_exec($curl);

            curl_close($curl);
            $response = json_decode($output, true);

            return $response;

            // $API_URL = $this->gtxBtoBsite . "gtxwebservices/whatsapp/";

            // $ch = curl_init();
            // curl_setopt($ch, CURLOPT_URL, $API_URL);
            // curl_setopt($ch, CURLOPT_HEADER, 0);
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, ($data));
            // //curl_setopt($ch, CURLOPT_PORT, 443);
            // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            //     'SecurityKey:' . SECURITYKEY,
            // ));
            // $output = curl_exec($ch);
            // curl_close($ch);
            // $response = json_decode($output, true);

            // return $response;
        } else {
            $data = array('status' => false, 'message' => 'Invalid request');
            return ($data);
        }
    }
    public function convertMinutes($fromtime, $totime)
	{
		$to_time = strtotime($totime);
		$from_time = strtotime($fromtime);
		return round(abs($to_time - $from_time) / 60, 2);
	}

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

    function moneyFormatIndia($number){    	
        $decimal = (string)($number - floor($number));
        $money = floor($number);
        $length = strlen($money);
        $delimiter = '';
        $money = strrev($money);

        for($i=0;$i<$length;$i++){
            if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$length){
                $delimiter .=',';
            }
            $delimiter .=$money[$i];
        }

        $result = strrev($delimiter);
        $decimal = preg_replace("/0\./i", ".", $decimal);
        $decimal = substr($decimal, 0, 3);

        if( $decimal != '0'){
            $result = $result.$decimal;
        }

        return $result;
    }
    function CustomerWallaetBalance($CustomerSysId)
	{
		if ($CustomerSysId) {
			$apiDataIV = array(
				"CustomerSysId" => $CustomerSysId,
			);
            $Url = $this->gtxBtoBsite.'gtxwebservices/customer-wallet/check-wallet-balance';
            $curl_p = curl_init($Url);
            curl_setopt($curl_p, CURLOPT_POST, true);
            curl_setopt($curl_p, CURLOPT_POSTFIELDS, ($apiDataIV));
            curl_setopt($curl_p, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_p, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_p, CURLOPT_TIMEOUT, 300);
            curl_setopt($curl_p, CURLOPT_HTTPHEADER, array(
                'SecurityKey:' . SECURITYKEY,
            ));
            $response = curl_exec($curl_p);

            curl_close($curl_p);
            // print_r($response);die;
			return Zend_Json::decode($response, true);
		} else {
			return 'Bad request';
		}
	}
    function DebitFromWallet($DebitFromWallet,$Url)
	{
		if ($DebitFromWallet) {
            $curl_p = curl_init($Url);
            curl_setopt($curl_p, CURLOPT_POST, true);
            curl_setopt($curl_p, CURLOPT_POSTFIELDS, ($DebitFromWallet));
            curl_setopt($curl_p, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_p, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_p, CURLOPT_TIMEOUT, 300);
            curl_setopt($curl_p, CURLOPT_HTTPHEADER, array(
                'SecurityKey:' . SECURITYKEY,
            ));
            $response = curl_exec($curl_p);

            curl_close($curl_p);
            // print_r($DebitFromWallet);
            // print_r($response);
            // die;
			return Zend_Json::decode($response, true);
		} else {
			return 'Bad request';
		}
	}
}

Youez - 2016 - github.com/yon3zu
LinuXploit