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/holidays.tripjack.com/library/Helper/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/holidays.tripjack.com/library/Helper/Flight.php_24_05_2022
<?php

/* * *************************************************************
 * Catabatic Technology Pvt. Ltd.
 * File Name     : Flight.php
 * File Desc.    : Flight helper to including supporting functions/methods for Flight
 * Created By    : Md Sabir <sabir@catpl.co.in>
 * Created Date  : 14 Feb 2020
 * Updated Date  : 07 Aug 2020
 * ************************************************************* */

class Zend_Controller_Action_Helper_Flight extends Zend_Controller_Action_Helper_Abstract
{

	public $baseUrl;
	public $_session;

	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->gtxBtoBsite  = $BootStrap['gtxBtoBsite'];
		$this->_session = new Zend_Session_Namespace('User');
	}

	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('2' => 'Economy', '3' => 'Premium Economy', '4' => 'Business', '5' => 'PremiumBusiness', '6' => 'First');
		// return array('1' => 'All', '2' => 'Economy', '3' => 'Premium Economy', '4' => 'Business', '5' => 'PremiumBusiness', '6' => 'First');
	}
	public function getFlightClassesTripJack()
	{
		//return array('1' => 'Economy', '2' => 'Premium Economy', '3' => 'Business');
		return array('2' => 'Economy', '3' => 'Premium Economy', '4' => 'Business', '5' => 'First');
	}
	public function getFlightClassesTripJackGet()
	{
		//return array('1' => 'Economy', '2' => 'Premium Economy', '3' => 'Business');
		return array('2' => 'ECONOMY', '3' => 'PREMIUM_ECONOMY', '4' => 'BUSINESS', '5' => 'FIRST');
	}
	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 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, $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 getTimeFromApiStringTJ($string)
	{
		if (empty($string))
			return '';

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

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

		return substr(@$arr[1], 0, 5);
	}
	public function MinutesToHours($minutes)
	{
		if ($minutes) {
			$hours = floor($minutes / 60);
			$min = $minutes - ($hours * 60);
			$LAYOVERTime = $hours . "h " . $min . 'm';
			return $LAYOVERTime;
		}
	}
	public function convertMinutesToHoursFormat($minutes)
	{
		if ($minutes < 1) {
			//return;
		}
		$hours = floor($minutes / 60);
		$minutes = ($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 SearchInterval($time1, $time2)
	{
		$diff = abs(strtotime($time1) - strtotime($time2));

		$tmins = $diff / 60;
		$hours = floor($tmins / 60);
		$mins = $tmins % 60;
		return ['h' => $hours, 'm' => $mins];
	}

	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 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);
				// echo '<pre>';
				// print_r($output);
				// die;
				$response = json_decode($output, true);

				if (FLIGHT_API_LOGS) {

					//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);
					//Write Request Logs starts...
					//Write Request Logs starts...
					$strFilePath = "flight/Auth/" . date('Y-m-d-H-i-s') . "_Auth_response.json";
					Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $output);
					//Write Request Logs starts...
				}

				$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());
			exit;
		}
	}

	// public function authenticateAPI()
	// {
	// 	$TokenIdSession = new Zend_Session_Namespace('TokenIdSession');
	// 	$objFlight = new Travel_Model_FlightMaster();
	// 	$CheckFlightToken = $objFlight->CheckFlightToken('tbl_token');

	// 	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);
	// 		//echo '<pre>';print_r($output);die;
	// 		$response = json_decode($output, true);

	// 		if (FLIGHT_API_LOGS) {

	// 			//Write Request Logs starts...
	// 			$strFilePath = "flight/Auth/" . time() . "_Auth_request.json";
	// 			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_string);
	// 			//Write Request Logs starts...
	// 			//Write Request Logs starts...
	// 			$strFilePath = "flight/Auth/" . time() . "_Auth_response.json";
	// 			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $output);
	// 			//Write Request Logs starts...
	// 		}

	// 		$tokenId = $response['TokenId'];
	// 		curl_close($ch);
	// 		$TokenIdSession = new Zend_Session_Namespace('TokenIdSession');
	// 		$TokenIdSession->params = $tokenId;
	// 		$insertArr = array(
	// 			'token' => $tokenId,
	// 			'created_at' => Zend_Date::now()->toString('YYYY-MM-dd HH:mm:ss'),
	// 		);
	// 		$objFlight->InsertFlightData('tbl_token', $insertArr);

	// 		return $tokenId;
	// 	} else {
	// 		$TokenIdSession->params = $CheckFlightToken['token'];
	// 		return $CheckFlightToken['token'];
	// 	}
	// }

	public function CreateSessionSearchParams($getData, $TraceId)
	{
		
		Zend_Session::namespaceUnset('sessionFlightSearchParams');
		//        Zend_Session::namespaceUnset('recentSearch');die;
		if (!empty($getData)) {
			$uri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
			$uriExp = explode('?', $uri);
			$recentSearch->params = [];
			$sessionFlightSearchParams = new Zend_Session_Namespace('sessionFlightSearchParams');
			$getData['from_city'] = $getData['from_des'];
			$getData['to_city'] = $getData['to_des'];
			$recentSearch = new Zend_Session_Namespace('recentSearch');
			$SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
			$sessionFlightSearchParams->params = $getData; // Putting all form data to Session
			$SearchFlightTraceId->params = $TraceId;


			$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);
			$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);

			$departure_dates = $getData['departure_date'];
			$return_dates = $getData['return_date'];
			$source_city = $getData['source_city']; // or DEL,BLR etc.
			$destination_city = $getData['destination_city']; // or DEL,BLR etc.
			$PreferredAirline = $getData['PreferredAirline'];
			//echo '<pre>';print_r($PreferredAirline);die;
			$DepDate = [];
			$DepDateMobile = [];
			$RetDate = [];
			$RetDateMobile = [];
			$intSourceCityId = [];
			$intCountryCode_ = [];
			$intdestinationCityId = [];
			$interNationalSearchArray = [];
			if ($departure_dates) {
				foreach ($departure_dates as $DEDate) {
					if (!empty($DEDate)) {
						$arrDepatureDate = explode("/", $DEDate);
						if (count($arrDepatureDate) > 0) {
							$strDepatureDate = $arrDepatureDate[2] . "-" . $arrDepatureDate[1] . "-" . $arrDepatureDate[0];
							$DepDate[] = $strDepatureDate;
							$DepDateMobile[] = date('d M D', strtotime($strDepatureDate));
						}
					}
				}
			}
			if ($return_dates) {
				foreach ($return_dates as $REDate) {
					if (!empty($REDate)) {
						$strReturnDate = explode("/", $REDate);
						if (count($strReturnDate) > 0) {
							$strReturnDate = $strReturnDate[2] . "-" . $strReturnDate[1] . "-" . $strReturnDate[0];
							$RetDate[] = $strReturnDate;
							$RetDateMobile[] = date('d M D', strtotime($strReturnDate));
						}
					}
				}
			}
			if ($source_city) {
				foreach ($source_city as $key => $filterByFrom) {
					$filterByTo = $destination_city[$key];
					$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 = "";
						$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['strDepatureDate'] = $DepDate;
			$sessionFlightSearchParams->params['strReturnDate'] = !empty($RetDate) ? $RetDate : '';
			$sessionFlightSearchParams->params['sourceCityId'] = !empty($intSourceCityId) ? $intSourceCityId : '';
			$sessionFlightSearchParams->params['intCountryCode'] = !empty($intCountryCode_) ? $intCountryCode_ : '';
			$sessionFlightSearchParams->params['destinationCityId'] = !empty($intdestinationCityId) ? $intdestinationCityId : '';
			$sessionFlightSearchParams->params['interNationalSearchArray'] = !empty($interNationalSearchArray) ? $interNationalSearchArray : '';
			$sessionFlightSearchParams->params['FlightTraceId'] = $TraceId;

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

			$sessionFlightSearchParams->params['DepatureDateMobile'] = ($DepDateMobile);
			$sessionFlightSearchParams->params['ReturnDateMobile'] = !empty($RetDateMobile) ? $RetDateMobile : '';
			$sessionFlightSearchParams->params['SearchTime'] = Zend_Date::now()->toString('YYYY-MM-dd HH:mm:ss');

			$sessionFlightSearchParams->params['ContSysId'] = $getData['ContSysId'];
			$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'];
			// echo '<pre>';print_r($sessionFlightSearchParams->params);
			// 
			// die;
			$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[$k + 1] = $sessionFlightSearchParams->params;
				$recentSearch->params[$k + 1]['searchUrl'] = $uriExp[1];
			}

			//echo '<pre>';print_r($sessionFlightSearchParams->params);die;
			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $TraceId . '/' . time() . "_SearchParam_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($sessionFlightSearchParams->params));
			}
			return $sessionFlightSearchParams->params;
		} else {
			die('Oops something went wrong');
		}
	}

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

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

		$strFlightRoute = trim($arrSessionData['route']);
		$adultCount = $arrSessionData['adults'];
		$childCount = $arrSessionData['child'];
		$infantCount = $arrSessionData['infant'];
		$FlightTraceId = $arrSessionData['FlightTraceId'];
		$PreferredAirline = $arrSessionData['PreferredAirline'];
		$interNationalSearch = isset($arrSessionData['interNationalSearch']) ? trim($arrSessionData['interNationalSearch']) : 0;
		if (isset($arrSessionData['DirectFlight']) && $arrSessionData['DirectFlight'] == 1) {
			$DirectFlight = true;
		} else {
			$DirectFlight = false;
		}

		$preferredFlightClassType = $arrSessionData['flight_class'];
		$Segments = [];
		if ($arrSessionData['sourceCityAirportCode']) {
			foreach ($arrSessionData['sourceCityAirportCode'] as $key => $value) {
				$origin = $arrSessionData['sourceCityAirportCode'][$key];
				$destination = $arrSessionData['destinationCityAirportCode'][$key];
				$preferredDepartureTime = $arrSessionData['strDepatureDate'][$key];
				$preferredArrivalTime = $arrSessionData['strDepatureDate'][$key];
				$preferredReturnArrivalTime = $arrSessionData['strReturnDate'][$key];
				$Segments[$key] = array(
					'Origin' => $origin,
					'Destination' => $destination,
					'FlightCabinClass' => $preferredFlightClassType,
					"PreferredDepartureTime" => $preferredDepartureTime . "T00:00:00",
					'PreferredArrivalTime' => $preferredArrivalTime . "T00:00:00",
				);
				if ($strFlightRoute == 2) {
					$Segments[$key + 1] = array(
						'Origin' => $destination,
						'Destination' => $origin,
						'FlightCabinClass' => $preferredFlightClassType,
						"PreferredDepartureTime" => $preferredReturnArrivalTime . "T00:00:00",
						'PreferredArrivalTime' => $preferredReturnArrivalTime . "T00:00:00",
					);
				}
			}
		}
		$datah = array(
			'EndUserIp' => $_SERVER['REMOTE_ADDR'],
			'TokenId' => $tokenId['token'],
			"AdultCount" => $adultCount,
			"ChildCount" => $childCount,
			"InfantCount" => $infantCount,
			"DirectFlight" => $DirectFlight,
			"OneStopFlight" => "false",
			"JourneyType" => $strFlightRoute,
			//"PreferredAirlines" => NULL, //["AI","9W","SG"]
			"Segments" => $Segments,
			"Sources" => NULL,
		);
		if (!empty($PreferredAirline)) {
			$datah['PreferredAirlines'] = $PreferredAirline;
		} else {
			$datah['PreferredAirlines'] = null;
		}
		if ($strFlightRoute == 2) {
			$datah['ReturnDate'] = $preferredReturnArrivalTime . "T00:00:00";
		}
		$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_POST, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		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($AgencySysid);
			$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_POST, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			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);
		}
		//echo '<pre>';print_r($response);die;
		if (FLIGHT_API_LOGS) {

			//Write Request Logs starts...
			//$strFilePath = "flight/FlightSearch/" . date('Y-m-d-H-i-s') . '_'. "_FlightSearch_request.json";
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . "_FlightSearch_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			//Write Request Logs starts...
			//Write Request Logs starts...
			//$strFilePath = "flight/FlightSearch/" . date('Y-m-d-H-i-s') . '_' .  "_FlightSearch_response.json";
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . "_FlightSearch_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			//Write Request Logs starts...
		}
		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();
			}
		}

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

		$logParams = [
			"user_id"      => 1,
			"custom_error" => ($ResponseStatus == 1) ? "Search Api Flight Response Success" : "Search Api Flight Response Failed",
			'error'        => $ErrorMessage,
			"text_udf"     => ['response' => $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('FlightSearchResults');
		$FlightSearchResults = new Zend_Session_Namespace('FlightSearchResults');
		$FlightSearchResults->params = $arrFlightSearchResponse; // store all serch result data to Session
		return $arrFlightSearchResponse;
		die;
	}

	public function searchApiFlightsTripjack($arrSessionData = array())
	{
		$arrFlightClass = Zend_Controller_Action_HelperBroker::getStaticHelper('Flight')->getFlightClassesTripJackGet();
		$cabinClass = $arrFlightClass[$arrSessionData['flight_class']];
		$interNationalSearch = isset($arrSessionData['interNationalSearch']) ? trim($arrSessionData['interNationalSearch']) : 0;
		//echo '<pre>';print_r($arrSessionData);
		$arrFlightSearchResponse = array();
		$FlightTraceId = $arrSessionData['FlightTraceId'];
		$PreferredAirline = $arrSessionData['PreferredAirline'];
		$strFlightRoute = trim($arrSessionData['route']);
		$adultCount = $arrSessionData['adults'];
		$childCount = $arrSessionData['child'];
		$infantCount = $arrSessionData['infant'];
		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 ($arrSessionData['sourceCityAirportCode']) {
			foreach ($arrSessionData['sourceCityAirportCode'] as $key => $value) {
				$origin = $arrSessionData['sourceCityAirportCode'][$key];
				$destination = $arrSessionData['destinationCityAirportCode'][$key];
				$preferredDepartureTime = $arrSessionData['strDepatureDate'][$key];
				$preferredReturnArrivalTime = $arrSessionData['strReturnDate'][$key];
				$routeInfo[$key] = array(
					'fromCityOrAirport' => array('code' => $origin),
					'toCityOrAirport' => array('code' => $destination),
					'travelDate' => $preferredDepartureTime,
				);
				if ($strFlightRoute == 2) {
					$routeInfo[$key + 1] = array(
						'fromCityOrAirport' => array('code' => $destination),
						'toCityOrAirport' => array('code' => $origin),
						'travelDate' => $preferredReturnArrivalTime,
					);
				}
			}
		}


		$data = array(
			'searchQuery' => array(
				'cabinClass' => ($cabinClass == 'All') ? 'ECONOMY' : strtoupper($cabinClass),
				'paxInfo' =>  array(
					'ADULT' => $adultCount,
					'CHILD' => $childCount,
					'INFANT' => $infantCount,
				),
				'routeInfos' => $routeInfo,
				'searchModifiers' => array('isDirectFlight' => $DirectFlight, 'isConnectingFlight' => $isConnectingFlight),
			),
		);
		if (!empty($PreferredAirline)) {
			$AirlineArr = [];
			foreach ($PreferredAirline as $code) {
				$AirlineArr[] = array(
					'code' => $code
				);
			}
			$data['searchQuery']['preferredAirline'] = $AirlineArr;
		}

		$data_stringh = json_encode($data);

		//echo '<pre>';print_r($data);
		//die;
		$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/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . "_FlightSearch_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/' . date('Y-m-d-H-i-s') . "_FlightSearch_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
		}

		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('FlightSearchResultsTJ');
		$FlightSearchResultsTJ = new Zend_Session_Namespace('FlightSearchResultsTJ');
		$FlightSearchResultsTJ->params = $arrFlightSearchResponse;  // store all serch result data to Session


		return $arrFlightSearchResponse;
	}

	public function GetApiFlightsFareRulesTripJack($arrData = array())
	{
		if ($arrData) {
			$FlightTraceId = $arrData['FlightTraceId'];
			$datah = array(
				'id' => $arrData['TraceId'],
				'flowType' => 'REVIEW',
			);

			$data_stringh = json_encode($datah);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, 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);
			if (FLIGHT_API_LOGS) {
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareRules/' . date('Y-m-d-H-i-s') . "_FlightSearch_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareRules/' . date('Y-m-d-H-i-s') . "_FlightSearch_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			}

			return $response;
		}
	}

	public function GetAmendmentCharges($arrData = array())
	{
		if ($arrData) {

			$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_POST, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			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) {

				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentCharges_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentCharges_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
			Zend_Session::namespaceUnset('AmendmentChargesSession');
			$AmendmentChargesSession = new Zend_Session_Namespace('AmendmentChargesSession');
			$AmendmentChargesSession->params = $response;  // store all serch result data to Session
			return $response;
		}
	}
	public function GetSubmitAmendment($arrData = array())
	{
		if ($arrData) {

			$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_SSL_VERIFYPEER, false);
			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) {

				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_SubmitAmendment_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_SubmitAmendment_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
			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) {

			$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_SSL_VERIFYPEER, false);
			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) {

				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentDetails_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentDetails_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}

			return $response;
		}
	}
	public function GetAmendmentDetailsTBO($arrData = array(), $AgencySysid)
	{
		if ($arrData) {
			$TOKEN_ID = $this->authenticateAPI($AgencySysid);
			$datah = array(
				"ChangeRequestId" => $arrData['amendmentId'],
				"EndUserIp" => $_SERVER['REMOTE_ADDR'],
				"TokenId" => $TOKEN_ID['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_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) {

				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentDetails_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentDetails_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}

			return $response;
		}
	}

	public function GetApiFlightsFareRules($arrData = array(), $AgencySysid)
	{
		$tokenId = $this->authenticateAPI($AgencySysid);
		$SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
		$FlightTraceId = $SearchFlightTraceId->params;
		if ($arrData) {
			$datah = array(
				'EndUserIp' => $_SERVER['REMOTE_ADDR'],
				'TokenId' => $tokenId['token'],
				'TraceId' => $arrData['TraceId'],
				'ResultIndex' => $arrData['ApiResultIndex'],
			);

			//            echo "<pre>";print_r($datah);exit;
			$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_SSL_VERIFYPEER, false);
			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);
			//            echo "<pre>";print_r($response);exit;
			if (FLIGHT_API_LOGS) {

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

	public function GetApiFlightsFareQuote($arrData = array(), $AgencySysid)
	{
		$tokenId = $this->authenticateAPI($AgencySysid);
		$SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
		$FlightTraceId = $SearchFlightTraceId->params;
		$FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
		$logFile = $FlightSearchLogFile->params;
		if ($arrData) {
			$datah = array(
				'EndUserIp' => $_SERVER['REMOTE_ADDR'],
				'TokenId' => $tokenId['token'],
				'TraceId' => $arrData['TraceId'],
				'ResultIndex' => $arrData['ResultIndex'],
			);
			//            print_r($arrData);
			$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_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_stringh);
			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($data_stringh),
			));

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

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareReview/' . date('Y-m-d-H-i-s') . "_FareQuote_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareReview/' . date('Y-m-d-H-i-s') . "_FareQuote_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
		}
		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
		}

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

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

		return $response;
	}

	public function apiFlightTicket($data, $AgencySysid)
	{
		// echo '<pre>';print_r($data['CustomerSession']);die;
		$sessionFlightSearchParams = $data['sessionFlightSearchParams'];
		$FlightTraceId = $sessionFlightSearchParams['FlightTraceId'];
		$SelectedMealSessionNew = $data['SelectedMealSessionNew'];
		$SelectedBaggSessionNew = $data['SelectedBaggSessionNew'];
		$selectedSeatSession = $data['selectedSeatSession'];

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

		$finalFareSummary = $data['finalFareSummary'];
		$FareBreakdown = $finalFareSummary['FairRules']['FareBreakdown'];
		$TraceId = $data['FlightBookingData']['apiTraceId'];
		$ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
		$strAirlineCode = $data['FlightBookingData']['AirlineCode'];

		// echo '<pre>';print_r($selectedSeatSession);
		// die;
		$arrPassengers = [];
		if (FLIGHT_API_LOGS) {
			//Write Request Logs starts...
			$strFilePath = "flight/FareBreakdown/" . date('Y-m-d-H-i-s') . "_FareBreakdown_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($FareBreakdown));
			//Write Request Logs starts...
		}

		$ARR_SALUTION = unserialize(ARR_SALUTION);
		$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
		if ($TraceId && $ResultIndex && $data) {
			$arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
			$paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
			$paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
			$IsInternational = $data['sessionFlightSearchParams']['interNationalSearch'];
			$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++) {
					$MealArr = [];
					$BaggageArr = [];
					$SeatArr = [];
					$INK = ($intK + 1);
					$isgstapply = isset($data['CustomerSession'][$intK]['isgstapply']) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
					if ($intK == 0) {
						$CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
					} else {
						$CustomerSysId = $data['CustomerSession'][$intK]['CustomerMemberSysId'];
					}
					if ($SelectedMealSessionNew) {
						foreach ($SelectedMealSessionNew as $Meal) {
							if (isset($Meal[$INK]) && !empty($Meal[$INK])) {
								$MealArr[] = array(
									'WayType' => isset($Meal[$INK]['WayType']) ? $Meal[$INK]['WayType'] : '',
									'Code' => isset($Meal[$INK]['Code']) ? $Meal[$INK]['Code'] : '',
									'Description' => isset($Meal[$INK]['Description']) ? $Meal[$INK]['Description'] : '',
									'AirlineDescription' => isset($Meal[$INK]['AirlineDescription']) ? $Meal[$INK]['AirlineDescription'] : '',
									'Quantity' => isset($Meal[$INK]['Quantity']) ? $Meal[$INK]['Quantity'] : '',
									'Price' => isset($Meal[$INK]['Price']) ? $Meal[$INK]['Price'] : '',
									'Currency' => isset($Meal[$INK]['Currency']) ? $Meal[$INK]['Currency'] : '',
									'Origin' => isset($Meal[$INK]['Origin']) ? $Meal[$INK]['Origin'] : '',
									'Destination' => isset($Meal[$INK]['Destination']) ? $Meal[$INK]['Destination'] : '',
								);
							}
						}
					}
					if ($SelectedBaggSessionNew) {
						foreach ($SelectedBaggSessionNew as $Bagg) {
							if (isset($Bagg[$INK]) && !empty($Bagg[$INK])) {
								$BaggageArr[] = array(
									'WayType' => isset($Bagg[$INK]['WayType']) ? $Bagg[$INK]['WayType'] : '',
									'Code' => isset($Bagg[$INK]['Code']) ? $Bagg[$INK]['Code'] : '',
									'Description' => isset($Bagg[$INK]['Description']) ? $Bagg[$INK]['Description'] : '',
									'Weight' => isset($Bagg[$INK]['Weight']) ? $Bagg[$INK]['Weight'] : '',
									'Price' => isset($Bagg[$INK]['Price']) ? $Bagg[$INK]['Price'] : '',
									'Currency' => isset($Bagg[$INK]['Currency']) ? $Bagg[$INK]['Currency'] : '',
									'Origin' => isset($Bagg[$INK]['Origin']) ? $Bagg[$INK]['Origin'] : '',
									'Destination' => isset($Bagg[$INK]['Destination']) ? $Bagg[$INK]['Destination'] : '',
								);
							}
						}
					}
					if ($selectedSeatSession) {
						foreach ($selectedSeatSession as $Seat) {
							if (isset($Seat[$INK]) && !empty($Seat[$INK])) {
								//$SeatArr[]['SegmentSeat'][0]['RowSeats'][0]['Seats'][0] = array(
								$SeatArr[] = array(
									'AirlineCode' => isset($Seat[$INK]['AirlineCode']) ? $Seat[$INK]['AirlineCode'] : '',
									'FlightNumber' => isset($Seat[$INK]['FlightNumber']) ? $Seat[$INK]['FlightNumber'] : '',
									'CraftType' => isset($Seat[$INK]['CraftType']) ? $Seat[$INK]['CraftType'] : '',
									'Origin' => isset($Seat[$INK]['Origin']) ? $Seat[$INK]['Origin'] : '',
									'Destination' => isset($Seat[$INK]['Destination']) ? $Seat[$INK]['Destination'] : '',
									'AvailablityType' => isset($Seat[$INK]['AvailablityType']) ? $Seat[$INK]['AvailablityType'] : '',
									'Description' => isset($Seat[$INK]['Description']) ? $Seat[$INK]['Description'] : '',
									'Code' => isset($Seat[$INK]['Code']) ? $Seat[$INK]['Code'] : '',
									'RowNo' => isset($Seat[$INK]['RowNo']) ? $Seat[$INK]['RowNo'] : '',
									'SeatNo' => isset($Seat[$INK]['SeatNo']) ? $Seat[$INK]['SeatNo'] : '',
									'SeatType' => isset($Seat[$INK]['SeatType']) ? $Seat[$INK]['SeatType'] : '',
									'SeatWayType' => isset($Seat[$INK]['SeatWayType']) ? $Seat[$INK]['SeatWayType'] : '',
									'Compartment' => isset($Seat[$INK]['Compartment']) ? $Seat[$INK]['Compartment'] : '',
									'Deck' => isset($Seat[$INK]['Deck']) ? $Seat[$INK]['Deck'] : '',
									'Currency' => isset($Seat[$INK]['Currency']) ? $Seat[$INK]['Currency'] : '',
									'Price' => isset($Seat[$INK]['Price']) ? $Seat[$INK]['Price'] : '',
								);
							}
						}
					}

					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'];
					$countryName = $data['CustomerSession'][$intK]['countryName'];
					$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];
							}
						}
					}
					//echo '<pre>';print_r($FareBreakdown[$key]);
					$PassengerType = $arrFairDetails[$intI]['PassengerType'];
					$PassengerCount = $arrFairDetails[$intI]['PassengerCount'];
					$intBaseFare = ($arrFairDetails[$intI]['BaseFare'] / $PassengerCount);
					$intTax = ($arrFairDetails[$intI]['TaxIN'] / $PassengerCount);
					$intYQTax = ($arrFairDetails[$intI]['YQ'] / $PassengerCount);
					$intAdditionalTxnFeeOfrd = $arrFairDetails[$intI]['AdditionalTxnFeeOfrd'];
					$intAdditionalTxnFeePub = $arrFairDetails[$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'],
						//'DateOfBirth' => $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00',
						'Gender' => $intGender,
						'AddressLine1' => $paxAddress,
						'AddressLine2' => '',
						'City' => $paxCityTitle,
						'CountryCode' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
						'CountryName' => $countryName,
						'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 || $strAirlineCode == 'I5') {
						$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;
						$arrPassengers[$intK]['PassportIssueCountryCode'] = $data['CustomerSession'][$intK]['countryCodeISO'];
					}
					if ($isgstapply == 1) {
						$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 (isset($MealArr) && !empty($MealArr)) {
						$arrPassengers[$intK]['MealDynamic'] = $MealArr;
					}
					if (isset($BaggageArr) && !empty($BaggageArr)) {
						$arrPassengers[$intK]['Baggage'] = $BaggageArr;
					}
					if (isset($SeatArr) && !empty($SeatArr)) {
						$arrPassengers[$intK]['SeatDynamic'] = $SeatArr;
					}
					// if (isset($BaggSelected[$CustomerSysId]) && !empty($BaggSelected[$CustomerSysId])) {
					// 	$arrPassengers[$intK]['Baggage'] = $BaggageArr;
					// } elseif ($IsInternational == 1 && ($data['CustomerSession'][$intK]['paxType'] == 1 || $data['CustomerSession'][$intK]['paxType'] == 2)) {
					// 	$arrPassengers[$intK]['Baggage'] = $BaggageArr;
					// }
					$intK++;
				}
			}
			//echo '<pre>';print_r($arrPassengers);die;
			$tokenId = $this->authenticateAPI($AgencySysid);
			$data = array(
				'PreferredCurrency' => 'INR',
				'IsBaseCurrencyRequired' => 'true',
				'EndUserIp' => $_SERVER['REMOTE_ADDR'],
				'TokenId' => $tokenId['token'],
				'TraceId' => $TraceId,
				'ResultIndex' => $ResultIndex,
				'Passengers' => $arrPassengers,

			);

			$data_stringh = json_encode($data);
			// echo "<pre>";
			// print_r($data_stringh);
			// die('TTT');
			$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_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);
			// echo "<pre>";
			// print_r($outputH);
			$response = json_decode($outputH, true);

			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/"  . $FlightTraceId . '/FlightTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_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,
					"custom_error" => ($ResponseStatus == 1) ? "Get Flight Api Ticket Response Success" : "Get Flight Api Ticket Response Response Failed",
					'error'        => $ErrorMessage,
					"text_udf"     => ['response' => $response], // Response
					"char_udf"     => ['request' => $data], // Request
					"udf1"         => $FlightTraceId,
					"status"       => ($ResponseStatus == 1) ? 2 : 1,
				];
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);


			}
			$apiFlightTicket = new Zend_Session_Namespace('apiFlightTicket');
			$apiFlightTicket->params = $response;
			return $response;
		} else {
			return $response = [];
		}
		exit;
	}

	public function apiFlightBooking($data, $AgencySysid)
	{

		$SelectedMealSessionNew = new Zend_Session_Namespace('SelectedMealSessionNew');
		$arrSSRSelected = $SelectedMealSessionNew->params;

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

		$SelectedMealSessionNew = $data['SelectedMealSessionNew'];
		$sessionFlightSearchParams = $data['sessionFlightSearchParams'];
		$FlightTraceId = $sessionFlightSearchParams['FlightTraceId'];
		//echo "<pre>";print_r($SelectedMealSessionNew);exit;
		$TraceId = $data['FlightBookingData']['apiTraceId'];
		$ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
		$finalFareSummary = $data['finalFareSummary'];
		$FareBreakdown = $finalFareSummary['FairRules']['FareBreakdown'];
		$arrPassengers = [];
		if (FLIGHT_API_LOGS) {
			//Write Request Logs starts...
			$strFilePath = "flight/FareBreakdown/" . date('Y-m-d-H-i-s') . "_FareBreakdown_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($FareBreakdown));
			//Write Request Logs starts...
		}
		$ARR_SALUTION = unserialize(ARR_SALUTION);
		$ARR_SALUTION_CHILD = 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'];
			$IsInternational = $data['sessionFlightSearchParams']['interNationalSearch'];
			$agencyEmailId = '';
			//$SeatCode = isset($flightSSRDetails->params['SeatPreference'][0]['Code']) ? trim($flightSSRDetails->params['SeatPreference'][0]['Code']) : 'A';
			//$SeatDesc = isset($flightSSRDetails->params['SeatPreference'][0]['Description']) ? trim($flightSSRDetails->params['SeatPreference'][0]['Description']) : 'Window';
			$intK = 0;
			for ($intI = 0; $intI < count($arrFairDetails); $intI++) {

				$intPassengerCount = isset($arrFairDetails[$intI]['PassengerCount']) ? trim($arrFairDetails[$intI]['PassengerCount']) : 0;
				$isgstapply = isset($data['CustomerSession'][$intK]['isgstapply']) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
				for ($intJ = 0; $intJ < $intPassengerCount; $intJ++) {
					if ($intK == 0) {
						$CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
					} else {
						$CustomerSysId = $data['CustomerSession'][$intK]['CustomerMemberSysId'];
					}

					$MealArr = [];
					$INK = ($intK + 1);
					if ($SelectedMealSessionNew) {
						foreach ($SelectedMealSessionNew as $Meal) {
							if (isset($Meal[$INK]) && !empty($Meal[$INK])) {
								$MealArr = array(
									'Code' => isset($Meal[$INK]['Code']) ? $Meal[$INK]['Code'] : '',
									'Description' => isset($Meal[$INK]['Description']) ? $Meal[$INK]['Description'] : '',
								);
							}
						}
					}

					if ($data['CustomerSession'][$intK]['paxType'] == 1) {
						$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
					} else {
						$paxTitle = trim($ARR_SALUTION_CHILD[$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'];
					$countryName = $data['CustomerSession'][$intK]['countryName'];

					$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 = $arrFairDetails[$intI]['PassengerType'];
					$PassengerCount = $arrFairDetails[$intI]['PassengerCount'];
					$intBaseFare = ($arrFairDetails[$intI]['BaseFare'] / $PassengerCount);
					$intTax = ($arrFairDetails[$intI]['TaxIN'] / $PassengerCount);
					$intYQTax = ($arrFairDetails[$intI]['YQ'] / $PassengerCount);
					$intAdditionalTxnFeeOfrd = $arrFairDetails[$intI]['AdditionalTxnFeeOfrd'];
					$intAdditionalTxnFeePub = $arrFairDetails[$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,
						'Nationality' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
						'CountryName' => $countryName,
						'ContactNo' => $paxContactNo,
						'Email' => $data['CustomerSession'][$intK]['EmailId'],
						'IsLeadPax' => $intMemberSysId,
						'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,
						],
						//'Meal' =>$meal,
						//'Seat' => ['Code' => $SeatCode, 'Description' => $SeatDesc],
					];
					if ($IsInternational == '' && $data['CustomerSession'][$intK]['paxType'] == 3 || $data['CustomerSession'][$intK]['paxType'] == 2) {
						$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;
						$arrPassengers[$intK]['PassportIssueCountryCode'] = $data['CustomerSession'][$intK]['countryCodeISO'];
					}
					if ($isgstapply == 1) {
						$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 (isset($MealArr) && !empty($MealArr)) {
						$arrPassengers[$intK]['Meal'] = $MealArr;
					}
					$intK++;
				}
			}
			// echo "<pre>";print_r($arrPassengers);exit;
			$tokenId = $this->authenticateAPI($AgencySysid);
			$dataArr = array(
				'EndUserIp' => $_SERVER['REMOTE_ADDR'],
				'TokenId' => $tokenId['token'],
				'TraceId' => $TraceId,
				'ResultIndex' => $ResultIndex,
				'Passengers' => $arrPassengers,
			);
			$data_stringh = json_encode($dataArr);
			//echo "<pre>";print_r($data_stringh);exit;
			$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_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) {
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightBooking/' . date('Y-m-d-H-i-s') . "_FlightBooking_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/"  . $FlightTraceId . '/FlightBooking/' . date('Y-m-d-H-i-s') . "_FlightBooking_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,
					"custom_error" => ($ResponseStatus == 1) ? "Get Flight Api Booking Response Success" : "Get Flight Api Booking Response Failed",
					'error'        => $ErrorMessage,
					"text_udf"     => ['response' => $response], // Response
					"char_udf"     => ['request' => $dataArr], // Request
					"udf1"         => $FlightTraceId,
					"status"       => ($ResponseStatus == 1) ? 2 : 1,
				];
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
			}
			return $response;
		} else {
			return $response = [];
		}
	}

	public function apiFlightTicketRound($data)
	{
		$FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
		$logFile = $FlightSearchLogFile->params;
		// echo '<pre>';print_r($data);die;
		if ($data) {
			$data_stringh = json_encode($data);

			$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_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);
			//echo "<pre>";print_r($outputH);die('lcc');
			$response = json_decode($outputH, true);

			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/FlightTicket/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_FlightTicket_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

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

			}
			return $response;
		} else {
			return $response = [];
		}
		exit;
	}

	public function apiFlightBookingRound($data)
	{

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

		if ($data) {

			$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_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) {
				//Write Request Logs starts...
				$strFilePath = "flight/FlightBooking/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_FlightBooking_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

				//Write Request Logs starts...
				$strFilePath = "flight/FlightBooking/" . date('Y-m-d-H-i-s') . '_' . $logFile . "_FlightBooking_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
			return $response;
		} else {
			return $response = [];
		}
	}

	public function generateRoundTripRequest($data, $IsLCC)
	{
		//echo '<pre>';print_r($data);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;
				//echo '<pre>';print_r($MealSelected);
				//echo '<pre>';print_r($BaggSelected);
				$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');

			$finalFareSummary = $data['finalFareSummary'];
			$FareBreakdown = $finalFareSummary['FairRules']['FareBreakdown'];
			$TraceId = $data['FlightBookingData']['apiTraceId'];
			$ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
			$arrPassengers = [];
			//echo "<pre>";print_r($FareBreakdown);
			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/FareBreakdown/" . date('Y-m-d-H-i-s') . "_FareBreakdown_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($FareBreakdown));
				//Write Request Logs starts...
			}
			$ARR_SALUTION = unserialize(ARR_SALUTION);
			$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
			if ($TraceId && $ResultIndex && $data) {
				$arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
				$IsInternational = $data['FlightBookingData']['IsInternational'];
				$paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
				$paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
				$SourceAirportCode = $data['FlightBookingData']['SourceAirportCode'];
				$DestAirportCode = $data['FlightBookingData']['DestAirportCode'];
				$agencyEmailId = '';
				$intK = 0;
				for ($intI = 0; $intI < count($arrFairDetails); $intI++) {

					$intPassengerCount = isset($arrFairDetails[$intI]['PassengerCount']) ? trim($arrFairDetails[$intI]['PassengerCount']) : 0;
					$isgstapply = isset($data['CustomerSession'][$intK]['isgstapply']) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
					for ($intJ = 0; $intJ < $intPassengerCount; $intJ++) {
						$MealArr = [];
						$BaggageArr = [];
						if ($intK == 0) {
							$CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
						} else {
							$CustomerSysId = $data['CustomerSession'][$intK]['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'];
							$MealArr[] = array(
								'WayType' => $WayType,
								'Code' => $Code,
								'Description' => $Description,
								'AirlineDescription' => $AirlineDescription,
								'Quantity' => $Quantity,
								'Price' => $Price,
								'Currency' => $Currency,
								'Origin' => $Origin,
								'Destination' => $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'];
							$OriginBaggage = $BaggSelected[$CustomerSysId]['Origin'];
							$DestinationBaggage = $BaggSelected[$CustomerSysId]['Destination'];
							$BaggageArr[] = array(
								'WayType' => $WayTypeBaggage,
								'Code' => $CodeBaggage,
								'Description' => $DescriptionBaggage,
								'Weight' => $WeightBaggage,
								'Currency' => $CurrencyBaggage,
								'Price' => $PriceBaggage,
								'Origin' => $OriginBaggage,
								'Destination' => $DestinationBaggage,
							);
						}
						// 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';
						// 	$OriginBaggage = isset($arrSSR['Baggage'][0][0]['Origin']) ? trim($arrSSR['Baggage'][0][0]['Origin']) : '0';
						// 	$DestinationBaggage = isset($arrSSR['Baggage'][0][0]['Destination']) ? trim($arrSSR['Baggage'][0][0]['Destination']) : '0';

						// 	$BaggageArr[] = array(
						// 		'WayType' => $WayTypeBaggage,
						// 		'Code' => $CodeBaggage,
						// 		'Description' => $DescriptionBaggage,
						// 		'Weight' => $WeightBaggage,
						// 		'Currency' => $CurrencyBaggage,
						// 		'Price' => $PriceBaggage,
						// 		'Origin' => $OriginBaggage,
						// 		'Destination' => $DestinationBaggage,
						// 	);
						// }

						if ($data['CustomerSession'][$intK]['paxType'] == 1) {
							$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
						} else {
							$paxTitle = trim($ARR_SALUTION_CHILD[$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]['APIBaseFareCal'] / $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'],
							//'DateOfBirth' => $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00',
							'Gender' => $intGender,
							//'PassportNo' => ($IsInternational == 1) ? $PassportNo : '',
							//'PassportExpiry' => ($IsInternational == 1) ? $PassportExpiry . 'T00:00:00' : '',
							'AddressLine1' => $paxAddress,
							'AddressLine2' => '',
							'City' => $paxCityTitle,
							'CountryCode' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
							'Nationality' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
							'CountryName' => $paxCountryTitle,
							'ContactNo' => $paxContactNo,
							'Email' => $data['CustomerSession'][$intK]['EmailId'],
							'IsLeadPax' => $intMemberSysId,
							'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,
							],
							//'Baggage' => $BaggageArr
						];
						if ($IsInternational == '' && $data['CustomerSession'][$intK]['paxType'] == 3 || $data['CustomerSession'][$intK]['paxType'] == 2) {
							$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) {
							$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 (isset($MealSelected[$CustomerSysId]) && !empty($MealSelected[$CustomerSysId])) {
							$arrPassengers[$intK]['MealDynamic'] = $MealArr;
						}

						if (isset($BaggSelected[$CustomerSysId]) && !empty($BaggSelected[$CustomerSysId])) {
							$arrPassengers[$intK]['Baggage'] = $BaggageArr;
						} elseif ($IsInternational == 1 && ($data['CustomerSession'][$intK]['paxType'] == 1 || $data['CustomerSession'][$intK]['paxType'] == 2)) {
							$arrPassengers[$intK]['Baggage'] = $BaggageArr;
						}

						$intK++;
					}
				}
				//echo "<pre>";print_r($arrPassengers);
				$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;
			}
			$finalFareSummary = $data['finalFareSummary'];
			$FareBreakdown = $finalFareSummary['FairRules']['FareBreakdown'];
			// echo "<pre>";print_r($FareBreakdown);
			$TraceId = $data['FlightBookingData']['apiTraceId'];
			$ResultIndex = $data['FlightBookingData']['ApiResultIndex'];
			$arrPassengers = [];
			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/FareBreakdown/" . date('Y-m-d-H-i-s') . "_FareBreakdown_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, json_encode($FareBreakdown));
				//Write Request Logs starts...
			}
			$ARR_SALUTION = unserialize(ARR_SALUTION);
			$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
			if ($TraceId && $ResultIndex && $data) {
				$arrFairDetails = $data['FlightBookingData']['FairRules']['FareBreakdown'];
				$IsInternational = $data['FlightBookingData']['IsInternational'];
				$paxCountryTitle = $data['FlightBookingData']['Segments'][0]['originCountryName'];
				$paxCountryCode = $data['sessionFlightSearchParams']['intCountryCode'];
				$agencyEmailId = '';
				$SeatCode = isset($flightSSRDetails->params['SeatPreference'][0]['Code']) ? trim($flightSSRDetails->params['SeatPreference'][0]['Code']) : 'A';
				$SeatDesc = isset($flightSSRDetails->params['SeatPreference'][0]['Description']) ? trim($flightSSRDetails->params['SeatPreference'][0]['Description']) : 'Window';
				$intK = 0;
				for ($intI = 0; $intI < count($arrFairDetails); $intI++) {

					$intPassengerCount = isset($arrFairDetails[$intI]['PassengerCount']) ? trim($arrFairDetails[$intI]['PassengerCount']) : 0;
					$isgstapply = isset($data['CustomerSession'][$intK]['isgstapply']) ? $data['CustomerSession'][$intK]['isgstapply'] : 0;
					for ($intJ = 0; $intJ < $intPassengerCount; $intJ++) {
						if ($intK == 0) {
							$CustomerSysId = $data['CustomerSession'][$intK]['CustomerSysId'];
						} else {
							$CustomerSysId = $data['CustomerSession'][$intK]['CustomerMemberSysId'];
						}

						if (isset($arrSSRSelected[$CustomerSysId]) && !empty($arrSSRSelected[$CustomerSysId])) {
							$MealCode = $arrSSRSelected[$CustomerSysId]['Code'];
							$MealDesc = $arrSSRSelected[$CustomerSysId]['Description'];
							$meal = array('Code' => $MealCode, 'Description' => $MealDesc);
						}
						// 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';
						// $meal = array('Code' => $MealCode, 'Description' => $MealDesc);
						// }
						$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
						$getSalutation = Zend_Controller_Action_HelperBroker::getStaticHelper("Flight")->getSalutationByid($data['CustomerSession'][$intK]['Salutation']);
						$intGender = $getSalutation['Gender_Id'];
						if ($data['CustomerSession'][$intK]['paxType'] == 1) {
							$paxTitle = trim($ARR_SALUTION[$data['CustomerSession'][$intK]['Salutation']], ".");
						} else {
							$paxTitle = trim($ARR_SALUTION_CHILD[$data['CustomerSession'][$intK]['Salutation']], ".");
						}
						$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]['APIBaseFareCal'] / $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'],
							//'DateOfBirth' => $data['CustomerSession'][$intK]['DOB'] . 'T00:00:00',
							'Gender' => $intGender,
							//'PassportNo' => ($IsInternational == 1) ? $PassportNo : '',
							//'PassportExpiry' => ($IsInternational == 1) ? $PassportExpiry . 'T00:00:00' : '',
							'AddressLine1' => $paxAddress,
							'AddressLine2' => '',
							'City' => $paxCityTitle,
							'CountryCode' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
							'Nationality' => $data['CustomerSession'][$intK]['countryCodeISO'], //$paxCountryCode,
							'CountryName' => $paxCountryTitle,
							'ContactNo' => $paxContactNo,
							'Email' => $data['CustomerSession'][$intK]['EmailId'],
							'IsLeadPax' => $intMemberSysId,
							'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,
							],
							'Seat' => array(
								'Code' => $SeatCode,
								'Description' => $SeatDesc,
							),
						];
						if ($IsInternational == '' && $data['CustomerSession'][$intK]['paxType'] == 3 || $data['CustomerSession'][$intK]['paxType'] == 2) {
							$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) {
							$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 (isset($arrSSRSelected[$CustomerSysId]) && !empty($arrSSRSelected[$CustomerSysId])) {
							$arrPassengers[$intK]['Meal'] = $meal;
						}
						$intK++;
					}
				}
				//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 generateNonLccTicket($data, $AgencySysid)
	{

		$tokenId = $this->authenticateAPI($AgencySysid);
		$FlightTraceId = $data['FlightTraceId'];
		$datah = array(
			'EndUserIp' => $_SERVER['REMOTE_ADDR'],
			'TokenId' => $tokenId['token'],
			'TraceId' => $data['TraceId'],
			'PNR' => $data['PNR'],
			'BookingId' => $data['BookingId'],
		);
		//echo '<pre>';print_r(($datah));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_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) {
			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/generateNonLccTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			//Write Request Logs starts...

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/generateNonLccTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			//Write Request Logs starts...
		}

		return $response;
	}
	public function flightSSRDetails($data, $AgencySysid)
	{
		///print_r($data);die;
		$tokenId = $this->authenticateAPI($AgencySysid);
		$SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
		$FlightTraceId = $SearchFlightTraceId->params;
		$FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
		$logFile = $FlightSearchLogFile->params;
		$datah = array(
			'EndUserIp' => $_SERVER['REMOTE_ADDR'],
			'TokenId' => $tokenId['token'],
			'TraceId' => $data['TraceId'],
			'ResultIndex' => $data['ResultIndex'],
		);
		$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) {

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/flightSSR/' . date('Y-m-d-H-i-s') . "_flightSSR_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			//Write Request Logs starts...

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/flightSSR/' . date('Y-m-d-H-i-s') . "_flightSSR_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			//Write Request Logs starts...

		}
		return $response;
	}

	public function GetApiFlightBookingDetails($arrData = array(), $filename = null, $AgencySysid)
	{
		$tokenId = $this->authenticateAPI($AgencySysid);
		$FlightSearchLogFile = new Zend_Session_Namespace('FlightSearchLogFile');
		$logFile = $FlightSearchLogFile->params;
		if ($arrData) {
			$datah = array(
				'EndUserIp' => $_SERVER['REMOTE_ADDR'],
				'TokenId' => $tokenId['token'],
				'BookingId' => $arrData['BookingId'],
			);

			//            echo "<pre>";print_r($datah);exit;
			$data_stringh = json_encode($datah);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, FLIGHT_API_BOOKING_DETAILS);
			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_SSL_VERIFYPEER, false);
			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);
			// echo "<pre>";print_r($response);exit;
			if (FLIGHT_API_LOGS) {

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

		return $response;
	}

	public function cancelFlightBooking($data, $AgencySysid)
	{
		$intCancellationType = $data['CancellationType'];
		$RequestType = $data['requestType'];
		$TOKEN_ID = $this->authenticateAPI($AgencySysid);
		//echo "<pre>"; print_r($data);die('dd');
		//if($intIsLCC == 1){
		$FlightTraceId = $data['FlightTraceId'];
		if ($RequestType == 2) {
			$datah = array(
				"BookingId" => $data['BookingId'],
				"RequestType" => $RequestType,
				"CancellationType" => $intCancellationType,
				"Sectors" => $data['sectorsSelectors'],
				"TicketId" => $data['TicketId'],
				"Remarks" => $data['remarks'],
				"EndUserIp" => $_SERVER['REMOTE_ADDR'],
				"TokenId" => $TOKEN_ID['token'],
			);
		} else {
			$datah = array(
				"BookingId" => $data['BookingId'],
				"Source" => $data['source'],
				"RequestType" => $RequestType,
				"Remarks" => $data['remarks'],
				"EndUserIp" => $_SERVER['REMOTE_ADDR'],
				"TokenId" => $TOKEN_ID['token'],
			);
		}

		$cURL = FLIGHT_API_BOOKING_CHANGE_REQUEST;
		//echo "<pre>"; print_r($datah); exit;
		$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_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);
		$responseTBO = json_decode($outputH, true);
		//echo $outputH;

		//echo "<pre>"; print_r($responseTBO); exit;
		if (FLIGHT_API_LOGS) {

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_SendChange_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			//Write Request Logs starts...

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_SendChange_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			//Write Request Logs starts...

		}

		$FlightCancelSession = new Zend_Session_Namespace('FlightCancelSession');
		$FlightCancelSession->params = $responseTBO;
		$intChangeRequestId = isset($responseTBO['Response']['TicketCRInfo'][0]['ChangeRequestId']) ? $responseTBO['Response']['TicketCRInfo'][0]['ChangeRequestId'] : '';
		$ResponseStatus = isset($responseTBO['Response']['ResponseStatus']) ? $responseTBO['Response']['ResponseStatus'] : '';
		$TicketCRInfo = isset($responseTBO['Response']['TicketCRInfo']) ? $responseTBO['Response']['TicketCRInfo'] : array();
		$objFlight = new Travel_Model_FlightMaster();
		if (!empty($ResponseStatus) && $ResponseStatus == 1) {
			if (isset($data['TicketId']) && !empty($data['TicketId'])) {
				foreach ($data['TicketId'] as $key => $value) {
					$TicketId = $TicketCRInfo[$key]['TicketId'];
					$ChangeRequestId = $TicketCRInfo[$key]['ChangeRequestId'];
					$ChangeRequestStatus = $TicketCRInfo[$key]['ChangeRequestStatus'];
					$datah = array(
						"ChangeRequestId" => $ChangeRequestId,
						"EndUserIp" => $_SERVER['REMOTE_ADDR'],
						"TokenId" => $TOKEN_ID['token'],
					);
					$data_stringh = json_encode($datah);
					$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_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),
					));
					$output = curl_exec($ch);
					$responseCan = json_decode($output, true);
					if (FLIGHT_API_LOGS) {

						//Write Request Logs starts...
						$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_GetChangeRequestStatus_request.json";
						Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
						//Write Request Logs starts...

						//Write Request Logs starts...
						$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_GetChangeRequestStatus_response.json";
						Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $output);
						//Write Request Logs starts...

					}
					//echo "<pre>"; print_r($responseCan); exit;
					$update = array(
						"ChangeRequestId" => $ChangeRequestId,
						"ChangeRequestRes" => json_encode($responseCan),
						"ChangeRequestStatus" => $ChangeRequestStatus,
					);
					$where = "TicketId = " . $TicketId; //exit;
					$updated = $objFlight->UpdateFlightData('tbl_flight_booking_customer', $update, $where);
				}
			}

			return $responseTBO;
			//echo "<pre>"; print_r($responseTBO); exit;
		}

		return $responseTBO;
	}
	public function CancellationChargesRequest($data, $AgencySysid)
	{

		$intCancellationType = $data['CancellationType'];
		$RequestType = $data['requestType'];
		$FlightTraceId = $data['FlightTraceId'];
		$TOKEN_ID = $this->authenticateAPI($AgencySysid);
		//echo "<pre>"; print_r($data);die('dd');
		//if($intIsLCC == 1){

		$datah = array(
			"BookingId" => $data['BookingId'],
			"RequestType" => $intCancellationType,
			"BookingMode" => 5,
			"EndUserIp" => $_SERVER['REMOTE_ADDR'],
			"TokenId" => $TOKEN_ID['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_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);
		$responseTBO = json_decode($outputH, true);
		//echo $outputH;

		if (FLIGHT_API_LOGS) {

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_GetCancellationCharges_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			//Write Request Logs starts...

			//Write Request Logs starts...
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightCancel/' . date('Y-m-d-H-i-s') . "_GetCancellationCharges_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
			//Write Request Logs starts...

		}
		//return $responseTBO;
		return $responseTBO;
	}

	public function GetAgencyBalance($arrData = array(), $AgencySysid)
	{
		$FlightTraceId = $arrData['FlightTraceId'];
		$tokenId = $this->authenticateAPI($AgencySysid);
		if ($arrData) {
			$datah = array(
				"EndUserIp" => $_SERVER['REMOTE_ADDR'],
				'ClientId' => FLIGHT_API_CLIENT_ID,
				'TokenId' => $tokenId['token'],
				'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) {

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/AgencyBalance/' . date('Y-m-d-H-i-s') . "_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/AgencyBalance/' . date('Y-m-d-H-i-s') . "_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...

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

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

		return $response;
	}

	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 '';
		}

		$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 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 calculateServiceTax($intAmount, $percentAgencySTax)
	{
		$percentAgencySTax = !empty($percentAgencySTax) ? $percentAgencySTax : 18;
		$intAmount = (float) $intAmount;
		$intNetSTax = (($intAmount * $percentAgencySTax) / 100);
		$BasePriceWithSTax = $intNetSTax + $intAmount;
		$arrSerciceTax = array(
			"BasePrice" => $intAmount,
			"serviceTaxAmount" => $intNetSTax,
			"BasePriceWithSTax" => $BasePriceWithSTax,
			"ServiceTaxPercentage" => $percentAgencySTax,
		);
		return $arrSerciceTax;
	}
	function calculateMarkup($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 calculateMarkupTBO($data, $action = null)
	{
		//
		$B2BType = $this->_session->B2BType;

		$getMarkupNew = isset($data['getMarkupNew']['data']) ? $data['getMarkupNew']['data'] : [];
		$arrApiServiceTax = 18; //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['TdsOnCommission']) ? $data['TdsOnCommission'] : 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;

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

		$NetCommission = ($intCommissionEarned);
		$intGTXMarkUp = 0;

		$AdminComminOnTDS = 0;
		$AdminComminAmount = 0;
		$totalAgencyMarkUp = 0;
		$TotalCommssionVal = 0;
		//die;
		if (count($getMarkupNew) > 0) {
			foreach ($getMarkupNew as $key => $AgencyMarkups) {
				if ($AgencyMarkups['PlanType'] == 1) {
					$ItemSourceType = $AgencyMarkups['ItemSourceType']; // 1 domestic / 2 international
					if ($ItemSourceType == 1 && $interNationalSearch == '') { /// for domestic
						$intCommssionVal = ($AgencyMarkups['Commission']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
						$TotalCommssionVal += $intCommssionVal;
						$intAgencyMarkUp = ($AgencyMarkups['MarkUpValue'] * $intMemberCount); // Agency Fix Mark UP...
						$totalAgencyMarkUp += $intAgencyMarkUp;
						$AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
						$AdminComminOnTDS += (($TdsOnPLB * $intCommssionVal) / 100);
					} elseif ($ItemSourceType == 2 && $interNationalSearch == 1) { /// for International
						$intCommssionVal = ($AgencyMarkups['Commission']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
						$TotalCommssionVal += $intCommssionVal;
						$intAgencyMarkUp = ($AgencyMarkups['MarkUpValue'] * $intMemberCount); // Agency Fix Mark UP...
						$totalAgencyMarkUp += $intAgencyMarkUp;
						$AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
						$AdminComminOnTDS += (($TdsOnPLB * $intCommssionVal) / 100);
					}
				}
			}
		}
		// For Agency MarkUps...
		$Agencycommission = ($NetCommission - $AdminComminAmount);
		$TdsOnPLB_ = ($TdsOnPLB); //- $AdminComminOnTDS

		$totalAgentMarkUp = 0;
		$TotalCommssionVal_ag = 0;
		$AdminComminAmount_ag = 0;
		if (count($arrAgentMarkups) > 0 && $B2BType != 2) {
			foreach ($arrAgentMarkups as $key => $AgtMarkups) {
				$intCommssionType = $AgtMarkups['CommssionType']; // 2 For percentage
				$intCommssionVal_ag = 0; //($AgtMarkups['CommssionVal']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
				$intAgencyMarkUp = ($AgtMarkups['StdMarkUpPer'] * $intMemberCount); // Agency Fix Mark UP...
				$totalAgentMarkUp += $intAgencyMarkUp;
				$TotalCommssionVal_ag += $intCommssionVal_ag;
				if ($intCommssionType == 2) {
					$AdminComminAmount_ag += (($Agencycommission * $intCommssionVal_ag) / 100);
				}
			}
		} else {
			$intCommssionVal_ag = 0;
			$TotalCommssionVal_ag += $intCommssionVal_ag;
			$AdminComminAmount_ag += (($Agencycommission * $intCommssionVal_ag) / 100);
		}

		//echo '<pre>';print_r(($arrAgentMarkups));echo '</pre>';
		if ($interNationalSearch == 1 && $action != 'Review') {
			$totalAgencyMarkUp = ($totalAgencyMarkUp * $intFlightRoute);
			$totalAgentMarkUp = ($totalAgentMarkUp * $intFlightRoute);
			$intGTXMarkUp = ($intGTXMarkUp * $intFlightRoute);
		}
		$calculateReverse = $this->calculateReverse($TripjackMarkup, $arrApiServiceTax);

		$apiMarkup = $calculateReverse['NetPrice'];
		$apiTaxOnMarkup = $calculateReverse['TaxAmount'];
		$arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
		//echo '<pre>';print_r(($data));echo '</pre>';die;
		$intGSTOnAgencyFixMarkUp = $arrGSTOnAgencyFixMarkUp['serviceTaxAmount'];

		$arrGSTOnAgentFixMarkUp = $this->calculateServiceTax($totalAgentMarkUp, $arrApiServiceTax);
		$intGSTOnAgentFixMarkUp = 0; //$arrGSTOnAgentFixMarkUp['serviceTaxAmount'];

		$arrSTaxOnGTXMarkUp = $this->calculateReverse($intGTXMarkUp, $arrApiServiceTax);
		$intGTXMarkUp = $arrSTaxOnGTXMarkUp['NetPrice'];
		$intSTaxOnGTXMarkUp = $arrSTaxOnGTXMarkUp['TaxAmount'];

		$intTotalGST = $intGSTOnAgencyFixMarkUp + $apiTaxOnMarkup;

		$CostToCustomer = ($intOfferedFare + $apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $intGSTOnAgencyFixMarkUp + $intGTXMarkUp + $intSTaxOnGTXMarkUp + $AdminComminAmount + $TdsOnPLB_);
		$intAgencyCommisionEarned = ($apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $AdminComminAmount + $TdsOnPLB_);
		$agencyPublishFare = ($intOfferedFare + $apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $intGSTOnAgencyFixMarkUp + $AdminComminAmount + $TdsOnPLB_);
		$CostToCompany = ($CostToCustomer - $intAgencyCommisionEarned);
		$dataArr = array(
			'apiMarkup' => ($apiMarkup),
			'apiTaxOnMarkup' => ($apiTaxOnMarkup),
			'IntNetCommission' => ($NetCommission), // GTX Agency Commission Retain %
			'IntCommissionValInPercentage' => ($intCommssionVal), // GTX Agency Commission Retain % 
			'IntCommission' => ($AdminComminAmount), // GTX agency Comm in Amount
			'IntAgencyFixMarkUp' => ($totalAgencyMarkUp),
			'IntTaxOnAgencyFixMarkUp' => ($intGSTOnAgencyFixMarkUp),
			"intGTXMarkUp" => ($intGTXMarkUp),
			"intSTaxOnGTXMarkUp" => $intSTaxOnGTXMarkUp,
			"intTotalGST" => ($intTotalGST),
			"PublishFare" => ($CostToCustomer),
			"CostToCustomer" => ($CostToCustomer),
			"BaseFareCal" => (($CostToCustomer - $intAgencyCommisionEarned)),
			"intCommisionEarnedForAgency" => ($intAgencyCommisionEarned),
			"CostToCompany" => ($CostToCompany),
			"intOfferedFare" => $intOfferedFare,
			"intPublishFare" => $intPublishedFare,
			"agencyPublishFare" => $agencyPublishFare,
			"TripjackMarkup" => $TripjackMarkup,
			"TripjackCommission" => $TripjackCommission,
			"TripjackTDS" => $TdsOnPLB_,
			"BR" => '=',
			"AgentOfferedFare" => $agencyPublishFare,
			"Agencycommission" => $Agencycommission,
			"TotalCommssionVal_ag" => $TotalCommssionVal_ag,
			"AdminComminAmount_ag" => $AdminComminAmount_ag,
			'totalAgentMarkUp' => ($totalAgentMarkUp),
			'intGSTOnAgentFixMarkUp' => ($intGSTOnAgentFixMarkUp),
			'AgentB2CEarning' => ($AdminComminAmount_ag + $totalAgentMarkUp),
			'CostToAgentCustomer' => ($agencyPublishFare + $intGSTOnAgentFixMarkUp + $totalAgentMarkUp + $AdminComminAmount_ag),
			'CostToAgent' => ($agencyPublishFare),
		);
		return $dataArr;
	}
	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, $action = null)
	{
		$B2BType = $this->_session->B2BType;
		$AddMarkup = isset($data['AddMarkup']) ? $data['AddMarkup'] : [];
		$markup_b2b = isset($AddMarkup['markup_b2b']) ? $AddMarkup['markup_b2b'] : 0;
		$getMarkupNew = isset($data['getMarkupNew']['data']) ? $data['getMarkupNew']['data'] : [];
		$arrApiServiceTax = 18; //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;

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

		$NetCommission = ($intCommissionEarned);
		if ($intFlightRoute == 3) {
			$markup_b2b = 0;
		}
		// For GTX MarkUps...
		$intGTXMarkUp = 0;

		$AdminComminAmount = 0;
		$totalAgencyMarkUp = 0;
		$TotalCommssionVal = 0;
		//echo '<pre>';print_r(($getMarkupNew));echo '</pre>';
		if (count($getMarkupNew) > 0) {
			foreach ($getMarkupNew as $key => $AgencyMarkups) {
				if ($AgencyMarkups['PlanType'] == 1) {
					$ItemSourceType = $AgencyMarkups['ItemSourceType']; // 1 domestic / 2 international
					if ($ItemSourceType == 1 && $interNationalSearch == '') { /// for domestic
						$TDSApplied = !empty($AgencyMarkups['TDS']) ? $AgencyMarkups['TDS'] : 0; // TDS flag from GTX
						$intCommssionVal = ($AgencyMarkups['Commission']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
						$TotalCommssionVal += $intCommssionVal;
						$intAgencyMarkUp = ($AgencyMarkups['MarkUpValue'] * $intMemberCount); // Agency Fix Mark UP...
						$totalAgencyMarkUp += $intAgencyMarkUp;
						$AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
					} elseif ($ItemSourceType == 2 && $interNationalSearch == 1) { /// for International
						$TDSApplied = !empty($AgencyMarkups['TDS']) ? $AgencyMarkups['TDS'] : 0;
						$intCommssionVal = ($AgencyMarkups['Commission']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
						$TotalCommssionVal += $intCommssionVal;
						$intAgencyMarkUp = ($AgencyMarkups['MarkUpValue'] * $intMemberCount); // Agency Fix Mark UP...
						$totalAgencyMarkUp += $intAgencyMarkUp;
						$AdminComminAmount += (($NetCommission * $intCommssionVal) / 100);
					}
				}
			}
		}
		// if((int) $TDSApplied == 1){
		// 	$TdsOnPLB = $TdsOnPLB;
		// }else{
		// 	$TdsOnPLB = 0;
		// }
		// print_r($TdsOnPLB);
		// var_dump($TDS);
		// die;

		// if (count($arrAgencyMarkups) > 0) {
		// 	foreach ($arrAgencyMarkups as $key => $AgencyMarkups) {
		// 		$AgentMarkups = isset($arrAgentMarkups[$key]) ? $arrAgentMarkups[$key] : '';

		// 		$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);
		// 		}
		// 	}
		// }
		$Agencycommission = ($NetCommission - $AdminComminAmount);
		//echo '<pre>';print_r(($totalAgencyMarkUp));echo '</pre>';
		$totalAgentMarkUp = 0;
		$TotalCommssionVal_ag = 0;
		$AdminComminAmount_ag = 0;
		if (count($arrAgentMarkups) > 0 && $B2BType != 2) {
			foreach ($arrAgentMarkups as $key => $AgtMarkups) {
				$intCommssionType = $AgtMarkups['CommssionType']; // 2 For percentage
				$intCommssionVal = 0; //($AgtMarkups['CommssionVal']); // Percntage Value For Agency Commision From Actual Commision Retuned From API...
				$intAgencyMarkUp = ($AgtMarkups['StdMarkUpPer'] * $intMemberCount); // Agency Fix Mark UP...
				$totalAgentMarkUp += $intAgencyMarkUp;
				$TotalCommssionVal_ag += $intCommssionVal;
				if ($intCommssionType == 2) {
					$AdminComminAmount_ag += (($Agencycommission * $intCommssionVal) / 100);
				}
			}
		} else {
			$intCommssionVal = 0;
			$TotalCommssionVal_ag += $intCommssionVal;
			$AdminComminAmount_ag += (($Agencycommission * $intCommssionVal) / 100);
		}

		if ($interNationalSearch == 1 && $action != 'Review') {
			$totalAgencyMarkUp = ($totalAgencyMarkUp * $intFlightRoute);
			$totalAgentMarkUp = ($totalAgentMarkUp * $intFlightRoute);
			$intGTXMarkUp = ($intGTXMarkUp * $intFlightRoute);
			$markup_b2b = ($markup_b2b * $intFlightRoute);
		}
		$markup_b2b = ($markup_b2b * $intMemberCount);
		$calculateReverse = $this->calculateReverse($TripjackMarkup, $arrApiServiceTax);
		$apiMarkup = $calculateReverse['NetPrice'];
		$apiTaxOnMarkup = $calculateReverse['TaxAmount'];

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

		$arrGSTOnAgencyFixMarkUp = $this->calculateServiceTax($totalAgencyMarkUp, $arrApiServiceTax);
		//echo '<pre>';print_r(($data));echo '</pre>';die;IntTaxOnAgencyFixMarkUp
		$intGSTOnAgencyFixMarkUp = ($arrGSTOnAgencyFixMarkUp['serviceTaxAmount'] +  $AddiaxOnMarkup);
		$totalAgencyMarkUp = ($totalAgencyMarkUp + $AddiMarkup);

		$arrGSTOnAgentFixMarkUp = $this->calculateServiceTax($totalAgentMarkUp, $arrApiServiceTax);
		$intGSTOnAgentFixMarkUp = 0; //$arrGSTOnAgentFixMarkUp['serviceTaxAmount'];

		$arrSTaxOnGTXMarkUp = $this->calculateReverse($intGTXMarkUp, $arrApiServiceTax);
		$intGTXMarkUp = $arrSTaxOnGTXMarkUp['NetPrice'];
		$intSTaxOnGTXMarkUp = $arrSTaxOnGTXMarkUp['TaxAmount'];

		$intTotalGST = $intGSTOnAgencyFixMarkUp + $apiTaxOnMarkup;

		$CostToCustomer = ($intOfferedFare + $apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $intGSTOnAgencyFixMarkUp + $intGTXMarkUp + $intSTaxOnGTXMarkUp + $AdminComminAmount + $TdsOnPLB);
		$intAgencyCommisionEarned = ($apiMarkup + $apiTaxOnMarkup + $totalAgencyMarkUp + $AdminComminAmount + $TdsOnPLB);
		$CostToCompany = ($CostToCustomer - $intAgencyCommisionEarned);
		$dataArr = array(
			'apiMarkup' => ($apiMarkup),
			'apiTaxOnMarkup' => ($apiTaxOnMarkup),
			'IntNetCommission' => ($NetCommission), // GTX Agency Commission Retain %
			'IntCommissionValInPercentage' => ($TotalCommssionVal), // GTX Agency Commission Retain % 
			'IntCommission' => ($AdminComminAmount), // GTX agency Comm in Amount
			'IntAgencyFixMarkUp' => ($totalAgencyMarkUp),
			'IntTaxOnAgencyFixMarkUp' => ($intGSTOnAgencyFixMarkUp),
			"intGTXMarkUp" => ($intGTXMarkUp),
			"intSTaxOnGTXMarkUp" => $intSTaxOnGTXMarkUp,
			"intTotalGST" => ($intTotalGST),
			"PublishFare" => ($CostToCustomer),
			"CostToCustomer" => ($CostToCustomer),
			"BaseFareCal" => (($CostToCustomer - $intAgencyCommisionEarned)),
			"intCommisionEarnedForAgency" => ($intAgencyCommisionEarned),
			"CostToCompany" => ($CostToCompany),
			"intOfferedFare" => $intOfferedFare,
			"intPublishFare" => $intPublishedFare,
			"TripjackMarkup" => $TripjackMarkup,
			"TripjackCommission" => $TripjackCommission,
			"TripjackTDS" => $TdsOnPLB,
			"BR" => '=',
			"Agencycommission" => $Agencycommission,
			"TotalCommssionVal_ag" => $TotalCommssionVal_ag,
			"AdminComminAmount_ag" => $AdminComminAmount_ag,
			'totalAgentMarkUp' => ($totalAgentMarkUp),
			'intGSTOnAgentFixMarkUp' => ($intGSTOnAgentFixMarkUp),
			'AgentB2CEarning' => ($AdminComminAmount_ag + $totalAgentMarkUp),
			'CostToAgentCustomer' => ($CostToCustomer + $intGSTOnAgentFixMarkUp + $totalAgentMarkUp),
			'CostToAgent' => ($CostToCustomer - $AdminComminAmount_ag),
			"AddiMarkup" => $AddiMarkup,
			"AddiTaxOnMarkup" => $AddiaxOnMarkup,
			"IntAdddimarkup" => (float)$markup_b2b,
			"TDSApplied" => (int)$TDSApplied,
		);
		//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;
	}


	function calculateMarkupTripJackInt($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 GetApiFlightsFareQuoteTripJack($arrData = array())
	{
		if ($arrData) {

			$priceIdArr = $arrData['TraceId'];
			$FlightTraceId = $arrData['SearchTraceId'];
			$datah = array(
				'priceIds' => $priceIdArr,
			);

			$data_stringh = json_encode($datah);
			//echo "<pre>";print_r($arrData);die;
			$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);

			if (FLIGHT_API_LOGS) {

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareReview/' . date('Y-m-d-H-i-s') . "_Review_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightFareReview/' . date('Y-m-d-H-i-s') . "_Review_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
		}
		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
		}

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

		$logParams = [
			"user_id"      => 1,
			"custom_error" => ($ResponseStatus == 1) ? "Get Flight Fare Quote Response success" : "Get Flight Fare Quote Response failed",
			'error'        => $ErrorMessage,
			"text_udf"     => ['response' => $response], // Response
			"char_udf"     => ['request' => $datah], // Request
			"udf1"         => $FlightTraceId,
			"status"       => ($ResponseStatus == 1) ? 2 : 1,
		];
		Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);

		return $response;
	}

	public function GetSeatMapFlightsTripJack($arrData = array())
	{
		if ($arrData) {
			$datah = array(
				'bookingId' => $arrData['bookingId'],
			);

			$data_stringh = json_encode($datah);
			$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);
			$response = json_decode($outputH, true);
			if (FLIGHT_API_LOGS) {

				//Write Request Logs starts...
				$strFilePath = "flight/FlightSeat/" . date('Y-m-d-H-i-s') . "_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') . "_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;
		}
	}
	public function apiFlightTicketTripJack($data)
	{

		$SelectedMealSessionNew = $data['SelectedMealSessionNew'];
		$SelectedBaggSessionNew = $data['SelectedBaggSessionNew'];
		$FlightTraceId = $data['SearchTraceId'];

		$interNationalSearch = $data['IsInternational'];

		$selectedSeatSession = $data['selectedSeatSession'];

		$bookingId = $data['FlightBookingData'][0]['bookingId_TJ'];
		$isAdobrMandatory = $data['FlightBookingData'][0]['isAdobrMandatory'];
		$isCdobrMandatory = $data['FlightBookingData'][0]['isCdobrMandatory'];
		$isIdobrMandatory = $data['FlightBookingData'][0]['isIdobrMandatory'];
		$isgstapply = isset($data['CustomerSession'][0]['isgstapply']) ? $data['CustomerSession'][0]['isgstapply'] : 0;
		// echo '<pre>';
		// print_r($data['FlightBookingData'][0]);die;
		$arrPassengers = [];
		$deliveryInfo = [];
		$ARR_SALUTION = unserialize(ARR_SALUTION_TJ);
		$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
		if ($bookingId && $data) {
			$SeatAmount = 0;
			if ($data['CustomerSession']) {
				foreach ($data['CustomerSession'] as $key => $val) {
					$value = $val;
					$strPaxDateOfBirth = $value['DOB'];
					if ($value['paxType'] == 1) {
						$paxType = 'ADULT';
						$paxTitle = trim($ARR_SALUTION[$value['Salutation']], ".");
						if ($key == 0) {
							$deliveryInfo['emails'][$key] = trim($value['EmailId']);
							$deliveryInfo['contacts'][$key] =  trim($value['countryCode']) . '' . trim($value['Contacts']);
						}
						if ($isAdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}
					if ($value['paxType'] == 2) {
						$paxType = 'CHILD';
						$paxTitle = trim($ARR_SALUTION_CHILD[$value['Salutation']], ".");
						if ($isCdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}
					if ($value['paxType'] == 3) {
						$paxType = 'INFANT';
						$paxTitle = trim($ARR_SALUTION_CHILD[$value['Salutation']], ".");
						if ($isIdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}

					$arrPassengers[$key] = [
						'ti' => $paxTitle,
						'fN' => trim($value['FirstName']),
						'lN' => trim($value['LastName']),
						'pt' => $paxType,
					];
					if ($value['paxType'] == 1) {
						if ($isAdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}
					if ($value['paxType'] == 2) {
						if ($isCdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}
					if ($value['paxType'] == 3) {
						if ($isIdobrMandatory == 1) {
							$arrPassengers[$key]['dob'] = $strPaxDateOfBirth;
						}
					}

					$BaggArr = [];
					if (!empty($SelectedBaggSessionNew)) {
						foreach ($SelectedBaggSessionNew as $segmentid => $val) {
							if (isset($val[$key + 1]) && !empty($val[$key + 1])) {
								$bagg = $val[$key + 1];
								$BaggArr[] = array('key' => $bagg['key'], 'code' => $bagg['Code']);
							}
						}
					}
					$MealArr = [];
					if (!empty($SelectedMealSessionNew)) {
						foreach ($SelectedMealSessionNew as $segmentid => $val) {
							if (isset($val[$key + 1]) && !empty($val[$key + 1])) {
								$meal = $val[$key + 1];
								$MealArr[] = array('key' => $meal['key'], 'code' => $meal['Code']);
							}
						}
					}
					$SeatArr = [];
					if (!empty($selectedSeatSession)) {
						foreach ($selectedSeatSession 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 ($interNationalSearch == 1) {
						$PassportIssue = $value['passporIssue'];
						$PassportExpiry = $value['PassportExpiry'];
						$arrPassengers[$key]['pNum'] = $value['PassportNo'];
						$arrPassengers[$key]['eD'] = $PassportExpiry;
						$arrPassengers[$key]['pid'] = $PassportIssue;
						$arrPassengers[$key]['pNat'] = $value['PassportNationality'];
					}
				}
			}
			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;
			if ($data['FlightBookingData']) {
				foreach ($data['FlightBookingData'] as $amount) {
					$PublishedFare += $amount['FairRules']['intPublishedFare'];
				}
			}
			if ($SelectedBaggSessionNew && !empty($SelectedBaggSessionNew)) {
				foreach ($SelectedBaggSessionNew as $baggage) {
					foreach ($baggage as $val) {
						$baggageAmount += $val['Price'];
					}
				}
			}
			if ($SelectedMealSessionNew && !empty($SelectedMealSessionNew)) {
				foreach ($SelectedMealSessionNew as $meals) {
					foreach ($meals as $val) {
						$mealAmount += $val['Price'];
					}
				}
			}

			$amount =  ($PublishedFare + $baggageAmount + $mealAmount + $SeatAmount);
			$paymentInfos[] = array('amount' => number_format($amount, 2, '.', ''));

			$data = array(
				'bookingId' => $bookingId,
				'paymentInfos' => $paymentInfos,
				'travellerInfo' => $arrPassengers,
				'deliveryInfo' => $deliveryInfo,
			);
			if ($isgstapply == 1) {
				$data['gstInfo'] = $gstInfo;
			}

			// echo '<pre>';
			// print_r($data);
			// echo '</pre>';
			// 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);
			$response = json_decode($outputH, true);

			if (FLIGHT_API_LOGS) {
				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...

				//Write Request Logs starts...
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightTicket/' . date('Y-m-d-H-i-s') . "_FlightTicket_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...

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

				$logParams = [
					"user_id"      => 1,
					"custom_error" => ($ResponseStatus == 1) ? "Flight Ticket Response success" : "Flight Ticket Response failed",
					'error'        => $ErrorMessage,
					"text_udf"     => ['response' => $response], // Response
					"char_udf"     => ['request' => $data], // Request
					"udf1"         => $FlightTraceId,
					"status"       => ($ResponseStatus == 1) ? 2 : 1,
				];
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
			}

			$apiFlightTicketTripJack = new Zend_Session_Namespace('apiFlightTicketTripJack');
			$apiFlightTicketTripJack->params = $response;
			return $response;
		} else {
			return $response = [];
		}
		exit;
	}

	public function bookingDetailsTripJack($response)
	{
		$ResponseStatus = isset($response['status']['success']) ? $response['status']['success'] : '0';

		if ($ResponseStatus == 1) {
			$FlightTraceId = isset($response['SearchTraceId']) ? $response['SearchTraceId'] : '0';
			$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',
				//'Accept-Encoding: gzip',
				'apikey:' . APIKEY,
				'Content-Length: ' . strlen($data_stringh)
			));
			$outputH = curl_exec($ch);
			$responses = json_decode($outputH, true);
			if (FLIGHT_API_LOGS) {
				$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/BookingDetails/' . date('Y-m-d-H-i-s') . "_BookingDetails_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);

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

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

				$logParams = [
					"user_id"      => 1,
					"custom_error" => ($ResponseStatus == 1) ? "Flight Booking Details Response success" : "Flight Booking Details Response failed",
					'error'        => $ErrorMessage,
					"text_udf"     => ['response' => $responses], // Response
					"char_udf"     => ['request' => $data], // Request
					"udf1"         => $FlightTraceId,
					"status"       => ($ResponseStatus == 1) ? 2 : 1,
				];
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);
			}



			return $responses;
		} else {
			return $response;
		}
	}
	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})+$/";
		return preg_match($regex, $gstin);
	}

	function getAgencyData($gtxagencysysid, $SecurityKey = null)
	{
		if ($gtxagencysysid) {
			$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);
			//print_r($responseIV);die;
			$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);
			$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';
		}
	}

	function getAgencyUserData($apiData)
	{
		if ($apiData) {
			$apiDataIV = $apiData;
			//echo '<pre>';print_r($apiDataIV);
			$curl_IV = curl_init(API_AGENT_PROFILE);
			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 getflightlogo($strAirlineCodeLogo)
	{
		$filePath = $_SERVER['DOCUMENT_ROOT'] . "/public/upload/AirlineLogo/";
		if (file_exists($filePath . $strAirlineCodeLogo . ".gif")) {
			$strAirlineLogo = $strAirlineCodeLogo . ".gif";
			$filePath = $this->baseUrl . "public/upload/AirlineLogo/" . $strAirlineLogo;
		} elseif (file_exists($filePath . $strAirlineCodeLogo . ".png")) {
			$strAirlineLogo = $strAirlineCodeLogo . ".png";
			$filePath = $this->baseUrl . "public/upload/AirlineLogo/" . $strAirlineLogo;
		} elseif (file_exists($filePath . $strAirlineCodeLogo . ".jpg")) {
			$strAirlineLogo = $strAirlineCodeLogo . ".jpg";
			$filePath = $this->baseUrl . "public/upload/AirlineLogo/" . $strAirlineLogo;
		} elseif (file_exists($filePath . $strAirlineCodeLogo . ".jpeg")) {
			$strAirlineLogo = $strAirlineCodeLogo . ".jpeg";
			$filePath = $this->baseUrl . "public/upload/AirlineLogo/" . $strAirlineLogo;
		} else {
			$filePath = $this->baseUrl . "public/upload/AirlineLogo/noimage.png";
		}
		return $filePath;
	}

	function AgencyWallaetBalance($SecurityKey)
	{
		if ($SecurityKey) {
			$apiDataIV = array(
				"B2BAgencySysIdKey" => SECURITYKEY,
				"B2CAgencySysIdKey" => $SecurityKey,
			);

			$curl_IV = curl_init(API_GET_AGENCY_BALANCE);
			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 AgencyupdateCreditBalance($data)
	{
		if ($data) {
			$apiDataIV = array(
				"B2BAgencySysIdKey" => SECURITYKEY,
				"B2CAgencySysIdKey" => $data['SecurityKey'],
				"Remark" => $data['Remark'],
				"Amount" => $data['Amount'],
				"PlanType" => $data['PlanType'],
				"UserSysId" => $data['UserSysId'],
				"PaymentMode" => $data['PaymentMode'],
				"RefrenceNo" => $data['RefrenceNo'],
			);
			//echo '<pre>';print_r($apiDataIV);die;
			$curl_IV = curl_init(API_GET_AGENCY_UPDATE_BALANCE);
			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);
			// echo '<pre>';print_r($responseIV);

			// die;
			curl_close($curl_IV);
			$response = Zend_Json::decode($responseIV, true);

			$Walletstatus  = $response['status'];
			$Walletmessage = $response['message'];
			$logParams = [
				"user_id"      => 1,
				"custom_error" => ($Walletstatus == 1) ? "Wallet Dedit success" : "Wallet Dedit failed",
				'error'        => $Walletmessage,
				"text_udf"     => ['response' => $response], // Response
				"char_udf"     => ['request' => $data], // Request
				"udf1"         => $data['FlightTraceId'],
				"status"       => ($Walletstatus == 1) ? 2 : 1,
			];
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->CreateLogs($logParams);



			return $response;
		} else {
			return 'Bad request';
		}
	}

	public function searchApiFlightsSeriesFare($arrSessionData = array(), $tripType = null)
	{
		$SearchFlightTraceId = new Zend_Session_Namespace('SearchFlightTraceId');
		$FlightTraceId = $SearchFlightTraceId->params;

		$strDepatureDate = isset($arrSessionData['strDepatureDate'][0]) ? $arrSessionData['strDepatureDate'][0] : '';
		$route = isset($arrSessionData['route']) ? $arrSessionData['route'] : '';
		// echo '<pre>';print_r($arrSessionData);
		// echo $tripType;
		if (isset($arrSessionData['from_city_'])) {
			$from_city = isset($arrSessionData['from_city_'][0]) ? explode('__', $arrSessionData['from_city_'][0]) : array();
		} else {
			$from_city = isset($arrSessionData['from_city'][0]) ? explode('__', $arrSessionData['from_city'][0]) : 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'][0]) && !empty(trim($arrSessionData['strDepatureDate'][0]))) ? trim($arrSessionData['strDepatureDate'][0])  : '';
		$InwardDate = (isset($arrSessionData['strReturnDate'][0]) && !empty(trim($arrSessionData['strReturnDate'][0]))) ? trim($arrSessionData['strReturnDate'][0])  : '';
		$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;
		$CurrentSeat = !empty($totaltrveller) ? $totaltrveller : '';

		$postFields = array(
			'SecurityKey' => $SECURITYKEY,
			'FlightType' => 1,
			'FromDate' => date('Y-m-d'),
			'CurrentSeat' => $CurrentSeat,
		);
		//$this->postFields .= "?SecurityKey=" . $SECURITYKEY;
		//$this->postFields .= "&OFAC=" . $SeriesFareSecotrs[0];
		if (isset($tripType) && $tripType == 'roundtrip') {
			$postFields['OFAC'] = $SeriesFareSecotrs[1];
			$postFields['OTAC'] = $SeriesFareSecotrs[0];
			$postFields['SearchDate'] = $InwardDate;
			//$this->postFields .= "&OTAC=" . $SeriesFareSecotrs[1];
		} else {
			$postFields['OFAC'] = $SeriesFareSecotrs[0];
			$postFields['OTAC'] = $SeriesFareSecotrs[1];
			$postFields['SearchDate'] = $SearchDate;
			//$this->postFields .= "&OTAC=" . $SeriesFareSecotrs[1];
			//$this->postFields .= "&IFAC=" . $SeriesFareSecotrs[1];
			//$this->postFields .= "&ITAC=" . $SeriesFareSecotrs[2];
		}
		//$this->postFields .= "&FlightType=" . $FlightType;
		// $this->postFields .= "&FlightType=1";
		// $this->postFields .= "&FromDate=" . date('Y-m-d');
		// $this->postFields .= "&SearchDate=" . $SearchDate;
		// $this->postFields .= "&CurrentSeat=" . $CurrentSeat;
		// if($route == 1 || $route == 2){
		// $this->postFields .= "&DepatureDate=" . $strDepatureDate;
		// }
		// echo '<pre>';
		// print_r($postFields);
		// die;
		$URL = 'http://gtxapi.hellogtx.com/api/v2/index/?' . http_build_query($postFields);
		//$URL = 'http://gtxapi.hellogtx.com/api/v2/index/' . $this->postFields;
		// echo '<pre>';
		// print_r($URL);
		// 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);
		// echo '<pre>';print_r($outputH);
		// echo '<pre>';print_r($response);  die('d');
		if (FLIGHT_API_LOGS) {
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/SeriesFare/' . date('Y-m-d-H-i-s') . "_FlightSearch_request.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
			$strFilePath = "flight/SearchParam/" . $FlightTraceId . '/FlightSearch/SeriesFare/' . date('Y-m-d-H-i-s') . "_FlightSearch_response.json";
			Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
		}

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


		return $response;
	}

	public function GetAgencyInventorySector($FlightType)
	{
		$SECURITYKEY = SECURITYKEY;
		$this->postFields = "?SecurityKey=" . $SECURITYKEY;
		$this->postFields .= "&FlightType=" . $FlightType;
		$URL = 'http://gtxapi.hellogtx.com/api/v2/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 GetApiFlightsFareQuoteSeriesFare($arrData = array())
	{
		if ($arrData) {

			$priceIdArr = $arrData['TraceId'];

			$id = (isset($priceIdArr[0]) && ($priceIdArr[0]) != '') ? explode('_', $priceIdArr[0]) : '';
			if (isset($id[0]) && !empty($id[0])) {

				$curl = curl_init();

				curl_setopt_array($curl, array(
					CURLOPT_URL => "http://api.hellogtx.com/api/v1/flightinventory/flightinventories/" . $id[0] . "/",
					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);
			}
		}
	}
	public function CheckInventorycheckRetriveUpdate($FlightBookingData = array(), $sessionFlightSearchParams = array())
	{
		$SECURITYKEY = SECURITYKEY;
		$apiTraceId = explode('_', $FlightBookingData[0]['apiTraceId']);

		$adults = $sessionFlightSearchParams['adults'];
		$childs = $sessionFlightSearchParams['childs'];
		$infants = $sessionFlightSearchParams['infants'];
		$FromDate = explode('/', $FlightBookingData[0]['FromDate']);
		$FromDate1 = trim($FromDate[2] . '-' . $FromDate[1] . '-' . $FromDate[0]);
		$this->postFields = "?SecurityKey=" . $SECURITYKEY;
		$this->postFields .= "&FlightType=1";
		$this->postFields .= "&FromDate=" . $FromDate1;
		$this->postFields .= "&id=" . $apiTraceId[1];
		$this->postFields .= "&adult=" . $adults;
		$this->postFields .= "&child=" . $childs;
		$this->postFields .= "&infant=" . $infants;
		$URL = 'http://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 = json_decode($response, 1);
		return $resultset;
	}

	public function CheckInventorycheckRetriveUpdateNew($FlightBookingData = array(), $sessionFlightSearchParams = array())
	{
		$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=1";
				$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($apiTraceId);
				$URL = 'http://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 CheckSoldInventory($bookingId)
	{
		$SECURITYKEY = SECURITYKEY;
		$this->postFields = "?RefNo=" . $bookingId;
		$URL = 'http://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 CheckReleaseInventory($bookingId)
	{
		$SECURITYKEY = SECURITYKEY;
		$this->postFields = "?RefNo=" . $bookingId;
		$URL = 'http://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 bookingDetailsSeriesFare($FlightBookingData, $response)
	{

		$SourceAirportCode = trim($FlightBookingData[0]['SourceAirportCode']);
		$DestAirportCode = trim($FlightBookingData[0]['DestAirportCode']);
		$OnwardGroupPNR = trim($FlightBookingData[0]['OnwardGroupPNR']);
		$bookingId = trim($FlightBookingData[0]['bookingId']);
		$ARR_SALUTION = unserialize(ARR_SALUTION_TJ);
		$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
		$passanger = $pnrDetails = array();
		if (isset($FlightBookingData[0]['Segments']) && !empty($FlightBookingData[0]['Segments'])) {
			foreach ($FlightBookingData[0]['Segments'] as $sskey => $ssVal) {
				$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,
				'DOB' => isset($val['DOB']) ? $val['DOB'] : '',
			);
		}
		$response = array(
			'status' => array('success' => 1),
			'itemInfos' => array('AIR' => array('travellerInfos' => $passanger)),
			'order' => array('bookingId' => $bookingId),
		);

		return $response;
	}

	public function bookingDetailsSeriesFareNew($FlightBookingData, $response)
	{
		$passanger = $bookingId = $pnrDetails = array();
		if ($FlightBookingData) {
			foreach ($FlightBookingData as $Data) {
				$SourceAirportCode = trim($Data['SourceAirportCode']);
				$DestAirportCode = trim($Data['DestAirportCode']);
				$OnwardGroupPNR = trim($Data['OnwardGroupPNR']);
				$bookingId[] = trim($Data['bookingId']);
				$ARR_SALUTION = unserialize(ARR_SALUTION_TJ);
				$ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);


				if (isset($Data['Segments']) && !empty($Data['Segments'])) {
					foreach ($Data['Segments'] as $sskey => $ssVal) {
						//echo '<pre>';print_r($ssVal);
						$pnrDetails[trim($ssVal['originAirportCode']) . '-' . trim($ssVal['destinationAirportCode'])] = $OnwardGroupPNR;
					}
				} else {
					$pnrDetails = array($SourceAirportCode . '-' . $DestAirportCode => $OnwardGroupPNR);
				}
			}
		}
		// $SourceAirportCode = trim($FlightBookingData[0]['SourceAirportCode']);
		// $DestAirportCode = trim($FlightBookingData[0]['DestAirportCode']);
		// $OnwardGroupPNR = trim($FlightBookingData[0]['OnwardGroupPNR']);
		// $bookingId = trim($FlightBookingData[0]['bookingId']);
		// $ARR_SALUTION = unserialize(ARR_SALUTION_TJ);
		// $ARR_SALUTION_CHILD = unserialize(ARR_SALUTION_CHILD);
		// $passanger = $pnrDetails = array();
		// if (isset($FlightBookingData[0]['Segments']) && !empty($FlightBookingData[0]['Segments'])) {
		//     foreach ($FlightBookingData[0]['Segments'] as $sskey => $ssVal) {
		//         $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,
				'DOB' => isset($val['DOB']) ? $val['DOB'] : '',
			);
		}
		$response = array(
			'status' => array('success' => 1),
			'itemInfos' => array('AIR' => array('travellerInfos' => $passanger)),
			'order' => array('bookingId' => $bookingId, 'status' => 'SUCCESS'),
		);
		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 getSupportContactData($PlanType, $MarketType, $ItemSourceType)
	{
		$result = array();
		$SupportNumber = $_SESSION['sessionSupportContact']['params']['data']['MasterDate']['SupportNumber'];
		foreach ($SupportNumber as $key => $val) {
			if ($val['PlanType'] == $PlanType && $val['MarketType'] == $MarketType) {
				$result = $val;
			}
		}
		return $result;
	}

	public function getAdditionalMarkup()
	{
		$select = $this->db->select()->from("tbl_manage_fare", ['id', 'faretype', 'markup_b2c', 'markup_b2b', 'showhide_b2b', 'showhide_b2c']);
		$select->where("status=?", 1);
		$select->order("id", 'ASC');
		$result = $this->db->fetchAll($select);
		$finalArr = [];
		$faretypeArr = [];
		if ($result) {
			foreach ($result as $key => $value) {
				$finalArr[$value['faretype']] = $value;
				if ($value['showhide_b2b'] == 1) {
					$faretypeArr[] = $value['faretype'];
				}
			}
		}
		return ['finalArr' => $finalArr, 'faretypeArr' => $faretypeArr];
	}
	public function GetAmendmentChargesSeriesFare($arrData = array(), $FlightBooking = array())
	{
		if ($arrData) {

			$paxDetailArray = (isset($arrData['paxDetailArray']) && !empty($arrData['paxDetailArray'])) ? $arrData['paxDetailArray'] : array();
			$passenger = $FlightBooking['passenger'];
			$Adult = 0;
			$Child = 0;
			$Infant = 0;
			if ($passenger) {
				foreach ($passenger as $keys => $value) {
					$paxName_ = trim($value['FirstName']) . '-' . trim($value['LastName']);
					$IsPaxSelected = isset($paxDetailArray[$paxName_]) ? $paxDetailArray[$paxName_] : '';
					if (!empty($paxDetailArray) && $IsPaxSelected == 1) {
						if ($value['paxType'] == 1) {
							$Adult++;
						} else if ($value['paxType'] == 2) {
							$Child++;
						} else {
							$Infant++;
						}
					} else if (empty($paxDetailArray)) {
						if ($value['paxType'] == 1) {
							$Adult++;
						} else if ($value['paxType'] == 2) {
							$Child++;
						} else {
							$Infant++;
						}
					}
				}
			}
			$SecurityKey = SECURITYKEY;
			$BookingId = $arrData['bookingId'];
			$url = "http://api.hellogtx.com/api/v1/flightinventory/check-booking-cancel-v1/?SecurityKey=" . $SecurityKey . "&BookingId=" . $BookingId . "&Adult=" . $Adult . "&Child=" . $Child . "&Infant=" . $Infant;
			$objFlight = new Travel_Model_FlightMaster();
			$resultset = $objFlight->getgtxapiinfo($url);
			//$outputH = '{"bookingId":"'.$BookingId.'","trips":[{"src":"DEL","dest":"KNU","departureDate":"2022-01-01T07:30","flightNumbers":["6926"],"airlines":["VA"],"amendmentInfo":{"ADULT":{"amendmentCharges":21,"refundAmount":100,"totalFare":121},"CHILD":{"amendmentCharges":21,"refundAmount":100,"totalFare":121},"INFANT":{"amendmentCharges":10,"refundAmount":10,"totalFare":20}}}],"status":{"success":true,"httpStatus":200}}';
			//  echo "<pre>";print_r($resultset);die;
			if (isset($resultset['results']['Status']) && $resultset['results']['Status'] == false) {
				echo json_encode(array('status' => false, 'success' => false, 'msg' => $resultset['results']['Message']));
				exit;
			}
			$amendmentInfo = array();
			$status = array('success' => false, 'error' => $resultset);
			if (isset($resultset['results']['resultSet'])) {
				$amendmentInfo['ADULT'] = [
					'amendmentCharges' => (int)round($resultset['results']['resultSet']['AC']['TotalInventoryCC'] / ($Adult + $Child), 2),
					'refundAmount' => (int)round($resultset['results']['resultSet']['AC']['RefundAmount'] / ($Adult + $Child), 2),
					'totalFare' => (int)round($resultset['results']['resultSet']['AC']['TotalInventoryCost'] / ($Adult + $Child), 2),
				];
				$amendmentInfo['CHILD'] = [
					'amendmentCharges' => (int)round($resultset['results']['resultSet']['AC']['TotalInventoryCC'] / ($Adult + $Child), 2),
					'refundAmount' => (int)round($resultset['results']['resultSet']['AC']['RefundAmount'] / ($Adult + $Child), 2),
					'totalFare' => (int)round($resultset['results']['resultSet']['AC']['TotalInventoryCost'] / ($Adult + $Child), 2),
				];

				$amendmentInfo['INFANT'] = [
					'amendmentCharges' => (int)round($resultset['results']['resultSet']['Infant']['TotalInventoryCC'] / ($Infant), 2),
					'refundAmount' => (int)round($resultset['results']['resultSet']['Infant']['RefundAmount'] / ($Infant), 2),
					'totalFare' => (int)round($resultset['results']['resultSet']['Infant']['TotalInventoryCost'] / ($Infant), 2),
				];
				$status = array('success' => $resultset['results']['Status'], 'httpStatus' => '200');
			}

			$arrData['trips'][0]['amendmentInfo'] = $amendmentInfo;
			$response = [
				'bookingId' => $BookingId,
				'trips' => $arrData['trips'],
				'remarks' => $arrData['remarks'],
				'type' => $arrData['type'],
				'apiresponse' => json_encode($resultset),
				'status' => $status,

			];
			$outputH = json_encode($response);
			$data_stringh = $url;
			if (FLIGHT_API_LOGS) {

				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentCharges_request.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $data_stringh);
				//Write Request Logs starts...
				//Write Request Logs starts...
				$strFilePath = "flight/Amendment/" . date('Y-m-d-H-i-s') . "_AmendmentCharges_response.json";
				Zend_Controller_Action_HelperBroker::getStaticHelper("General")->createApiCallLogs($strFilePath, $outputH);
				//Write Request Logs starts...
			}
			Zend_Session::namespaceUnset('AmendmentChargesSession');
			$AmendmentChargesSession = new Zend_Session_Namespace('AmendmentChargesSession');
			$AmendmentChargesSession->params = $response;  // store all serch result data to Session
			return $response;
		}
	}
	public function GetSubmitAmendmentSeriesFare($arrData = array(), $FlightBooking = array())
	{
		if ($arrData) {
			$paxDetailArray = (isset($arrData['paxDetailArray']) && !empty($arrData['paxDetailArray'])) ? $arrData['paxDetailArray'] : array();
			$passenger = $FlightBooking['passenger'];
			$Adult = 0;
			$Child = 0;
			$Infant = 0;
			if ($passenger) {
				foreach ($passenger as $keys => $value) {
					$paxName_ = trim($value['FirstName']) . '-' . trim($value['LastName']);
					$IsPaxSelected = isset($paxDetailArray[$paxName_]) ? $paxDetailArray[$paxName_] : '';
					if (!empty($paxDetailArray) && $IsPaxSelected == 1) {
						if ($value['paxType'] == 1) {
							$Adult++;
						} else if ($value['paxType'] == 2) {
							$Child++;
						} else {
							$Infant++;
						}
					} else if (empty($paxDetailArray)) {
						if ($value['paxType'] == 1) {
							$Adult++;
						} else if ($value['paxType'] == 2) {
							$Child++;
						} else {
							$Infant++;
						}
					}
				}
			}
			$SecurityKey = SECURITYKEY;
			$BookingId = $arrData['bookingId'];
			if (isset($arrData['isCancelType']) && $arrData['isCancelType'] == 2) {
				$url = "http://api.hellogtx.com/api/v1/flightinventory/booking-cancel-v1/?SecurityKey=" . $SecurityKey . "&BookingId=" . $BookingId . "&Adult=" . $Adult . "&Child=" . $Child . "&Infant=" . $Infant . "&CancellationType=2";
			} else {
				$url = "http://api.hellogtx.com/api/v1/flightinventory/booking-cancel-v1/?SecurityKey=" . $SecurityKey . "&BookingId=" . $BookingId . "&Adult=" . $Adult . "&Child=" . $Child . "&Infant=" . $Infant;
			}
			$objFlight = new Travel_Model_FlightMaster();
			$resultset = $objFlight->getgtxapiinfo($url);
			if (isset($resultset['results']['Status']) && $resultset['results']['Status'] == false) {
				echo json_encode(array('status' => false, 'success' => false, 'msg' => $resultset['results']['Message']));
				exit;
			}

			$RefundAmount = $amendmentCharges = 0;
			$status = array('success' => false, 'error' => $resultset);
			if (isset($resultset['results']['resultSet'])) {
				$RefundAmount = round(($resultset['results']['resultSet']['AC']['RefundAmount']) + ($resultset['results']['resultSet']['Infant']['RefundAmount']), 2);
				$amendmentCharges = round(($resultset['results']['resultSet']['AC']['TotalInventoryCC']) + ($resultset['results']['resultSet']['Infant']['TotalInventoryCC']), 2);
				$status = array('success' => $resultset['results']['Status'], 'httpStatus' => '200');
			}
			$amendmentInfo = array();
			$response = [
				'bookingId' => $BookingId,
				'amendmentId' => $resultset['results']['refId'],
				'apiresponse' => json_encode($resultset),
				'RefundAmount' => $RefundAmount,
				'amendmentCharges' => $amendmentCharges,
				'status' => $status,
				'isCancelType' => $arrData['isCancelType'],
			];
			//$outputH = '{"bookingId":"'.$BookingId.'","amendmentId":"9300102317","status":{"success":true,"httpStatus":200}}';
			$outputH = json_encode($response);
			$data_stringh = $url;
			if (FLIGHT_API_LOGS) {

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

	public function getAirlinesSupport($airlinecode)
	{
		$select = $this->db->select()->from("tbl_airline_support", ['*']);
		$select->where('airlinecode IN(?)', $airlinecode);
		$select->where("status=?", '1');
		$select->order("id", 'ASC');
		$result = $this->db->fetchAll($select);
		$finalArr = [];
		if ($result) {
			foreach ($result as $key => $value) {
				$finalArr[$key]['airlinecode'] = $value['airlinecode'];
				$finalArr[$key]['address1'] = $value['address1'];
				$finalArr[$key]['address2'] = $value['address2'];
				$finalArr[$key]['phoneno'] = $value['phoneno'];
				$finalArr[$key]['mobileno'] = $value['mobileno'];
			}
		}
		return $finalArr;
	}
        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';
		}
	}
}

Youez - 2016 - github.com/yon3zu
LinuXploit