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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/b2b.hellogtx.com/library/Helper/General.php
<?php

/* * *************************************************************
 * Catabatic Technology Pvt. Ltd.
 * File Name     : IndexController.php
 * File Desc.    : General helper to including supporting functions/methods
 * Created By    : Ranvir Singh <ranvir@catpl.co.in>
 * Created Date  : 27 Oct 2017
 * Updated Date  : 01 Dec 2017
 * ************************************************************* */

class Zend_Controller_Action_Helper_General extends Zend_Controller_Action_Helper_Abstract {

    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;
    private $db = NULL;
    private $hotelTypeArr;
    private $tourTypeArr;
    protected $currentDateTime;
    public $baseUrl;

    const USER_NAMESPACE = 'PSESS';

    public $_storage;
    public $packageSession;
    public $packageTypeStatic;
    public $myNamespace;
    public $siteName;
    public $gtxagencysysid;
    public $elasticemail;
    public $objMdl;
    public $gtxwebserviceurl;

    /**
     * Constructor: initialize plugin loader
     * 
     * @return void
     */
    public function __construct() {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
        $this->db = Zend_Db_Table::getDefaultAdapter();

        $this->tourTypeArr = unserialize(CONST_TOURTYPE);

        $BootStrap = $this->config();

        $this->siteName = $BootStrap['siteName'];
        $this->baseUrl = $BootStrap['siteUrl'];
        $this->b2cUrl = $BootStrap['b2cSiteUrl'];
        $this->stylecss = $BootStrap['stylecss'];
        $this->gtxagencysysid = $BootStrap['gtxagencysysid'];
        $this->gtxwebserviceurl = $BootStrap['gtxwebserviceurl'];
        $this->elasticemail = $BootStrap['elasticemail'];
        //         $emailSenderKey = trim($this->elasticemail);
        $this->currentDateTime = date('Y-m-d');
        $this->packageTypeStatic = $BootStrap['packageTypeDynamic'];

        $this->_storage = new Zend_Session_Namespace(self::USER_NAMESPACE);
    }

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

    public function getMypopCookie($name) {
        if (isset($_COOKIE[$name])) {
            $MyCookies = $_COOKIE[$name]; // get user end infomations
            return Zend_Json::decode($MyCookies);
        } else {
            return false;
        }
    }

    public function getLatitudeLongitude($strAddress) {
        // Get lat and long by address         
        $prepAddr = str_replace(' ', '+', $strAddress);

        $geocode = file_get_contents(GOOGLE_MAPS_API_GEOCODE_URL . '?address=' . $prepAddr . '&sensor=false');
        $output = json_decode($geocode);
        $arrLocation = array();
        if (count($output->results) > 0) {
            $latitude = $output->results[0]->geometry->location->lat;
            $longitude = $output->results[0]->geometry->location->lng;
            $arrLocation['latitude'] = $latitude;
            $arrLocation['longitude'] = $longitude;
            return $arrLocation;
        }
        return $arrLocation;
    }

    public function getPlaceDetails($strAddress) {
        // Get lat and long by address         
        $prepAddr = str_replace(' ', '+', $strAddress);

        $geocode = file_get_contents(GOOGLE_MAPS_API_GEOCODE_URL . '?address=' . $prepAddr . '&sensor=true');
        $output = json_decode($geocode);

        $arrLocation = array();
        if (count($output->results) > 0) {
            $arrLocation = $output->results;
            return $arrLocation;
        }
        return $arrLocation;
    }

    public function getFileExtension($file) {
        if (!empty($file)) {
            $arrInfo = pathinfo($file);
            return strtolower($arrInfo['extension']);
        }
    }

    // get tour type char here
    public function getTourTypeChar($defaultTourType) {
        //        if ( !$defaultTourType ) {
        //            throw new Exception(" function " . __FUNCTION__ . " need parameter as int [ 1 or 2 ] " );
        //        }
        return ($defaultTourType == 1) ? 'P' : 'G';
    }

    // params : array [key , value] , array
    /*
      [0] => Array
      (
      [id] => 101
      [name] => ranvir
      )
      [1] => Array
      (
      [id] => 102
      [name] => amit
      )
     */

    public function filterArrayByValueKeyPair($keyValuePair, array $array) {
        //        $arr = $this->array_change_key_case_recursive($array,CASE_LOWER);
        $arr = $array;
        $returnArr = [];
        $tempArr = explode('|', $keyValuePair[1]);
        foreach ($arr as $k => $val) {
            if (isset($val[$keyValuePair[0]]) && !empty($val[$keyValuePair[0]])) {
                if (in_array(($val[$keyValuePair[0]]), $tempArr))
                    $returnArr[] = $val;
            }
        }
        return $returnArr;
    }

    public function filterArrayByNoValueKeyPair($keyValuePair, array $array) {
        //        $arr = $this->array_change_key_case_recursive($array,CASE_LOWER);
        $arr = $array;
        $returnArr = [];
        $tempArr = explode('|', $keyValuePair[1]);
        foreach ($arr as $k => $val) {
            if (isset($val[$keyValuePair[0]])) {
                if (!in_array(($val[$keyValuePair[0]]), $tempArr))
                    $returnArr[] = $val;
            }
        }
        return $returnArr;
    }

    public function mergeMultiArray($OriginalArray, $SecondArray) {
        $i = 0;
        $NewArray = array();
        foreach ($OriginalArray as $value) {
            $NewArray[] = array_merge($value, ($SecondArray[$i]));
            $i++;
        }
        return $NewArray;
    }

    public function getArrayKeyByValue($val, array $arr) {
        return array_search($val, $arr);
    }

    public function getArrayValueByKey($key, array $array) {
        $value = $array[$key];
        if (!is_array($value))
            return $value;
        else {
            return $value;
        }
    }

    public function getValueByKeyFromArray($key, array $array) {
        //        $data = $this->array_change_key_case_recursive($array,CASE_LOWER);
        return $array[$key];
    }

    // converts all keys in a multidimensional array to lower or upper case
    public function array_change_key_case_recursive($arr, $case = CASE_LOWER) {
        return array_map(function ($item) use ($case) {
            if (is_array($item))
                $item = $this->array_change_key_case_recursive($item, $case);
            return $item;
        }, array_change_key_case($arr, $case));
    }

    public function getRatingImage($rating, $fullRating = 5) {

        $ratingStar = '<img src="' . $this->baseUrl . 'public/images/red-star.png">';
        //$ratingStar_half  = '<img src="'. $this->baseUrl .'public/images/smtRating_half.png">';
        $ratingStar_light = '<img src="' . $this->baseUrl . 'public/images/gray-star.png">';

        $ratingImage = '';

        for ($i = 0; $i < $rating; $i++) {
            $ratingImage .= $ratingStar;
        }

        $grayStars = $fullRating - $rating;

        for ($i = 0; $i < $grayStars; $i++) {
            $ratingImage .= $ratingStar_light;
            $ratingImage;
        }

        return $ratingImage;
    }

    public function getInclusionIcon($Inclusions, $stringSeparator) {
        $ret = $icon = '';
        $InclusionsMaster = unserialize(CONST_AMENITIES_MASTER);

        foreach (explode($stringSeparator, $Inclusions) as $inc) {
            $icon = (isset($InclusionsMaster[$inc])) ? $InclusionsMaster[$inc] : "question";

            if ($icon != 'question') {
                if (file_exists("public/img/amenities/$icon.png")) {

                    $ret .= '<img src="public/img/amenities/' . $icon . '.png" alt=" " />';
                    //            $ret .= "<i class=\"fa fa-{$icon}\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{$inc}\"></i>";
                }
            }
        }
        return $ret;
    }

    public function round_up($value, $places) {
        $mult = pow(10, abs($places));
        return $places < 0 ?
                ceil($value / $mult) * $mult :
                ceil($value * $mult) / $mult;
    }

    public function createRange($rangeLimits = null) {

        if ($rangeLimits != null)
            sort($rangeLimits);

        //Setting range limits.
        //$rangeLimits = array(0,10,32,50,250,500,2000);
        $ranges = array();

        for ($i = 0; $i < count($rangeLimits); $i++) {
            if ($i == count($rangeLimits) - 1) {
                break;
            }
            $lowLimit = $rangeLimits[$i];
            $highLimit = $rangeLimits[$i + 1];

            $ranges[$i]['ranges']['min'] = $lowLimit;
            $ranges[$i]['ranges']['max'] = $highLimit;
            //echo '<pre>';echo ($ranges[$i]['ranges']['min']);
            //echo '<pre>';echo($ranges[$i]['ranges']['max']);
            foreach ($rangeLimits as $perPrice) {

                if ($perPrice >= $lowLimit && $perPrice < $highLimit) {
                    $ranges[$i]['values'][] = $perPrice;
                }
            }
        }
        //die('mm');
        return $ranges;
    }

    public function filterDuplicateItinerary($array_key, array $array) {

        $temp = [];
        $res = [];
        if (count($array)) {
            foreach ($array as $key => $val) {
                $res[$val['day']["$array_key"]] = $val;
            }
        }
        $res = array_values($res); // resetting the array keys
        return $res;
    }

    public function moneyFormatINR($number) {
        //        var_dump($number);
        $sign = '';
        if ($number < 0) {
            $sign = '-';
            $number = trim($number, '-');
        }
        //        echo (int)$number;

        if (is_float($number)) {
            $n = explode('.', $number);
            $number = $n[0];
            $decimal = isset($n[1]) ? $n[1] : 0;
        } else {
            $number = $number;
            $decimal = 0;
        }

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

    public function array_filter_rv($array) {
        return array_values(array_intersect_key($array, array_unique(array_map('serialize', $array))));
    }

    // change date format | params : datetime , delimiter[ default : - ] | returns : formated date
    public function changeDateFormat($dt, $delimiter = "-") {
        return date("d" . $delimiter . "m" . $delimiter . "Y", strtotime($dt));
    }

    // add days into given date
    // params : date [Y/m/d] , number of days | returns : formated date
    public function dateAddDays($date, $days) {
        return date('d/m/Y', strtotime($date . " +$days day"));
    }

    // creates price range params : start value , End value , fractions/multiples of number
    function createRangeRv($start, $end, $fraction) {
        //        echo $start ."|". $end ."|". $fraction;

        if ($fraction > $end)
            return "Invalid";

        $total = ceil($end / $fraction);
        //        $loopstart  = (floor($start/$fraction) ==0) ? 1 : 0;
        $loopstart = 1;

        $start = ($fraction * $loopstart);
        $end = ($fraction * $total);

        return range($start, $end, $fraction);
    }

    // creates price range dropdown | params : start value , End value , fractions/multiples of number
    function getPriceDropdown($min, $max, $fraction, $minPriceArray = []) {
        $min = (int) str_replace(',', '', $min);
        $max = (int) str_replace(',', '', $max);

        $limit = $this->createRangeRv($min, $max, $fraction);
        $newarr = [];
        $next = 1;
        if ($limit !== 'Invalid') {
            foreach ($limit as $key => $value) {
                // check if the price range is exists or not
                if ($this->checkRangeExists($value, $minPriceArray)) {
                    $newarr[$next . '-' . $value] = $next . '-' . $value;
                    $next = $value + 1;
                }
                //              if($value==30000) {
                ////                  break;
                //                  echo $value;
                //                    var_dump($this->checkRangeExists( $value , $minPriceArray));
                //              }
            }
        }
        return $newarr;
    }

    public function checkRangeExists($num, array $arr) {
        $returnval = false;

        foreach ($arr as $value) {
            if ($num < $value) {
                $returnval = true;
                break;
            }
        }

        return $returnval;
    }

    public function getPackagePrice($defaultCategory, $tourTypeChar, array $priceArray, $discounted = false) {
        $PriceResultArr = $priceArray[$tourTypeChar][$defaultCategory]['price'][0];

        // discounted true means lesser amount | discount excluded in amount 
        if ($discounted) {
            $finalp = (float) $PriceResultArr['PricePerPerson'];
        } else {
            $discountValue = 0;

            if ($PriceResultArr['DiscountType'] === 1) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else if ($PriceResultArr['DiscountType'] === 2) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else {
                $discountValue = 0;
            }

            $finalp = (float) $PriceResultArr['PricePerPerson'] + $discountValue;
        }

        return $finalp;
    }

    public function filterTransportItinerary(array $masterData, $type = '') {
        $tempArr = [];
        if (count($masterData)) {
            foreach ($masterData as $key => $value) {
                if ($value['transType'] == strtolower($type)) {
                    $tempArr[] = $value;
                }
            }
        }
        return $tempArr;
    }

    public function getTransportItinerary(array $array, array $masterData, $type = '') {

        $tempArr = $this->filterTransportItinerary($masterData, $type);
        $masterData = $tempArr;

        $itineraryArr = $array;
        $count_Itinerary = count($itineraryArr);
        $itineraryArrCustom = $SightSeeingItineraryArr = $SightSeeingITINERARY_ITEM_Result = [];
        $SightSeeingITINERARY = $SightSeeingITINERARY_ITEM = $SightSeeingITINERARY_Result = $SSItiArray = '';

        for ($i = 0; $i < $count_Itinerary; $i++) {

            $SightSeeingITINERARY = $this->filterArrayByValueKeyPair(['Type', 'TRANSFERS'], $itineraryArr[$i]['ItineraryItem']);
            // get sightseeing of the days Itinerary
            if ($SightSeeingITINERARY[0]['Type'] === 'TRANSFERS') {

                // fetch which transfer is included true / false
                if (count($SightSeeingITINERARY[0]['Items'])) {

                    $SSItiArray = $SightSeeingITINERARY[0]['Items']; // get single day sightsing list

                    $TransferArr = [];
                    foreach ($SSItiArray as $key => $value) {
                        if (isset($value['Type']) && (strtolower($type) === $value['Type'])) {
                            $TransferArrInner = [];
                            foreach ($value['Item'] as $k => $v) {
                                $TransferArrInner[] = ['itemid' => $v['Id'], 'IsIncluded' => $v['IsIncluded']];
                            }
                            $TransferArr[] = $TransferArrInner;
                        }
                    }


                    $itineraryArrCustom[$i] = ['Day' => $itineraryArr[$i]['Day'], 'FinalArray' => $TransferArr];
                }
            }
        }
        return $itineraryArrCustom;
    }

    public function createArrayDetailDynamic(array $array, array $param) {
        if (!is_array($array)) {
            throw new Exception("function 'createArrayDetailDynamic(array , array)' expects array only as input parameter.");
        } else {

            $catId = $param['catid'];
            $gtxId = $param['gtxid'];
            $packageId = $param['pkgid'];
            $tourtype = $param['tourtype'];

            $detail = $array; // assign the input array to $detail 

            $dayViewNew = $detail['dayViewNew'];
            // start : array for day itinerary view
            $dayItineraryArray = [];
            $iti = '';
            $tempArr = [];
            for ($r = 0; $r < count($dayViewNew); $r++) {
                $iti = $dayViewNew[$r]['day']['Day'];
                if (!in_array($iti, $tempArr)) {
                    $dayItineraryArray[$iti] = $dayViewNew[$r];
                    $tempArr[] = $iti;
                } else {
                    $dayItineraryArray[$iti]['repeat'] = 1;
                    $dayItineraryArray[$iti]['day']['Title'] = [$dayViewNew[$r - 1]['day']['Title'], $dayViewNew[$r]['day']['Title']];
                    $dayItineraryArray[$iti]['day']['Program'] = [$dayViewNew[$r - 1]['day']['Program'], $dayViewNew[$r]['day']['Program']];
                    $dayItineraryArray[$iti]['Activities'] = [$dayViewNew[$r - 1]['Activities'], $dayViewNew[$r]['Activities']];
                    $dayItineraryArray[$iti]['SightSeeings'] = [$dayViewNew[$r - 1]['SightSeeings'], $dayViewNew[$r]['SightSeeings']];
                }
            }
            // end : array for day itinerary view

            $PackageType = $detail['PackageType'];
            $GTXPkgId = $gtxId;
            $PkgSysId = $packageId;

            $BookingValidUntil = $detail['BookingValidUntil'];
            //    $TPId   = $detail['tourType'][$catId]; 
            // dynamic package for | 2
            if ($detail['PackageType'] == 2) {
                $TPId = $detail['TPId'];
            } else {
                $TPId = @$detail['tourType'][$catId];
            }

            // do dynamic
            $CitiesArray = isset($detail['finalArray']['city']) ? $detail['finalArray']['city'] : array();
            ;
            $hotelHotelArray = array();
            $transfersArray = $ItineraryIdArray = $hotelIdArray = [];

            $itinerariesArray = [];
            $cityMaster = $hotelsMaster = $activityMaster = $ssMaster = [];
            $detail['itementries']['Cities'] = isset($detail['itementries']['Cities']) ? $detail['itementries']['Cities'] : array();
            foreach ($detail['itementries']['Cities'] as $key => $value) {
                if (isset($value['Hotels']['Hotel'])) {
                    foreach ($value['Hotels']['Hotel'] as $keyH => $valueH) {
                        $hotelsMaster[$valueH['RefHotelId']] = $valueH;
                    }
                }

                if (isset($value['Activities']['Activity'])) {
                    foreach ($value['Activities']['Activity'] as $keyH => $valueH) {
                        $activityMaster[$valueH['RefActivityId']] = $valueH;
                    }
                }

                if (isset($value['SightSeeings']['SightSeeing'])) {
                    foreach ($value['SightSeeings']['SightSeeing'] as $keyH => $valueH) {
                        $ssMaster[$valueH['RefSSId']] = $valueH;
                    }
                }
            }

            $cityMaster['Hotels'] = $hotelsMaster;
            $cityMaster['Activities'] = $activityMaster;
            $cityMaster['SightSeeings'] = $ssMaster;
            $detail['itementries']['Itineraries']['Itinerary'] = isset($detail['itementries']['Itineraries']['Itinerary']) ? $detail['itementries']['Itineraries']['Itinerary'] : array();
            foreach ($detail['itementries']['Itineraries']['Itinerary'] as $itineraries) {
                $itinerariesDays = $itineraries['Day'];
                $ItineraryId = $itineraries['ItineraryId'];

                $cityArray = [];
                foreach ($itineraries['ItineraryItem'] as $itinerariesItem) {

                    if ($itinerariesItem['Type'] == 'CITY') {
                        $cityArray[] = ['itemid' => $itinerariesItem['Id']];
                    }

                    if ($itinerariesItem['Type'] == 'HOTEL') {
                        $hotelHotelArray = [];

                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {

                            if ($itinerariesHotel['Id'] == $catId) {
                                if (isset($itinerariesHotel['Item'])) {
                                    foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                        if ($itinerariesDayHotel['Id'] && $itinerariesDayHotel['IsIncluded'] == 1) {
                                            $hotelHotelArray[] = [
                                                'itemid' => $itinerariesDayHotel['Id'],
                                                'MasterIntSysId' => $itinerariesDayHotel['MasterIntSysId'],
                                                'AccomSysId' => $itinerariesDayHotel['ACCOMSYSID'],
                                                'RoomType' => isset($itinerariesDayHotel['ROOMTYPE']) ? $itinerariesDayHotel['ROOMTYPE'] : 0,
                                                'MealPlanType' => isset($itinerariesDayHotel['MEALPLANTYPE']) ? $itinerariesDayHotel['MEALPLANTYPE'] : 0,
                                                'IsIncluded' => ($itinerariesDayHotel['IsIncluded']) ? $itinerariesDayHotel['IsIncluded'] : false,
                                                'Title' => $hotelsMaster[$itinerariesDayHotel['Id']]['Name'],
                                                'SupplierSysId' => $hotelsMaster[$itinerariesDayHotel['Id']]['SupplierSysId'],
                                            ];
                                            $hotelIdArray[] = $itinerariesDayHotel['Id'];
                                            $ACCOMSYSIDArray[] = $itinerariesDayHotel['ACCOMSYSID'];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if ($itinerariesItem['Type'] == 'ACTIVITY') {
                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {
                            $ActivitiesArray = [];
                            foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                if ($itinerariesDayHotel['Id']) {
                                    $ActivitiesArray[] = ['itemid' => $itinerariesDayHotel['Id'], 'IsIncluded' => ($itinerariesDayHotel['IsIncluded']) ? $itinerariesDayHotel['IsIncluded'] : false];
                                }
                            }
                        }
                    }

                    if ($itinerariesItem['Type'] == 'SIGHTSEEING') {
                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {
                            $SightSeeingsArray = [];
                            foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                if ($itinerariesDayHotel['Id']) {
                                    $SightSeeingsArray[] = ['itemid' => $itinerariesDayHotel['Id'], 'IsIncluded' => ($itinerariesDayHotel['IsIncluded']) ? $itinerariesDayHotel['IsIncluded'] : false];
                                }
                            }
                        }
                    }

                    if ($itinerariesItem['Type'] == 'TRANSFERS') {
                        $transfersITIArray = [];
                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {
                            $sessionPackageSearchParams = new Zend_Session_Namespace('sessionPackageSearchParams');
                            $searchSessionData = $sessionPackageSearchParams->params;
                            $noofpax = isset($searchSessionData) ? $searchSessionData['totadlt'] + $searchSessionData['totchld'] : '2';
                            foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                if (!empty($itinerariesDayHotel['RouteSysId'])) {
                                    $model = new Detail_Model_PackageMapper();
                                    $tranFINALArray = $model->fetchTransfersDetailsByRouteSysID($itinerariesDayHotel['RouteSysId']);
                                    foreach ($tranFINALArray as $transfinVal) {
                                        $dataArray = Zend_Json::decode($transfinVal['category']);
                                        foreach ($dataArray as $vahdata) {
                                            if ($vahdata['RouteVechSysId'] == $itinerariesDayHotel['RouteVechSysId']) {
                                                $VehSysId = $vahdata['VehicleSysId'];
                                                $VehicleTypeSysId = $vahdata['VehicleTypeSysId'];
                                                $TransType = '';
                                                $Capacity = $vahdata['Capacity'];
                                                $VehName = $vahdata['VehName'];
                                                $SupplierSysId = $vahdata['SupplierSysId'];
                                            }
                                        }
                                        if ($noofpax != $Capacity || $noofpax > $Capacity) {
                                            $quantity = $noofpax / $Capacity;
                                            if (is_float($quantity)) {
                                                $quan = intval($quantity);
                                                $quantity = $quan + 1;
                                            }
                                        }
                                        $area = json_decode($transfinVal['Area'], 1);
                                        foreach ($area as $destiVal) {
                                            $FromPlace = $destiVal['PickUPLocation'];
                                            $ToPlace = $destiVal['DropLocation'];
                                        }
                                        $TransportSubType = end(explode(',', $transfinVal['TransportSubType']));
                                        $TransportCategory = end(json_decode($transfinVal['TransportCategory'], 1));
                                        foreach ($TransportCategory as $val) {
                                            $TransportCategory = $val;
                                        }
                                    }
                                    if ($itinerariesDayHotel['Id']) {
                                        $transfersITIArray[] = [
                                            'itemid' => $itinerariesDayHotel['Id'],
                                            'IsIncluded' => ($itinerariesDayHotel['IsIncluded']) ? $itinerariesDayHotel['IsIncluded'] : false,
                                            'RouteSysId' => $itinerariesDayHotel['RouteSysId'],
                                            'RouteVechSysId' => $itinerariesDayHotel['RouteVechSysId'],
                                            'VehSysId' => $VehSysId,
                                            'VehicleTypeSysId' => $VehicleTypeSysId,
                                            'TransType' => $TransType,
                                            'FromPlace' => $FromPlace,
                                            'ToPlace' => $ToPlace,
                                            'Capacity' => $Capacity,
                                            'VehName' => $VehName,
                                            'SupplierSysId' => $SupplierSysId,
                                            'Qty' => $quantity,
                                            'SubCategory' => $TransportCategory,
                                            'TransportSubType' => $TransportSubType,
                                        ];
                                        if ($itinerariesDayHotel['IsIncluded'] == true) {
                                            $transfersArray[$itinerariesHotel['Type']][$itineraries['Day']][] = $itinerariesDayHotel['Id'];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                $itinerariesArray[$ItineraryId]['day'] = $itinerariesDays;
                $itinerariesArray[$ItineraryId]['city'] = $cityArray;
                $itinerariesArray[$ItineraryId]['hotel'] = $hotelHotelArray;
                $itinerariesArray[$ItineraryId]['activity'] = $ActivitiesArray;
                $itinerariesArray[$ItineraryId]['sightSeeing'] = $SightSeeingsArray;
                $itinerariesArray[$ItineraryId]['transfers'] = $transfersITIArray;
            }

            $itinerariesDays = $ItineraryIdArray = [];

            $carTrans = [];
            if (isset($detail['itementries']['TransfersMaster']) && count($detail['itementries']['TransfersMaster'])) {
                foreach ($detail['itementries']['TransfersMaster'] as $key => $val) {
                    if (strtolower($val['transType']) == 'car') {
                        $carTrans['car'][] = $val;
                    }
                }
            }
            //    
            //    end : merge car transfers into transferArray

            $transfersArray = array_merge($transfersArray, $carTrans);

            /*
              $CategoriesArray = array();
              foreach ($detail['itementries']['TourType'] as $TourType) {
              if ($TourType['TourType'] == $tourtype) {
              foreach ($TourType['Categories'] as $Categories) {
              foreach ($Categories as $CategoriesType) {
              if ($CategoriesType['CategoryId'] == $catId) {
              $CategoriesArray['TourTypeTitle'] = $TourType['TourTypeTitle'];
              $CategoriesArray['TourType'] = $TourType['TourType'];
              $CategoriesArray['Type'] = $CategoriesType['Type'];
              foreach ($CategoriesType['PriceAdditional'] as $PriceAdditional) {
              // $CategoriesArray['NetPrice'] = $PriceAdditional['PricePerPerson'];
              //  $CategoriesArray['DiscountNetPrice'] = (float) $PriceAdditional['PricePerPerson'] + (float) $PriceAdditional['DiscountVal'];
              }
              $CategoriesArray['NetPrice'] = $CategoriesType['PriceAdditional'][0]['PricePerPerson'];
              $CategoriesArray['DiscountNetPrice'] = (float) $CategoriesType['PriceAdditional'][0]['PricePerPerson'] + (float) $CategoriesType['PriceAdditional'][0]['DiscountVal'];

              }
              }
              }
              }
              }
             * 
             */

            $CategoriesArray = array();
            foreach ($detail['itementries']['TourType'] as $TourType) {
                if ($TourType['TourType'] == $tourtype) {
                    foreach ($TourType['Categories'] as $Categories) {
                        foreach ($Categories as $CategoriesType) {
                            if ($CategoriesType['CategoryId'] == $catId) {
                                $CategoriesArray['TourTypeTitle'] = $TourType['TourTypeTitle'];
                                $CategoriesArray['TourType'] = $TourType['TourType'];
                                $CategoriesArray['Type'] = $CategoriesType['Type'];
                                foreach ($CategoriesType['PriceAdditional'] as $PriceAdditional) {
                                    // $CategoriesArray['NetPrice'] = $PriceAdditional['PricePerPerson'];
                                    //  $CategoriesArray['DiscountNetPrice'] = (float) $PriceAdditional['PricePerPerson'] + (float) $PriceAdditional['DiscountVal'];
                                }
                                $CategoriesArray['NetPrice'] = $CategoriesType['PriceAdditional'][0]['PricePerPerson'];
                                $CategoriesArray['DiscountNetPrice'] = (float) $CategoriesType['PriceAdditional'][0]['PricePerPerson'] + (float) $CategoriesType['PriceAdditional'][0]['DiscountVal'];

                                if ($CategoriesType['MPType']) {
                                    $mparray = [];
                                    foreach ($CategoriesType['MPType'] as $key => $value) {
                                        $mparray[] = [
                                            'id' => $value['MPTypeId'],
                                            'txt' => $value['MPTypeText'],
                                            'sfp' => $value['SeletedForPackage'],
                                            'price' => $value['PriceAdditional'],
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /* get default category 
             * hotel standard array
             * Tour type defualt
             * 
             */
            $categoryDetails = $this->getCategoryAndPriceArray($detail['itementries']['TourType'], 'B2C');
            $CategoriesArray = $categoryDetails['priceArrJson'];

            $ActivitiesArray = array();
            foreach ($detail['dayView'] as $itineraries) {
                foreach ($itineraries['Activities'] as $itinerariesItem) {
                    if ($itinerariesItem['Type'] == 'ACTIVITY') {
                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {
                            foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                if ($itinerariesDayHotel['IsIncluded'] == true) {
                                    $ActivitiesArray[] = $itinerariesDayHotel['Id'];
                                }
                            }
                        }
                    }
                }
            }
            $SightSeeingsArray = array();
            foreach ($detail['dayView'] as $itineraries) {
                foreach ($itineraries['SightSeeings'] as $itinerariesItem) {
                    if ($itinerariesItem['Type'] == 'SIGHTSEEING') {
                        foreach ($itinerariesItem['Items'] as $itinerariesHotel) {
                            foreach ($itinerariesHotel['Item'] as $itinerariesDayHotel) {
                                if ($itinerariesDayHotel['IsIncluded'] == true) {
                                    $SightSeeingsArray[] = $itinerariesDayHotel['Id'];
                                }
                            }
                        }
                    }
                }
            }

            $TransfersMaster = isset($detail['itementries']['TransfersMaster']) ? $detail['itementries']['TransfersMaster'] : '';
            $OtherServices = isset($detail['itementries']['OtherServices']) ? $detail['itementries']['OtherServices'] : '';

            $finalarray = [
                'dayItineraryArray' => $dayItineraryArray,
                'CitiesArray' => $CitiesArray,
                'CategoriesArray' => $CategoriesArray,
                'ActivitiesArray' => $ActivitiesArray,
                'SightSeeingsArray' => $SightSeeingsArray,
                'hotelHotelArray' => $hotelHotelArray,
                'hotelIdArray' => $hotelIdArray,
                'OtherServices' => $OtherServices,
                'TransfersMaster' => $TransfersMaster,
                'transfersArray' => $transfersArray,
                //                'transfersITIArray' => $transfersITIArray ,
                'itinerariesDays' => $itinerariesDays,
                'ItineraryIdArray' => $ItineraryIdArray,
                'itementries' => $detail['itementries'],
                'dayView' => $detail['dayView'],
                'dayViewNew' => $detail['dayViewNew'],
                'finalArray' => $detail['finalArray'],
                'PackageType' => $detail['PackageType'],
                'BookingValidUntil' => $detail['BookingValidUntil'],
                'tourType' => $detail['tourType'],
                'imageUrl' => $detail['imageUrl'],
                'itinerariesArray' => $itinerariesArray,
                'cityMaster' => $cityMaster,
            ];
        }
        return $finalarray;
    }

    public function getTransfersArray($type, array $array) {
        $tempArr = [];
        if (strtolower($type) === 'car') {
            if (count($array)) {
                foreach ($array as $key => $value) {
                    if ($value['transType'] == 'car') {
                        //                        $tempArr[] = $value;
                        $tempArr[] = ['itemid' => $value['fixTransSysId'], 'IsIncluded' => ($value['isIncluded']) ? true : false];
                    }
                }
            }
        } else if (strtolower($type) === 'otherservices') {
            if (count($array)) {
                foreach ($array as $key => $value) {
                    $tempArr[] = ['itemid' => $value['otherSrvSysId'], 'IsIncluded' => ($value['isCostInclInTP']) ? true : false];
                }
            }
        }
        return $tempArr;
    }

    public function getSelectedItemRate($itemid, array $array, $type) {
        $price = 0;

        if (strtolower($type) === 'car') {
            if (array_key_exists($itemid, $array)) {
                $price = $array[$itemid]['costPerson'];
            }
        } else {
            if (array_key_exists($itemid, $array)) {
                //                $price = $array[$itemid]['priceaditionals']['NetCost'];
                $price = $array[$itemid]['priceaditionals']['netCost'];
            }
        }
        return $price;
    }

    public function getMasterData($packageid, $type) {
        $array = $this->getPackageJSONDataArray($packageid);
        $returnResult = [];

        if (strtolower($type) === 'city') {
            $hotelArr = [];
            foreach ($array['Cities']['City'] as $key => $value) {
                $hotelArr[$value['CityId']] = ['CityId' => $value['CityId'], 'Title' => $value['Title']];
            }
            $returnResult = $hotelArr;
        } else if (strtolower($type) === 'h') {
            $hotelArr = [];
            foreach ($array['Cities']['City'] as $key => $value) {
                foreach ($value['Hotels']['Hotel'] as $keyINN => $valueINN) {

                    $hotelArr[$valueINN['RefHotelId']] = $valueINN;
                }
            }
            $returnResult = $hotelArr;
        } else if (strtolower($type) === 'a') {
            $hotelArr = [];
            foreach ($array['Cities']['City'] as $key => $value) {
                if (isset($value['Activities']['Activity'])) {
                    foreach ($value['Activities']['Activity'] as $keyINN => $valueINN) {

                        $hotelArr[$valueINN['RefActivityId']] = $valueINN;
                    }
                }
            }
            $returnResult = $hotelArr;
        } else if (strtolower($type) === 's') {
            $hotelArr = [];
            foreach ($array['Cities']['City'] as $key => $value) {
                if (isset($value['SightSeeings']['SightSeeing'])) {
                    foreach ($value['SightSeeings']['SightSeeing'] as $keyINN => $valueINN) {
                        $hotelArr[$valueINN['RefSSId']] = $valueINN;
                    }
                }
            }
            $returnResult = $hotelArr;
        } else if (strtolower($type) === 'car') {
            $hotelArr = [];
            foreach ($array['Transfers'] as $key => $value) {
                if ($value['transType'] === 'car') {
                    $hotelArr[$value['fixTransSysId']] = $value;
                }
            }
            $returnResult = $hotelArr;
        } else if (strtolower($type) === 'services') {
            $hotelArr = [];
            foreach ($array['OtherServices'] as $key => $value) {
                $hotelArr[$value['otherSrvSysId']] = $value;
            }
            $returnResult = $hotelArr;
        }
        return $returnResult;
    }

    public function getGroupCountForRate($itinerary, $pkgid, $tourtype, $catid, $itemid) {
        $PSESS = $this->_storage->packageSession;
        $countITIHotel = 1;

        if (!empty($PSESS[$pkgid][$tourtype][$catid])) {
            foreach ($PSESS[$pkgid][$tourtype][$catid] as $keyO => $valueO) {
                if ($keyO === 'itineraries') {
                    foreach ($valueO as $keyH => $valueH) {
                        if (is_array($valueH['hotel']) && count($valueH['hotel'])) {
                            foreach ($valueH['hotel'] as $key => $value) {
                                if ($value['MasterIntSysId'] == $itinerary) {
                                    if ($value['itemid'] == $itemid) {
                                        $countITIHotel++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $countITIHotel;
    }

    public function getMarkupDetailsArray($packageid, $tourtype, $catid, $market = 'B2B', $SourcePlaceSysId = null, $fromDate = null) {
        $array = $this->getPackageJSONDataArray($packageid);

        $IsFixedDeparturePackage = $array['IsFixedDeparturePackage'];
        $SpecificationId = $array['PackageSpec']['SpecificationId'];
        $returnResult = [];
        if ($IsFixedDeparturePackage == 1 && $SpecificationId == 3) {
            $priceArray = $this->getCategoryAndPriceArray($array['TourTypes']['MarketType'], $market, null, null, $SourcePlaceSysId, $fromDate);
        } else {
            $priceArray = $this->getCategoryAndPriceArray($array['TourTypes']['MarketType'], $market);
        }
        $tourTypeChar = ($tourtype == 1) ? 'P' : 'G';
        $returnResult = [
            'MarkType' => $priceArray['priceArrJson'][$tourTypeChar][$catid]['price'][0]['MarkType'],
            'MarkValue' => $priceArray['priceArrJson'][$tourTypeChar][$catid]['price'][0]['MarkValue'],
            'LongJsonInfo' => $array
        ];
        return $returnResult;
    }

    // $countit = number of nights / itinerary
    public function calculateMarkupOnPrice(array $markupDetialsArray, $adjustmentPrice, $countit) {
        if (array_key_exists('MarkType', $markupDetialsArray)) {
            if ($markupDetialsArray['MarkType'] == 2) {
                $markupvalue = ($adjustmentPrice * $markupDetialsArray['MarkValue']) / 100;
            }
            $adjustmentPrice += $markupvalue;
            $adjustmentPrice *= $countit;
        }
        return round($adjustmentPrice);
    }

    public function getPackagePriceArray($packageid) {
        $array = $this->getPackageJSONDataArray($packageid);
        $returnResult = [];
        $tourtype = $category = [];
        return $returnResult;
    }

    public function getPackageJSONData($packageid) {
        $model = new Admin_Model_CRUD();
        $result = $model->rv_select_row('tb_tbb2c_packages_master', ['LongJsonInfo'], ['IsMarkForDel' => 0, 'IsActive' => 1, 'IsPublish' => 1, 'PkgSysId' => $packageid], ['PkgSysId' => 'DESC']);
        echo '<pre>';
        print_r($result);
        die;
        return $result;
    }

    public function getPackageJSONDataArray($packageid) {
        $model = new Admin_Model_CRUD();
        $result = $model->rv_select_row('tb_tbb2c_packages_master', ['LongJsonInfo'], ['IsMarkForDel' => 0, 'IsActive' => 1, 'IsPublish' => 1, 'PkgSysId' => $packageid], ['PkgSysId' => 'DESC']);

        $return = [];
        if ($result['LongJsonInfo']) {
            $return = Zend_Json::decode($result['LongJsonInfo']);
        }
        return (array_key_exists('package', $return)) ? $return['package'] : $return;
    }

    public function writeLogTrack($data) {
        $fileName = date("Y-m-d") . ".txt";
        $fp = fopen("data/track/" . $fileName, 'a+');
        $data = date("Y-m-d H:i:s") . " - " . $data;
        fwrite($fp, $data);
        fclose($fp);
    }

    public function writeLogs($data, $type, $filename) {

        if ($type == 'webservice_package') {
            if (!file_exists("data/webservices/package")) {
                mkdir("data/webservices/package", 0777);
            }
            $directory = "data/webservices/package/";
        } else if ($type == 'webservice_activity') {
            if (!file_exists("data/webservices/activity")) {
                mkdir("data/webservices/activity", 0777);
            }
            $directory = "data/webservices/activity/";
        }
        file_put_contents($directory . $filename, $data);
    }

    public function sessionObjectToArray($obj_namespace) {
        return Zend_Session::namespaceGet($obj_namespace);
    }

    /*
     * This function is used to check if the session is created for dynamic package 
     * @param  $packageid , $tourtype , $catid
     * @return session array
     */

    public function checksession($packageid, $tourtype, $catid) {
        if (!is_int($packageid)) {
            throw new Exception("function 'hashingg()' expects int only as input parameter.");
        } else {
            $hasAlreadySession = $splitID = $code = 0;
            //            echo $packageid , $tourtype , $catid;
            //            if( isset($this->_storage->packageSession) && (array_key_exists($packageid, $this->_storage->packageSession)) )
            //            {
            //                if( isset($this->_storage->packageSession[$packageid]['tourtype']) && ($this->_storage->packageSession[$packageid]['tourtype'] == $tourtype ) )
            //                {
            //                    if( isset($this->_storage->packageSession[$packageid][$tourtype]['category']) && ($this->_storage->packageSession[$packageid][$tourtype]['category'] == $catid ) )
            //                    {
            //                        $hasAlreadySession = true;
            //                    }
            //                }
            //            }
            if (isset($this->_storage->packageSession) && (array_key_exists($packageid, $this->_storage->packageSession))) {
                if (isset($this->_storage->packageSession[$packageid]) && array_key_exists($tourtype, $this->_storage->packageSession[$packageid])) {
                    if (isset($this->_storage->packageSession[$packageid][$tourtype]) && array_key_exists($catid, $this->_storage->packageSession[$packageid][$tourtype])) {
                        $hasAlreadySession = true;
                    }
                }
            }
        }
        //        var_dump($hasAlreadySession); die;
        return $hasAlreadySession;
    }

    /*
     * This function is used to copy the session if dynamic package 
     * @param $pkgid , $tourtypeAAA , $catid , array $itinerariesArray , $price=0 , array $others
     * @return void
     */

    public function copysession($pkgid, $tourtypeAAA, $catid, array $itinerariesArray, $price = 0, array $others = array()) {
        if (!$pkgid) {
            throw new Exception("Package id missing");
        } else {

            $tourtype = ($tourtypeAAA === 2) ? 2 : 1;
            //            $PSESS['tourtype'] = $tourtype;
            //            $PSESS['category'] = $catid;

            $PSESS['itineraries'] = $itinerariesArray;
            $PSESS['others']['price'] = $price;
            $PSESS['others']['services'] = $others['services'];
            $PSESS['others']['transfers'] = $others['transfers'];
            $this->_storage->packageSession[$pkgid][$tourtype][$catid] = $PSESS;

            //            $this->_storage->setExpirationSeconds( 10, $this->_storage->packageSession ); // set expiration time in seconds
        }
    }

    /*
     * This function is used to remove the session if dynamic package
     * @param null
     * @return void
     */

    public function flushSession() {
        $this->_storage->unsetAll();
    }

    // prepare the json for front end as per need for listing page
    // params : B2B | B2C (default)
    public function customiseForJsonV2($resultset, $market = 'B2C',$querydata = array()) {       
        $objPackagesMaster = new Travel_Model_PackagesMaster();
        $CATEGORY_TYPE_NEW = unserialize(CATEGORY_TYPE_NEW);
       
        $getMonthsArrayAll = array();
        $currencyTypeArray = $this->getCurrencyData();
         
        $result = $result1 = $result2 = $myCategoryArray = $hotelStandardArr = $tourTypeArray = [];
        $shortJSON = $longJSON = $PackageCategoryStr = $PackageDestinationStr = '';
        $temp = array();
        $displayFinalPrice = $displayFinalPriceDisc = '';
        $defaultCategoryId = 0;
        $defaultTourType = 0;
        $jsonData = $PackageNights = $PackagePriceRange = [];

        $PackageType = $PackageSubType = $tourTypeRadio = $categoryDetails = $destinationTitleCustomFinalStr = $MPType = '';
        $priceArrJson = $tourTypeArrayOfIds = $destinationNightCountsArray = $destinationTitleCustomArray = [];

        $getNewworkPackageId = $this->getNewworkPackageId($this->gtxagencysysid);
        
        $getNewworkPackageIdArray = (!empty($getNewworkPackageId)) ? json_decode($getNewworkPackageId, 1) : array();
        if (isset($getNewworkPackageIdArray['status'])) {
            $getNewworkPackageIdArray = array();
        }
       
        $deleteNetworkPackage = array();
        foreach ($resultset as $resultkey => $resultval) {
            
            $PackageType = $resultval['PackageType'];
            $PackageSubType = $resultval['PackageSubType'];
            try {
                $longJSON = Zend_Json::decode($resultval['LongJsonInfo'], true);
            } catch (Zend_Exception $e) {
                $longJSON = "error";
            }

            if ($longJSON != "error") {

                if (isset($longJSON['package']['AgencyIdB2C']) && $longJSON['package']['AgencyIdB2B'] && $longJSON['package']['AgencyIdB2C'] != $longJSON['package']['AgencyIdB2B']) {
                    if($this->stylecss == 'himalayanyatra'){
                        continue;
                    }else{
                        if (!empty($getNewworkPackageIdArray) && !isset($getNewworkPackageIdArray[$resultval['GTXPkgId']])) {
                            $deleteNetworkPackage[] = $resultval['GTXPkgId'];
                            continue;
                        }
                    }
                }

                $temp['package'] = $longJSON['package']; // get package type array
                $temp['packageTypeArr'] = $longJSON['package']['PackageType']; // get package type array
                $temp['cityArr'] = $longJSON['package']['Cities']['City'];   // get cities included in package
                $temp['inclusionsArr'] = $longJSON['package']['Inclusions']; // get inclusions of package

                $temp['tourType'] = $longJSON['package']['TourTypes']['MarketType']; // get package validity
                $temp['Validity'] = $longJSON['package']['Validity']; // get package validity
                $temp['itineraryArr'] = $longJSON['package']['Itineraries']['Itinerary']; // get Itineraries 
                $temp['Transfers'] = $longJSON['package']['Transfers']; // get package transfers
                $temp['IsSharingPrice'] = $longJSON['package']['IsSharingPrice']; //
                $temp['IsFixPriceCalculate'] = $longJSON['package']['IsFixPriceCalculate']; //
                $defaultCategoryId = 0;
                $defaultCategory = '';
                $hotelStandardArr = [];
                $$adulttypeArr = [];
                // used for getting | category | meal plan change options
                $priceJsonViewFile = $this->getCategoryAndPriceArrayJSON($temp['tourType'], $market, $PackageType, $PackageSubType);
                $MPTypeArray = $priceJsonViewFile['priceArrJson'];
                $category = $TPId = '';
                
                
                /* get default category 
                 * hotel standard array
                 * Tour type defualt
                 */
                $PackageTax = isset($longJSON['package']['PackageTax'][0]) ? $longJSON['package']['PackageTax'][0] : array(); 
                $categoryDetails = $this->getCategoryAndPriceArray($temp['tourType'], $market, $PackageType, $PackageSubType,'','',$PackageTax,$temp['package']['IsFixedDeparturePackage'],$resultval['GTXPkgId']);
                if (!empty($categoryDetails) && $temp['package']['IsFixedDeparturePackage'] == 1) {
                    $MPTypeArray = $categoryDetails['priceArrJson'];
                }
                
                // if dynamic package then all type has same tp id
                $TPId = ($resultval['PackageType'] == $this->packageTypeStatic) ? $longJSON['package']['TPId'] : $categoryDetails['TPId']; // get tpid all same for dynamic package

                $defaultCategoryId = $categoryDetails['defaultCategoryId'];
                $defaultCategory = $categoryDetails['defaultCategory'];
                $defaultTourType = $categoryDetails['defaultTourType'];

                $hotelStandardArr = $categoryDetails['hotelStandardArr'];
                $tourTypeArrayOfIds = $categoryDetails['tourTypeArrayOfIds'];
                $priceArrJson = $categoryDetails['priceArrJson'];
                $Sharing_Type = $priceArrJson['P'][$defaultCategoryId]['sharing_Type'];
                $adulttypeArr = $priceArrJson['P'][$defaultCategoryId]['adulttypeArr'];
                $MPType = (!empty($categoryDetails['MPType']) && ($categoryDetails['MPType'] != 'LowestCost') && ($PackageType == $this->packageTypeStatic)) ? array_search($categoryDetails['MPType'], unserialize(CONST_MEAL_PLAN_ARR)) : 0;
                $this->hotelTypeArr = $hotelStandardArr; // get hotel standard value dynamic
                $tourType = $this->tourTypeArr; // static value private and group
                // get market type here B2B/B2C
                $marketType = [];
                $tourTypeRadio = [];

                $getTourTypeResult = $this->getTourTypeV2($tourType, $tourTypeArrayOfIds, 'RADIO_BUTTON'); // for radio button
                $tourTypeRadio = $getTourTypeResult['tourTypeRadio'];
                
                $itineraryArr = $temp['itineraryArr'];
                $count_Itinerary = count($itineraryArr);

                $itineraryArrCustom = $hotelTypeArr = $hotelsArr = $ActivityItineraryArr = $ActivityITINERARY_ITEM_Result = [];

                $cityITINERARY = $cityITINERARYTitle = $hotelsInCity = $destinationTitleCustomStr = '';
                $SightSeeingITINERARY = $SightSeeingITINERARY_ITEM = $SightSeeingITINERARY_Result = $SSItiArray = '';

                $destinationTitleCustomArray1 = $destinationIdCustomArray1 = $itineraryArrCustomSight = [];
                
                for ($i = 0; $i < $count_Itinerary; $i++) {

                    $cityITINERARY = $this->filterArrayByValueKeyPair(['Type', 'CITY'], $itineraryArr[$i]['ItineraryItem']);
                    $cityITINERARYTitle = $this->filterArrayByValueKeyPair(['CityId', $cityITINERARY[0]['Id']], $temp['cityArr']);

                    $HotelITINERARY = $this->filterArrayByValueKeyPair(['Type', 'HOTEL'], $itineraryArr[$i]['ItineraryItem']);
                    $SightSeeingITINERARY = $this->filterArrayByValueKeyPair(['Type', 'SIGHTSEEING'], $itineraryArr[$i]['ItineraryItem']);
                    $tRANSPORTITINERARY = $this->filterArrayByValueKeyPair(['Type', 'TRANSPORT'], $itineraryArr[$i]['ItineraryItem']);
                    // filter the days Itinerary on the basis of hotel || hotel must be in last day of repeated day
                    
                    if (($HotelITINERARY[0]['Type']) == 'HOTEL') {
                        
                        $HotelITINERARY_ITEM = $hotelsInCity = $hotelsArrInner = $hotelPriceResultArr = $HotelITINERARY_ITEM_Result = [];
                        $hotelDetailsResult = $hotelID = $hotelName = $hotelStar = $hotelTARating = $hotelPrice = $hotelPriceAdditional = '';
                        
                        $hasHotelInItineray = false;
                        if(!empty($this->hotelTypeArr)){
                            foreach ($this->hotelTypeArr as $hotelTypeKey => $hotelTypeValue) {

                                // fetch hotel ids only
                                $HotelITINERARY_ITEM = $this->filterArrayByValueKeyPair(['Type', ($hotelTypeValue)], $HotelITINERARY[0]['Items']);
                                
                                // fetch which hotel is included true / false
                                if (isset($HotelITINERARY_ITEM[0]['Item']) && count($HotelITINERARY_ITEM[0]['Item'])) {
                                    $HotelITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                                    $HotelITINERARY_ITEM_ResultInc = $this->filterArrayByNoValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                                } else {
                                    $HotelITINERARY_ITEM_Result = $HotelITINERARY_ITEM_ResultInc = [];
                                }
                                $hotelID = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['Id'] : 0;
                                $hotelACCOMSYSID = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['ACCOMSYSID'] : 0;
                                $MEALPLANTYPE = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['MEALPLANTYPE'] : 0;
                                $ROOMTYPE = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['ROOMTYPE'] : 0;
                                $TotalNotInclude = ($HotelITINERARY_ITEM_ResultInc) ? count($HotelITINERARY_ITEM_ResultInc) : 0;

                                $hotelsInCity = (isset($cityITINERARYTitle[0]['Hotels']['Hotel'])) ? $cityITINERARYTitle[0]['Hotels']['Hotel'] : [];

                                if (count($hotelsInCity)) {

                                    $hotelDetailsResult = $this->filterArrayByValueKeyPair(['RefHotelId', $hotelID], $hotelsInCity); // fetch hotel details

                                    $hotelName = (isset($hotelDetailsResult[0]['Name'])) ? $hotelDetailsResult[0]['Name'] : '-';
                                    $hotelStar = (isset($hotelDetailsResult[0]['Star'])) ? $hotelDetailsResult[0]['Star'] : 0;
                                    $hotelTARating = (isset($hotelDetailsResult[0]['Rating'])) ? floor($hotelDetailsResult[0]['Rating']) : 0;
                                }

                                $tourTypeChar = ($defaultTourType == 1) ? 'P' : 'G'; // if private than P else G for Group tour type
                                $hotelPriceResultArr = $this->filterArrayByValueKeyPair(['Type', ($hotelTypeValue)], $priceArrJson[$tourTypeChar]);
                                $hotelPrice = (isset($hotelPriceResultArr[0]) && $hotelPriceResultArr[0]['price']) ? $hotelPriceResultArr[0]['price'] : [];

                                $hotelPrice = isset($hotelPrice) ? $hotelPrice : []; // get the first node value

                                $hotelPriceFiltered = [];
                                $tmpFrom = $tmpTo = '';

                                foreach ($hotelPrice as $hpkey => $hpvalue) {
                                    $tmpFrom = substr($hpvalue['To'], 0, 10);
                                    $tmpTo = substr($hpvalue['From'], 0, 10);
                                    if (($this->currentDateTime >= $tmpFrom) && ($this->currentDateTime <= $tmpTo)) {
                                        $hotelPriceFiltered[] = $hpvalue;
                                    }
                                }

                                $TPSysId = (isset($hotelPriceResultArr[0]['TPSysId'])) ? $hotelPriceResultArr[0]['TPSysId'] : 0;
                                if ($hotelID) {
                                    $hotelsArrInner[$hotelTypeKey] = [
                                        'TPSysId' => $TPSysId,
                                        'hotelID' => $hotelID,
                                        'hotelACCOMSYSID' => $hotelACCOMSYSID,
                                        'MEALPLANTYPE' => $MEALPLANTYPE,
                                        'ROOMTYPE' => $ROOMTYPE,
                                        'hotelName' => $hotelName,
                                        'hotelStar' => $hotelStar,
                                        'hotelTARating' => $hotelTARating,
                                        'orSimilar' => $TotalNotInclude,
                                            //                                'PriceAdditional' => $hotelPrice,
                                    ];
                                    $hasHotelInItineray = true;
                                } else {
                                    $hotelsArrInner[$hotelTypeKey] = [
                                        'hotelID' => $hotelID,
                                    ];
                                }

                                $hotelTypeValueNew = $hotelTypeValue;
                                if (isset($CATEGORY_TYPE_NEW[$hotelTypeValueNew]) && !empty($CATEGORY_TYPE_NEW[$hotelTypeValueNew])) {
                                    $hotelTypeValueNew = $CATEGORY_TYPE_NEW[$hotelTypeValueNew];
                                }
                                $hotelTypeArr[] = ['type' => $hotelTypeKey, 'typeTitle' => $hotelTypeValueNew];
                                if ($hotelID) {
                                    $itineraryArrCustom[$hotelTypeKey][] = [
                                        'hid' => $hotelID,
                                        'haid' => $hotelACCOMSYSID,
                                        'MEALPLANTYPE' => $MEALPLANTYPE,
                                        'ROOMTYPE' => $ROOMTYPE,
                                        'hotel' => $hotelName,
                                        'star' => (int) $hotelStar,
                                        'city' => $cityITINERARYTitle[0]['Title'],
                                        'CityId' => $cityITINERARYTitle[0]['CityId'],
                                        'day' => $this->getValueByKeyFromArray('Day', $itineraryArr[$i]),
                                        'orSimilar' => $TotalNotInclude,
                                    ];
                                }
                            }
                            
                        }else{
                            
                            foreach($HotelITINERARY[0]['Items'] as $itkey => $itvalue){
                                $hotelTypeKey = $itvalue['Id'];
                                $hotelTypeValue = $itvalue['Type'];
                                $HotelITINERARY_ITEM = array(0=>$itvalue); 
                            
                                // fetch which hotel is included true / false
                                if (isset($HotelITINERARY_ITEM[0]['Item']) && count($HotelITINERARY_ITEM[0]['Item'])) {
                                    $HotelITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                                    $HotelITINERARY_ITEM_ResultInc = $this->filterArrayByNoValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                                } else {
                                    $HotelITINERARY_ITEM_Result = $HotelITINERARY_ITEM_ResultInc = [];
                                }
                                
                                $hotelID = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['Id'] : 0;
                                $hotelACCOMSYSID = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['ACCOMSYSID'] : 0;
                                $MEALPLANTYPE = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['MEALPLANTYPE'] : 0;
                                $ROOMTYPE = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['ROOMTYPE'] : 0;
                                $TotalNotInclude = ($HotelITINERARY_ITEM_ResultInc) ? count($HotelITINERARY_ITEM_ResultInc) : 0;

                                $hotelsInCity = (isset($cityITINERARYTitle[0]['Hotels']['Hotel'])) ? $cityITINERARYTitle[0]['Hotels']['Hotel'] : [];

                                if (count($hotelsInCity)) {

                                    $hotelDetailsResult = $this->filterArrayByValueKeyPair(['RefHotelId', $hotelID], $hotelsInCity); // fetch hotel details

                                    $hotelName = (isset($hotelDetailsResult[0]['Name'])) ? $hotelDetailsResult[0]['Name'] : '-';
                                    $hotelStar = (isset($hotelDetailsResult[0]['Star'])) ? $hotelDetailsResult[0]['Star'] : 0;
                                    $hotelTARating = (isset($hotelDetailsResult[0]['Rating'])) ? floor($hotelDetailsResult[0]['Rating']) : 0;
                                }
                                
                                $tourTypeChar = ($defaultTourType == 1) ? 'P' : 'G'; // if private than P else G for Group tour type
                                
                                $hotelPrice = []; // get the first node value

                                $hotelPriceFiltered = [];
                                $tmpFrom = $tmpTo = '';

                                
                                
                                $TPSysId = 0;
                                if ($hotelID) {
                                    $hotelsArrInner[$hotelTypeKey] = [
                                        'TPSysId' => $TPSysId,
                                        'hotelID' => $hotelID,
                                        'hotelACCOMSYSID' => $hotelACCOMSYSID,
                                        'MEALPLANTYPE' => $MEALPLANTYPE,
                                        'ROOMTYPE' => $ROOMTYPE,
                                        'hotelName' => $hotelName,
                                        'hotelStar' => $hotelStar,
                                        'hotelTARating' => $hotelTARating,
                                        'orSimilar' => $TotalNotInclude,
                                            //                                'PriceAdditional' => $hotelPrice,
                                    ];
                                    $hasHotelInItineray = true;
                                } else {
                                    $hotelsArrInner[$hotelTypeKey] = [
                                        'hotelID' => $hotelID,
                                    ];
                                }

                                $hotelTypeValueNew = $hotelTypeValue;
                                if (isset($CATEGORY_TYPE_NEW[$hotelTypeValueNew]) && !empty($CATEGORY_TYPE_NEW[$hotelTypeValueNew])) {
                                    $hotelTypeValueNew = $CATEGORY_TYPE_NEW[$hotelTypeValueNew];
                                }
                                $hotelTypeArr[] = ['type' => $hotelTypeKey, 'typeTitle' => $hotelTypeValueNew];
                                if ($hotelID) {
                                    $itineraryArrCustom[$hotelTypeKey][] = [
                                        'hid' => $hotelID,
                                        'haid' => $hotelACCOMSYSID,
                                        'MEALPLANTYPE' => $MEALPLANTYPE,
                                        'ROOMTYPE' => $ROOMTYPE,
                                        'hotel' => $hotelName,
                                        'star' => (int) $hotelStar,
                                        'city' => $cityITINERARYTitle[0]['Title'],
                                        'CityId' => $cityITINERARYTitle[0]['CityId'],
                                        'day' => $this->getValueByKeyFromArray('Day', $itineraryArr[$i]),
                                        'orSimilar' => $TotalNotInclude,
                                    ];
                                }
                            }
                        }
                        
                        
                        if ($i < $count_Itinerary - 1) {
                            $destinationTitleCustomArray1[$this->getValueByKeyFromArray('Day', $itineraryArr[$i])] = $cityITINERARYTitle[0]['Title'];
                            $destinationIdCustomArray1[$this->getValueByKeyFromArray('Day', $itineraryArr[$i])] = $cityITINERARYTitle[0]['CityId'];
                        }
                    }

                    if ($SightSeeingITINERARY[0]['Type'] === 'SIGHTSEEING') {

                        // fetch which hotel is included true / false
                        if (count($SightSeeingITINERARY[0]['Items'])) {
                            $SightSeeingItineraryArrTemp = [];
                            $SSItiArray = $SightSeeingITINERARY[0]['Items'][0]['Item']; // get single day sightsing list
                            // if result go to fetch Activity Ids
                            if (count($SSItiArray)) {
                                // note : multi array result may be multi for single day
                                $SightSeeingITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $SSItiArray);
                                // if has results than create array
                                if (is_array($SightSeeingITINERARY_ITEM_Result)) {

                                    $SightSeeingItineraryArrResultsTemp = $SightSeeingItineraryArr = [];
                                    foreach ($SightSeeingITINERARY_ITEM_Result as $keySS => $valueSS) {
                                        $sightseeingInCity = isset($cityITINERARYTitle[0]['SightSeeings']['SightSeeing']) ? $cityITINERARYTitle[0]['SightSeeings']['SightSeeing'] : array(); // get all SightSeeing in city

                                        $SightSeeingItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefSSId', $valueSS['Id']], $sightseeingInCity)[0];
                                        if ($i == 3) {
                                        }
                                        $SightSeeingItineraryArrTemp[] = [
                                            //                                        'itemid' => $SightSeeingItineraryArrResultsTemp['RefSSId'] ,
                                            'Title' => $SightSeeingItineraryArrResultsTemp['Title'],
                                                //                                        'IsIncluded' => $valueSS['IsIncluded']
                                        ];
                                    }

                                    $SightSeeingItineraryArr = $SightSeeingItineraryArrTemp;
                                }
                            }
                            // else part of : result go to fetch Activity Ids (define array as blank)
                            else {
                                $SightSeeingItineraryArr = [];
                            }

                            if (!empty($SightSeeingItineraryArr)) {
                                $itineraryArrCustomSight[$this->getValueByKeyFromArray('Day', $itineraryArr[$i])] = $SightSeeingItineraryArr;
                            }
                        }
                    }
                } // outer for loop ends here
                $finalSightseeingArray = array();

                if (isset($itineraryArrCustomSight) && !empty($itineraryArrCustomSight)) {
                    foreach ($itineraryArrCustomSight as $sKey => $sVal) {
                        if (isset($sVal) && !empty($sVal)) {
                            $TitleS = array();
                            foreach ($sVal as $sKey1 => $sVal1) {
                                $TitleS[] = str_replace("&#039;", "'", $sVal1['Title']);
                            }
                            $finalSightseeingArray[$sKey] = implode(', ', $TitleS);
                        } else {
                            $finalSightseeingArray[$sKey] = '-';
                        }
                    }
                }
                $destinationTitleCustomArray = $destinationTitleCustomArray1;

                $myCustomizedestTitleNightsArray = array();
                $r = 0;
                $destinationTitleCustom = '';
                $mdestinationTitleCustom = $mdestinationIdCustom = array();
                $DN = 1;
                foreach (($destinationIdCustomArray1) as $key => $value) {

                    if ($value == $destinationIdCustomArray1[$key - 1]) {
                        $DN++;
                        $CityN = $value;
                    } else {
                        $DN = 1;
                        $CityN = $value;
                        $r++;
                    }


                    $mdestinationTitleCustom[$r] = $destinationTitleCustomArray[$key] . " (" . $DN . "N)";
                    $mdestinationIdCustom[$r] = $value;
                }




                $mr = 0;
                foreach ($mdestinationTitleCustom as $mkey => $mvalue) {
                    $icon = ($mr > 0) ? " | " : "";
                    $destinationTitleCustom .= $icon . $mvalue;
                    $mvalueExplode = explode('(', $mvalue);
                    $myCustomizedestTitleNightsArray[] = ['title' => trim($mvalueExplode[0]), 'nights' => trim(rtrim($mvalueExplode[1], ')'))];
                    $mr++;
                }

                $rm = 0;
                $myCustomizedestIdArray = array();
                foreach (($mdestinationTitleCustom) as $key => $value) {

                    $myCustomizedestIdArray[] = ['cityId' => $mdestinationIdCustom[$key], 'title' => $myCustomizedestTitleNightsArray[$rm]['title'], 'nights' => $myCustomizedestTitleNightsArray[$rm]['nights'], 'CountryIds' => $resultval['CountryIds']];
                    $rm++;
                }
                $destinationTitleCustomFinalStr = $destinationTitleCustom;

                $itineraryArrCustomNew = $itineraryArrCustom;

                $itineraryNewArray = $itineraryNewArrayOnlyHotelId = [];

                $tempArray = [];
                
                foreach ($itineraryArrCustomNew as $k => $val) {
                    $daymerge = 1;
                    $ima = 0;
                    foreach ($val as $key => $value) {

                        if ((int) $value['CityId'] != (int) $val[$key - 1]['CityId']) {
                            $daymerge = 1;
                            $exists = true;
                            $hid = $value['hid'];
                            $haid = $value['haid'];
                            $MEALPLANTYPE = $value['MEALPLANTYPE'];
                            $ROOMTYPE = $value['ROOMTYPE'];
                            $hotel = $value['hotel'];
                            $star = $value['star'];
                            $city = $value['city'];
                            $CityId = $value['CityId'];
                            $day = $value['day'];
                            $orSimilar = $value['orSimilar'];
                        } else {
                            $daymerge++;

                            $exists = false;
                        }

                        if ($exists) {
                            $itineraryNewArray[$k][$ima] = [
                                'hid' => $hid,
                                'haid' => $haid,
                                'MEALPLANTYPE' => $MEALPLANTYPE,
                                'ROOMTYPE' => $ROOMTYPE,
                                'hotel' => $hotel,
                                'star' => $star,
                                'city' => $city,
                                'CityId' => $CityId,
                                'day' => $value['day'],
                                'orSimilar' => $value['orSimilar'],
                            ];
                            $ima1 = $ima;
                            //$itineraryNewArray[$k][$ima1]['night'] = $daymerge;
                            $ima++;
                        }
                        $itineraryNewArray[$k][$ima1]['nights'] = $daymerge;

                        $itineraryNewArrayOnlyHotelId[$k][$haid]['haid'] = $haid;
                        $itineraryNewArrayOnlyHotelId[$k][$haid]['hotelName'] = $hotel;
                        $itineraryNewArrayOnlyHotelId[$k][$haid]['HotelCityId'] = $CityId;
                        $itineraryNewArrayOnlyHotelId[$k][$haid]['night'][] = 1;
                        $itineraryNewArrayOnlyHotelId[$k][$haid]['MEALPLANTYPE'] = $MEALPLANTYPE;
                        $itineraryNewArrayOnlyHotelId[$k][$haid]['ROOMTYPE'] = $ROOMTYPE;
                        $tempArray[] = ($value['hid']) ? $k . $value['hid'] : ''; // insert the standard and hotel id too ( hotel id is duplicate in multiple category )
                    }
                }

                //  end : prepare the array for itineray
                // filter the itinerary array to display
                $itineraryArrCustom = $this->filterDuplicateItinerary('dayNumber', $itineraryArrCustom);

                if (count($itineraryArrCustom) > 2)
                    array_pop($itineraryArrCustom); // remove the last day | because last day should not show in table of hotels grid

                $myPriceArray[$resultval['PkgSysId']] = $priceArrJson;
                $tourTypeChar = ($defaultTourType == 1) ? 'P' : 'G'; // if private than P else G for Group tour type
                
                $displayFinalPrice = $this->getPackagePriceV2($defaultCategoryId, $tourTypeChar, $priceArrJson, true); // Param 4: true ( if calculate discounted price )
//                if($resultval['GTXPkgId'] == 37058){   
//                }
             
                $displayFinalPriceDisc = $this->getPackagePriceV2($defaultCategoryId, $tourTypeChar, $priceArrJson); // get with discount included
                $CurrencySysId = $priceArrJson[$tourTypeChar][$defaultCategoryId]['price'][0]['Currency'];
                $CommissionValueFg = $priceArrJson[$tourTypeChar][$defaultCategoryId]['price'][0]['CommissionValueFg'];
                $PAX = $priceArrJson[$tourTypeChar][$defaultCategoryId]['price'][0]['PAX']; 
                $getCurrencyType = $currencyTypeArray[$priceArrJson[$tourTypeChar][$defaultCategoryId]['price'][0]['Currency']];
                $GroupSize = $priceArrJson[$tourTypeChar][$defaultCategoryId]['GroupSize'];
                $PackageCategoryStr .= "," . $resultval['PackageCategory'];
                $PackageDestinationStr .= "," . $resultval['filterDestinations'];
                $PackageNights[] = $resultval['Nights'];

                if (trim($temp['inclusionsArr'], ',')) {
                    $inclusionsArr = explode(',', trim($temp['inclusionsArr'], ','));
                } else {
                    $inclusionsArr = [];
                }

                $image = explode(',', $resultval['Image']);
                $ImgThumbnail1 = $image[0];

                if ($image[0] != '') {
                    $thumb_icon = (isset($this->b2cUrl) && (!empty($this->b2cUrl))) ? $this->b2cUrl . "public/upload/" . $this->stylecss . "/tours/" . $resultval['PkgSysId'] . '/small/' . $image[0] : $this->baseUrl . "public/upload/" . $this->gtxagencysysid . "/tours/" . $resultval['PkgSysId'] . '/images/large/' . $image[0];
                } else if ($image[1] != '') {
                    $thumb_icon = (isset($this->b2cUrl) && (!empty($this->b2cUrl))) ? $this->b2cUrl . "public/upload/" . $this->stylecss . "/tours/" . $resultval['PkgSysId'] . '/small/' . $image[1] : $this->baseUrl . "public/upload/" . $this->gtxagencysysid . "/tours/" . $resultval['PkgSysId'] . '/images/large/' . $image[1];
                } else {
                    $thumb_icon = trim($temp['package']['ImgThumbnail']);
                }

                if (empty($thumb_icon)) {
                    $thumb_icon = $baseUrl . 'public/images/noimageother.jpg';
                }

                $itineraryNewArrayOnlyHotelIdFinal = $itineraryNewArrayOnlyHotelId1 = array();
                foreach ($itineraryNewArrayOnlyHotelId as $hoIdKey1 => $hoIdVal1) {
                    foreach ($hoIdVal1 as $hoIdKey => $hoIdVal) {
                        $itineraryNewArrayOnlyHotelId1[$k]['haid'][] = $hoIdVal['haid'];
                        $itineraryNewArrayOnlyHotelId1[$k]['hotelName'][] = $hoIdVal['hotelName'];
                        $itineraryNewArrayOnlyHotelId1[$k]['HotelCityId'][] = $hoIdVal['HotelCityId'];
                        $itineraryNewArrayOnlyHotelId1[$k]['night'][] = count($hoIdVal['night']);
                        $itineraryNewArrayOnlyHotelId1[$k]['MEALPLANTYPE'][] = $hoIdVal['MEALPLANTYPE'];
                        $itineraryNewArrayOnlyHotelId1[$k]['ROOMTYPE'][] = $hoIdVal['ROOMTYPE'];
                    }
                }


                foreach ($itineraryNewArrayOnlyHotelId1 as $hoIdKey => $hoIdVal) {
                    //                    $itineraryNewArrayOnlyHotelIdFinal[$hoIdKey] = json_encode(array('hotelName'=>  base64_encode(json_encode($hoIdVal['hotelName'])),'haid'=>$hoIdVal['haid'],'HotelCityId'=>$hoIdVal['HotelCityId'],'night'=>$hoIdVal['night'],'MEALPLANTYPE'=>$hoIdVal['MEALPLANTYPE'],'ROOMTYPE'=>$hoIdVal['ROOMTYPE']));
                    $itineraryNewArrayOnlyHotelIdFinal[$hoIdKey] = json_encode(array('haid' => $hoIdVal['haid'], 'HotelCityId' => $hoIdVal['HotelCityId'], 'night' => $hoIdVal['night'], 'MEALPLANTYPE' => $hoIdVal['MEALPLANTYPE'], 'ROOMTYPE' => $hoIdVal['ROOMTYPE']));
                }

                $SourcePlaceSysId = isset($temp['package']['SourcePlaceSysId']) ? $temp['package']['SourcePlaceSysId'] : '';
                $DestinationPlacesSysId = isset($temp['package']['DestinationPlacesSysId']) ? $temp['package']['DestinationPlacesSysId'] : '';
                $SourcePlaces = isset($temp['package']['SourcePlaces']) ? $temp['package']['SourcePlaces'] : '';
                $DestinationPlaces = isset($temp['package']['DestinationPlaces']) ? $temp['package']['DestinationPlaces'] : '';
                $SourcePlacesHtml = isset($temp['package']['SourcePlaces']) ? $temp['package']['SourcePlaces'] . ' | ' : '';
                $DestinationPlacesHtml = isset($temp['package']['DestinationPlaces']) ? ' | ' . $temp['package']['DestinationPlaces'] : '';
                $getMonthsArray = $fixedInventoryPriceDateWise = $fixedCurrentInventoryDateWise = array();
                $AdultCost = $DefaultAdultCost = $DefaultAdultMarkup = $IsfixedInventory = 0;
                $fixedInventory = $temp['package']['fixedInventory'];
                $AgencyType = isset($_SESSION['User']['AgencyType']) ? trim($_SESSION['User']['AgencyType']) : 0;
                if(!empty($PackageTax) && $AgencyType != 1){
                    $FlightTaxPercentage = $PackageTax['FlightTaxPercentage'];
                    $FlightTaxType = $PackageTax['FlightTaxType'];
                }else{
                    $getDefaultTaxSetting = Catabatic_Helper::getDefaultTaxSetting(1);
                    $FlightTaxPercentage = $getDefaultTaxSetting['TaxPercentage'];
                    $FlightTaxType = $getDefaultTaxSetting['TaxType'];
                } //echo "<pre>";print_r($temp['package']['fixedInventory']);die;
                $fixedInventoryNew = array();
                
                if (!empty($temp['package']['fixedInventory'])) {
                    $inc = 0;
                    foreach ($temp['package']['fixedInventory'] as $key => $value) {
                        $AdultCost = 0;
                        $fixedInventoryNew[$inc]['CityId'] = $key;
                        $fixedInventoryNew[$inc]['CityName'] = $value['CityName'];
                        $fixedInventoryNew[$inc]['FlightInv'] = $value['FlightInv'];
                        foreach ($value['FlightInv'] as $invKey => $invValue) {
                            foreach ($invValue as $invKey1 => $invValue1) {
                                if (trim($invValue1['AirlineName']) != '' && trim($invValue1['DepartureAirportCode']) != '') {
                                    $IsfixedInventory = 1;
                                }
                            }
                        }
                        $countDate = 0;

                        foreach ($value['FromDate'] as $key1 => $value1) {
                            if (strtotime($value1['FromDate']) >= strtotime(date('Y-m-d'))) {
                                $fixedInventoryNew[$inc]['FromDate'][] = $value1['FromDateDMY'];
                                $exchangerate = 1;
                                if((int) $value1['CurrencySysId'] != (int) $CurrencySysId){
                                    $exchangerate = $this->currencyExchangeRate((int) $value1['CurrencySysId'], (int) $CurrencySysId, 0);
                                }
                                

                                $AdultCost = 0;
                                if (!empty($value1)) {
                                    if($market == 'B2C'){
                                        $B2BAdultMarkup = (float) $value1['B2CAdultMarkup'] * $exchangerate;
                                    }else{
                                        $B2BAdultMarkup = (float) $value1['B2BAdultMarkup'] * $exchangerate;
                                    }
                                    
                                    $AdultCost = (float) $value1['AdultCost'] * $exchangerate;

                                    $GSTAmountF = 0;
                                    if ($FlightTaxType == 1) {
                                        $GSTAmountF = ((int) ($AdultCost + $B2BAdultMarkup) * ((int) $FlightTaxPercentage / 100));
                                    } else if ($FlightTaxType == 2) {
                                        $GSTAmountF = ((int) $B2BAdultMarkup * ((int) $FlightTaxPercentage / 100));
                                    }
                                    $AdultCost = (int) ($B2BAdultMarkup + $AdultCost + $GSTAmountF);
                                    //if ($inc == 0) {
                                    $fixedInventoryPriceDateWise[$value1['FromDate']][$key]['Cost'] = $AdultCost;
                                    $fixedInventoryPriceDateWise[$value1['FromDate']][$key]['Inventory'] = (isset($value['Inventory'][$key1]['CurrentInventory']) && $_SESSION['User']['AgencyType'] == 3) ? (int)$value['Inventory'][$key1]['CurrentInventory'] : 0;
                                    //}
                                    if ($inc == 0 && $countDate == 0) {
                                        $DefaultAdultCost = $AdultCost;
                                        $DefaultAdultMarkup = $B2BAdultMarkup;
                                    }
                                    if ($countDate == 0) {
                                        $fixedInventoryNew[$inc]['TotalPrice'] = (float) ($AdultCost);
                                    }

                                    $countDate++;
                                }
                            }
                        }

                        $inc++;
                    }
                }
                
                $checkCategoryDateArrayDate = $CategoryDateNameArray = $CategoryDateArray = array();
                if($temp['package']['IsFixedDeparturePackage'] == 1 && $temp['package']['IsCF'] == 1){
            
                }else{
                    foreach ($MPTypeArray['P'] as $key => $value) {

                        if (count($MPTypeArray['P']) > 1) { 
                            $checkCategoryDateArray = array();
                            foreach ($MPTypeArray['P'][$key]['price'] as $pkey => $pvalue) {
                                if (!in_array(trim($pvalue['From']), $checkCategoryDateArray)) {
                                    array_push($checkCategoryDateArray, trim($pvalue['From']));
                                    $FromD = explode('-', $pvalue['From']);
                                    $currentdateStr = strtotime(date('Y-m-d'));
                                    $FromDateStr = strtotime($pvalue['From']);
                                    if ($currentdateStr <= $FromDateStr) {
                                        if (!in_array(trim($pvalue['From']), $checkCategoryDateArrayDate)) {
                                            array_push($checkCategoryDateArrayDate, trim($pvalue['From']));
                                            $CategoryDateArray[] = [
                                                'FromDateVal' => $pvalue['From'],
                                                'FromDate' => $FromD[2] . '/' . $FromD[1] . '/' . $FromD[0],
                                            ];
                                        }
                                        $PackageFlightCost = $fixedInventoryPriceDateWise[$pvalue['From']];
                                        $PackageFlightInventory = $fixedCurrentInventoryDateWise[$pvalue['From']];
                                        $PricePerPerson = $MPTypeArray['P'][$key]['price'][0]['PricePerPerson'];
                                        $CategoryDateNameArray[$key][] = array('cost' => $PackageFlightCost, 'PricePerPerson' => $PricePerPerson, 'date' => date('d M', strtotime($pvalue['From'])),'Inventory' => $PackageFlightInventory);
                                        $getMonthsArray = array_merge($getMonthsArray, $this->getMonths($pvalue['From'], $pvalue['To']));
                                    }
                                }
                            }
                            //}
                        } else {

    //                        $CategoryDateArray  = array();
                            $checkCategoryDateArray = array();
                            foreach ($MPTypeArray['P'][$key]['price'] as $pkey => $pvalue) {
                                if (!in_array(trim($pvalue['From']), $checkCategoryDateArray)) {
                                    array_push($checkCategoryDateArray, trim($pvalue['From']));
                                    $FromD = explode('-', $pvalue['From']);
                                    $currentdateStr = strtotime(date('Y-m-d'));
                                    $FromDateStr = strtotime($pvalue['From']);

                                    if ($currentdateStr <= $FromDateStr) {
                                        if (!in_array(trim($pvalue['From']), $checkCategoryDateArrayDate)) {
                                            array_push($checkCategoryDateArrayDate, trim($pvalue['From']));
                                            $CategoryDateArray[] = [
                                                'FromDateVal' => $pvalue['From'],
                                                'FromDate' => $FromD[2] . '/' . $FromD[1] . '/' . $FromD[0],
                                            ];
                                        }
                                        $PackageFlightCost = $fixedInventoryPriceDateWise[$pvalue['From']];
                                        $PackageFlightInventory = $fixedCurrentInventoryDateWise[$pvalue['From']];
                                        $PricePerPerson = $MPTypeArray['P'][$key]['price'][0]['PricePerPerson'];
                                        $CategoryDateNameArray[$key][] = array('cost' => $PackageFlightCost, 'PricePerPerson' => $PricePerPerson, 'date' => date('d M Y', strtotime($pvalue['From'])),'Inventory' => $PackageFlightInventory);
                                        $getMonthsArray = array_merge($getMonthsArray, $this->getMonths($pvalue['From'], $pvalue['To']));
                                    }
                                }
                            }
                        }
                    }
                }
                if($resultval['GTXPkgId'] == 10292){
                    //echo "<pre>";print_r($CategoryDateNameArray);die;
                }
                $CommissionValueFlightFg = 0;
                if($_SESSION['User']['AgencyType'] == 3 && $_SESSION['User']['IsFranchise'] == 2 && !empty($_SESSION['User']['FranchiseeCT'])){
                    if($temp['package']['IsFixedDeparturePackage'] == 1){
                        $FranchiseeCT = isset($_SESSION['User']['FranchiseeCT'][1]) ? $_SESSION['User']['FranchiseeCT'][1] : array();
                    }else{
                        $FranchiseeCT = isset($_SESSION['User']['FranchiseeCT'][0]) ? $_SESSION['User']['FranchiseeCT'][0] : array();
                    }
                    
                    if(!empty($FranchiseeCT)){
                        $FCommissionType = $FranchiseeCT['FCommissionType']; 
                        $FCommissionValue = $FranchiseeCT['FCommissionValue'];
                        if($FCommissionType == 1){
                            $CommissionValueFlightFg = $DefaultAdultMarkup * $FCommissionValue / 100; 
                        }else{
                            $CommissionValueFlightFg = $DefaultAdultCost * $FCommissionValue / 100; 
                        } 
                    } 
                }
//                if($resultval['GTXPkgId'] == 10292){
//                    echo "<pre>";print_r($itineraryNewArray);die;
//                }
                
//                if($resultval['GTXPkgId'] == 52004){
//                }
                $defaultCategoryIdm = isset($temp['package']['Itineraries']['Itinerary'][0]['ItineraryItem'][1]['Items'][0]['Id']) ? $temp['package']['Itineraries']['Itinerary'][0]['ItineraryItem'][1]['Items'][0]['Id'] : 0;
                
                $forEnquiryData = [
                    'PkgSysId' => $resultval['PkgSysId'],
                    'GTXPkgId' => $resultval['GTXPkgId'],
                    'TPId' => !empty($TPId) ? $TPId : $resultval['GTXPkgId'],
                    'package' => ['Name' => trim(str_replace('/', ' ', $temp['package']['Name'])), 'Tagline1' => (isset($temp['package']['Tagline1']) ? trim($temp['package']['Tagline1']) : "")],
                    'PackageType' => $resultval['PackageType'],
                    'defaultCategoryId' => ($defaultCategoryId != '') ? $defaultCategoryId : $defaultCategoryIdm,
                    'defaultTourType' => $defaultTourType,
                    'mp' => $MPType,
                    'Countries' => $resultval['Countries'],
                    'CountryIds' => isset($resultval['CountryIds']) ? ($resultval['CountryIds']) : 0,
                    'IsFixedDeparturePackage' => $temp['package']['IsFixedDeparturePackage'],
                    'CategoryDateArray' => $CategoryDateArray, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                    'myCustomizeDestNights' => $myCustomizedestIdArray,
                    'Duration' => $resultval['Nights'],
                    'Currency' => ($CurrencySysId) ? (int) $CurrencySysId : 0,
                    'CurrencyType' => ($getCurrencyType) ? $getCurrencyType : 'INR',
                    'destinationTitleCustomFinalStr' => $destinationTitleCustomFinalStr,
                    'isHotel' => count($itineraryNewArray), // custom field
                    'adulttypeArr' => $adulttypeArr,
                    'IsSharingPrice' => $temp['IsSharingPrice'],
                    'IsFixPriceCalculate' => $temp['IsFixPriceCalculate'],
                    'querydata' => $querydata,
                ];
                if($resultval['GTXPkgId'] == 10292){
                        //echo "<pre>";print_r($CategoryDateNameArray);die;
                }
                //                if($IsfixedInventory == 1){
                //                    $mfixedInventory = array_pop(array_reverse($fixedInventory));
                //                    $FromDateArr = array_pop(array_reverse($mfixedInventory['FromDate']));
                //                    $displayFinalPrice = (int)($displayFinalPrice + $FromDateArr['B2BAdultMarkup'] + $FromDateArr['AdultCost']);
                //                }

                $pricerangetemp = $this->getRangeByValue(unserialize(CONST_PRICE_RANGE_5000), (int) ($displayFinalPrice + $DefaultAdultCost));
                $pricerangetemp1 = explode('-', $pricerangetemp);
                if ((int) $pricerangetemp > 0) {
                    $PackagePriceRangeCountArr[$pricerangetemp]++;
                    $PackagePriceRange[$pricerangetemp1[0]] = array('value' => trim($pricerangetemp), 'count' => $PackagePriceRangeCountArr[$pricerangetemp]);
                }


                if ($IsfixedInventory > 0) {
                    $SourcePlacesHtml = $DestinationPlacesHtml = ' | ';
                }

                if (count($itineraryNewArray) > 0) {
                    $ActiveLi = 0;
                } else if ($IsfixedInventory > 0) {
                    $ActiveLi = 1;
                } else if ($finalSightseeingArray > 0) {
                    $ActiveLi = 2;
                } else if (!empty((html_entity_decode(html_entity_decode($temp['package']['Terms']['Inclusion']))))) {
                    $ActiveLi = 3;
                } else if ((html_entity_decode(html_entity_decode($temp['package']['Terms']['Exclusions'])))) {
                    $ActiveLi = 4;
                } else {
                    $ActiveLi = 0;
                }
                
                
            //                if ($displayFinalPrice > 0 || $resultval['AgencySysId'] == 1) {
                    if ($temp['package']['IsFixedDeparturePackage'] == 1) {
                        $result1[] = [
                            'PkgSysId' => $resultval['PkgSysId'],
                            'Countries' => $resultval['Countries'],
                            'CountryIds' => isset($resultval['CountryIds']) ? ($resultval['CountryIds']) : 0,
                            'TPId' => !empty($TPId) ? $TPId : $resultval['GTXPkgId'],
                            'GTXPkgId' => $resultval['GTXPkgId'],
                            'DisplayIndex' => $resultval['DisplayIndex'],
                            'PackageType' => $resultval['PackageType'],
                            'CurrencyType' => ($getCurrencyType) ? $getCurrencyType : 'INR',
                            ////                        //                'StarRating' => $resultval['StarRating'],
                            'filterDestinations' => $resultval['filterDestinations'], // variable used in json
                            'Destinations' => $resultval['Destinations'], // variable used in json
                            'DestinationsId' => $resultval['DestinationsId'], // variable used in json
                            'des' => trim($SourcePlacesHtml . $destinationTitleCustomFinalStr . $DestinationPlacesHtml), // variable used in json
                            'desSaArr' => array_count_values($destinationTitleCustomArray), // variable used in json
                            'myCustomizeDestNights' => $myCustomizedestIdArray,
                            'myCustomizeDestNightsEncoded' => json_encode($myCustomizedestIdArray),
                            'PriceRange' => $pricerangetemp,
                            'Duration' => $resultval['Nights'],
                            'PackageTypeArr' => explode(',', trim($temp['packageTypeArr'], ',')), // custom field
                            'IsCruise' => (is_array($PackageTypeArr) && in_array('Cruise', $PackageTypeArr) && !in_array('Flight', $PackageTypeArr)) ? 1 : 0,
                            'hotelTypeArr' => $this->array_filter_rv($hotelTypeArr), // custom field
                            'inclusionsArr' => $inclusionsArr, // custom field
                            'package' => ['Name' => trim(str_replace('/', ' ', $temp['package']['Name'])), 'Tagline1' => (isset($temp['package']['Tagline1']) ? trim($temp['package']['Tagline1']) : "")], // custom field
                            'ImgThumbnail' => trim($temp['package']['ImgThumbnail']),
                            'ImgThumbnail1' => $thumb_icon,
                            'defaultCategoryId' => ($defaultCategoryId != '') ? $defaultCategoryId : $defaultCategoryIdm, // custom field
                            'defaultStandard' => $defaultCategory, //$hotelTypeArr[0]['type'] ,
                            'itineraryArr1' => $itineraryNewArray, // custom field
                            'isHotel' => count($itineraryNewArray), // custom field
                            'itineraryNewArrayOnlyHotelId' => (!empty($itineraryNewArrayOnlyHotelIdFinal)) ? $itineraryNewArrayOnlyHotelIdFinal : '', // custom field
                            'Price' => ($displayFinalPrice > 0) ? (int) ($displayFinalPrice + $DefaultAdultCost) : 0, // custom field
                            'PAX' => (int)$PAX, // custom field
                            'CommissionValueFg' => (int) ($CommissionValueFg + $CommissionValueFlightFg), // custom field
            
                            'sharing_Type' => $Sharing_Type,
                            'PriceDis' => $displayFinalPriceDisc, // custom field price includes discount too
                            
                            'defaultTourType' => $defaultTourType, //$hotelTypeArr[0]['type'] ,
                            'tourType' => $tourTypeRadio,
                            'deal' => $resultval['HotDeal'],
                            'mp' => (int) $MPType, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'mpArr' => $MPTypeArray, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'CategoryDateArray' => $CategoryDateArray, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'GroupSize' => $GroupSize, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'SourcePlaceSysId' => $SourcePlaceSysId, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'DestinationPlacesSysId' => $DestinationPlacesSysId, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'SourcePlaces' => $SourcePlaces, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'DestinationPlaces' => $DestinationPlaces, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'Inclusion' => (html_entity_decode(html_entity_decode($temp['package']['Terms']['Inclusion']))),
                            'Exclusions' => (html_entity_decode(html_entity_decode($temp['package']['Terms']['Exclusions']))),
                            'finalSightseeingArray' => $finalSightseeingArray,
                            'IsFixedDeparturePackage' => $temp['package']['IsFixedDeparturePackage'],
                            'forEnquiryData' => base64_encode(json_encode($forEnquiryData)),
                            'FirstDepartureCityId' => isset($fixedInventoryNew[0]['CityId']) ? $fixedInventoryNew[0]['CityId'] : 0,
                            'FirstCategoryId' => isset($hotelTypeArr[0]['type']) ? $hotelTypeArr[0]['type'] : 0,
                            'FirstCategoryName' => isset($hotelTypeArr[0]['typeTitle']) ? $hotelTypeArr[0]['typeTitle'] : '',
                            'fixedInventory' => $fixedInventoryNew,
                            'IsfixedInventory' => $IsfixedInventory,
                            'getMonthsArray' => ($getMonthsArray),
                            'CategoryDateNameArray' => $CategoryDateNameArray,
                            'activeLi' => $ActiveLi,
                            'MinPax' => $resultval['MinPax'],
                        ];
                    } else {
                        $result2[] = [
                            'PkgSysId' => $resultval['PkgSysId'],
                            'Countries' => $resultval['Countries'],
                            'CountryIds' => isset($resultval['CountryIds']) ? ($resultval['CountryIds']) : 0,
                            'TPId' => !empty($TPId) ? $TPId : $resultval['GTXPkgId'],
                            'GTXPkgId' => $resultval['GTXPkgId'],
                            'DisplayIndex' => $resultval['DisplayIndex'],
                            'PackageType' => $resultval['PackageType'],
                            'CurrencyType' => ($getCurrencyType) ? $getCurrencyType : 'INR',
                            //                'StarRating' => $resultval['StarRating'],
                            'filterDestinations' => $resultval['filterDestinations'],
                            'Destinations' => $resultval['Destinations'], // variable used in json
                            'DestinationsId' => $resultval['DestinationsId'], // variable used in json
                            'des' => trim($SourcePlacesHtml . $destinationTitleCustomFinalStr . $DestinationPlacesHtml), // variable used in json
                            'desSaArr' => array_count_values($destinationTitleCustomArray), // variable used in json
                            'myCustomizeDestNights' => $myCustomizedestIdArray,
                            'myCustomizeDestNightsEncoded' => json_encode($myCustomizedestIdArray),
                            'PriceRange' => $pricerangetemp,
                            'Duration' => $resultval['Nights'],
                            'PackageTypeArr' => explode(',', trim($temp['packageTypeArr'], ',')), // custom field
                            // 'IsCruise' => (in_array('Cruise',$PackageTypeArr) && !in_array('Flight',$PackageTypeArr)) ? 1 : 0,
                            'IsCruise' => (is_array($PackageTypeArr) && in_array('Cruise', $PackageTypeArr) && !in_array('Flight', $PackageTypeArr)) ? 1 : 0,
                            'hotelTypeArr' => $this->array_filter_rv($hotelTypeArr), // custom field
                            'inclusionsArr' => $inclusionsArr, // custom field
                            'package' => ['Name' => trim(str_replace('/', ' ', $temp['package']['Name'])), 'Tagline1' => (isset($temp['package']['Tagline1']) ? trim($temp['package']['Tagline1']) : "")], // custom field
                            'ImgThumbnail' => trim($temp['package']['ImgThumbnail']),
                            'ImgThumbnail1' => $thumb_icon,
                            'defaultCategoryId' => ($defaultCategoryId != '') ? $defaultCategoryId : $defaultCategoryIdm, // custom field
                            'defaultStandard' => $defaultCategory, //$hotelTypeArr[0]['type'] ,
                            'itineraryArr1' => $itineraryNewArray, // custom field
                            'isHotel' => count($itineraryNewArray), // custom field
                            'itineraryNewArrayOnlyHotelId' => (!empty($itineraryNewArrayOnlyHotelIdFinal)) ? $itineraryNewArrayOnlyHotelIdFinal : '', // custom field
                            'Price' => (int) ($displayFinalPrice + $DefaultAdultCost), // custom field
                            'PAX' => (int)$PAX, // custom field
                            'CommissionValueFg' => (int) ($CommissionValueFg + $CommissionValueFlightFg), // custom field
            
                            'sharing_Type' => $Sharing_Type,
                            'PriceDis' => $displayFinalPriceDisc, // custom field price includes discount too
                            
                            'defaultTourType' => $defaultTourType, //$hotelTypeArr[0]['type'] ,
                            'tourType' => $tourTypeRadio,
                            'deal' => $resultval['HotDeal'],
                            'mp' => (int) $MPType, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'mpArr' => $MPTypeArray, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'CategoryDateArray' => $CategoryDateArray, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'GroupSize' => $GroupSize, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'SourcePlaceSysId' => $SourcePlaceSysId, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'DestinationPlacesSysId' => $DestinationPlacesSysId, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'SourcePlaces' => $SourcePlaces, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'DestinationPlaces' => $DestinationPlaces, //  // 0 : lowest cost | 6 , 7 , 9 : Meal plan
                            'Inclusion' => (html_entity_decode(html_entity_decode($temp['package']['Terms']['Inclusion']))),
                            'Exclusions' => (html_entity_decode(html_entity_decode($temp['package']['Terms']['Exclusions']))),
                            'finalSightseeingArray' => $finalSightseeingArray,
                            'IsFixedDeparturePackage' => $temp['package']['IsFixedDeparturePackage'],
                            'forEnquiryData' => base64_encode(json_encode($forEnquiryData)),
                            'FirstDepartureCityId' => isset($fixedInventoryNew[0]['CityId']) ? $fixedInventoryNew[0]['CityId'] : 0,
                            'FirstCategoryId' => isset($hotelTypeArr[0]['type']) ? $hotelTypeArr[0]['type'] : 0,
                            'FirstCategoryName' => isset($hotelTypeArr[0]['typeTitle']) ? $hotelTypeArr[0]['typeTitle'] : '',
                            'fixedInventory' => $fixedInventoryNew,
                            'IsfixedInventory' => $IsfixedInventory,
                            'getMonthsArray' => ($getMonthsArray),
                            'CategoryDateNameArray' => $CategoryDateNameArray,
                            'activeLi' => $ActiveLi,
                            'MinPax' => $resultval['MinPax'],
                        ];
                    }
//                }
            }
        }

        $price1 = array_column($result1, 'Price');
        array_multisort($price1, SORT_ASC, $result1);
        $price2 = array_column($result2, 'Price');
        array_multisort($price2, SORT_ASC, $result2);

        $result = array_merge($result1, $result2);
//        echo "<pre>";print_r($result);die;
        if (!empty($myPriceArray)){
            $this->createJsonFile($myPriceArray, 'package_price.json'); // create json file ui manipulation
        }

        if (!empty($deleteNetworkPackage)) {
            $deleteNetworkPackageStr = implode(',', $deleteNetworkPackage);
            $objPackagesMaster->deletePackageByGTXPkgId($deleteNetworkPackageStr);
        }

// package category for filter
        $PackageCategory = array_unique(explode(',', str_replace('"', '', trim($PackageCategoryStr, ','))));
        asort($PackageCategory);

        $PackageCategory1 = array_values($PackageCategory); // reset the array key

        $PackageDestination = array_unique(explode(',', str_replace('"', '', trim($PackageDestinationStr, ','))));
        asort($PackageDestination);
        $PackageDestination1 = array_values($PackageDestination); // reset the array key
        // package number of nights for filter
        $PackageNightsU = (array_unique($PackageNights));
        asort($PackageNightsU);
        $PackageNights1 = array_values($PackageNightsU);

        // package price range for filter
        $PackagePriceRangeU = (($PackagePriceRange));

        ksort($PackagePriceRangeU); // sort array by key
        $PackagePriceRange1 = array_values($PackagePriceRangeU);
        //$filterMonthArray = array('January','February','March','April','May','June','July','August','September','October','November','December');

        $filterMonthArray = unserialize(CONST_YEAR_NAME);
        if (count($result))
            $this->createJsonFile(['rows' => $result, 'filterCat' => $PackageCategory1, 'filterDest' => $PackageDestination1, 'filterNight' => $PackageNights1, 'filterPrice' => $PackagePriceRange1, 'filterMonth' => $filterMonthArray], 'tours_package.json', 'public/data/dynamic/'); // create package json file for ui

        return Zend_Json::encode(['rows' => $result, 'filterCat' => $PackageCategory1, 'filterDest' => $PackageDestination1, 'filterNight' => $PackageNights1, 'filterPrice' => $PackagePriceRange1, 'filterMonth' => $filterMonthArray]);
    }

    function getCategoryAndPriceArray(array $tourType = null, $market = null, $PackageType = null, $PackageSubType = null, $SourcePlaceSysId = null, $fromDate = null, $PackageTax = array(),$IsFixedDeparturePackage = 0, $GTXPkgId = 0) {
        
        $defaultCategoryId = $priceArrJson = $defaultTourType = '';
        // $GSTAmountF = '';
        $this->objMdl = new Admin_Model_CRUD();
        $PackageTax = array();
        foreach ($tourType as $tourKey => $tourVal) {

            $priceArrJsonInner1 = [];
            
            // check the market type is b2b or b2c
            if ($tourVal['MarketTypeTitle'] == $market) {

                $priceArrJsonInner = $categoryArray = $tourtypeArray = [];
                foreach ($tourVal['TourType'] as $k => $v) {

                    $category = $v['Categories']['Category'];

                    if (is_array($category) && count($category)) {

                        $tempCategory = [];
                        $MPType = '';

                        foreach ($category as $keyCat => $valueCat) {
                            //                              echo $valueCat['Type'] = $keyCat.'SSSS'; // this is temporary code need to delete this line of code
                            // if dynamic package
                            if (($PackageType) && ($PackageType == $this->packageTypeStatic)) {
                                $MPTypeArray = [];
                                foreach ($valueCat['MPType'] as $valueMP) {
                                    if (isset($valueMP['SeletedForPackage']) && !empty($valueMP['SeletedForPackage'])) {
                                        $MPType = $valueMP['MPTypeText'];
                                    }
                                    if ($valueMP['MPTypeText'] != "LowestCost") {
                                        $MPTypeArray[$valueMP['MPTypeId']] = $valueMP['MPTypeText'];
                                    }
                                }
                            }

                            // create hotel type/standard array whether in group or private tour
                            if ($k == 0) {
                                $hotelStandardArr[$valueCat['CategoryId']] = $valueCat['Type']; // create hotel type array for display radio button on view
                                $categoryArray[$valueCat['CategoryId']] = ['Type' => $valueCat['CategoryId'], 'Title' => $valueCat['Type']];
                                if (isset($valueMP['MPTypeText']) && ($valueMP['MPTypeText'] != "LowestCost") && ($valueMP['MPTypeText'] != "ITENARYWISE")) {
                                    $categoryArray[$valueCat['CategoryId']]['mptype'][] = $MPTypeArray;
                                }
                            }


                            if ($SourcePlaceSysId && $fromDate) {
                                foreach ($valueCat['MPType'][0]['PriceAdditional'] as $key => $value) {
                                    if ($value['DestinationSysId'] == $SourcePlaceSysId && $fromDate == $value['From']) {
                                        $PriceAdditional[] = $value;
                                    }
                                }
                            } else {
                                $PriceAdditional = $valueCat['MPType'][0]['PriceAdditional'];
                            }

                            $objHelperGeneral = Zend_Controller_Action_HelperBroker::getStaticHelper('General');
                            $PC = (isset($PriceAdditional[0]['PC'])) ? (int) $PriceAdditional[0]['PC'] : (int) $PriceAdditional[0]['Currency'];
                            if(isset($_SESSION['User']['AgentCurrency']) && (int)$_SESSION['User']['AgentCurrency'] > 0){
                                $Currency = (int) $_SESSION['User']['AgentCurrency'];
                            }else{
                                $Currency = (int) $PriceAdditional[0]['Currency'];
                            }
                            $PriceAdditionaltemp = $PriceAdditional[0];
                            $adulttypeArr = [];
                            $TaxType = $TaxPercentage = 0;
                            if($_SESSION['User']['AgencyType'] != 3){
                                if(!empty($PackageTax)){
                                    $TaxPercentage = $PackageTax['PackageTaxPercentage'];
                                    $TaxType = $PackageTax['PackageTaxType']; 
                                }else{
                                    $getDefaultTaxSetting = Catabatic_Helper::getDefaultTaxSetting(5);
                                    $TaxPercentage = $getDefaultTaxSetting['TaxPercentage'];
                                    $TaxType = $getDefaultTaxSetting['TaxType'];
                                }
                            }
                            if ($Currency == $PC) {
                                $finalpHexa = (float) $PriceAdditionaltemp['CostHexa'];
                                $finalpQuint = (float) $PriceAdditionaltemp['CostQuint'];
                                $finalpQuad = (float) $PriceAdditionaltemp['CostQuad'];
                                if (!empty($finalpQuad) && $finalpQuad != 0 && $finalpQuad != 'null') {
                                    $adulttypeArr[] = 'Quad';
                                }
                                if (!empty($finalpQuint) && $finalpQuint != 0 && $finalpQuint != 'null') {
                                    $adulttypeArr[] = 'Quint';
                                } if (!empty($finalpHexa) && $finalpHexa != 0 && $finalpHexa != 'null') {
                                    $adulttypeArr[] = 'Hexa';
                                }

                                if (!empty($finalpHexa) && $finalpHexa != 0 && $finalpHexa != 'null') {
                                    $COSTDO = (float) $PriceAdditionaltemp['CostHexa'];
                                    $sharing_type = 'Hexa Sharing';
                                } else if (!empty($finalpQuint) && $finalpQuint != 0 && $finalpQuint != 'null') {
                                    $COSTDO = (float) $PriceAdditionaltemp['CostQuint'];
                                    $sharing_type = 'Quint Sharing';
                                } else if (!empty($finalpQuad) && $finalpQuad != 0 && $finalpQuad != 'null') {
                                    $COSTDO = (float) $PriceAdditionaltemp['CostQuad'];
                                    $sharing_type = 'Quad Sharing';
                                } else {
                                    $COSTDO = (float) $PriceAdditionaltemp['PricePerPerson'];
//                                    $sharing_type = 'Per person '.(int)($PriceAdditionaltemp['PAX']).' Sharing';
                                    $sharing_type = 'Per Person';
                                }
                            } else {
                                $exchangerate = $objHelperGeneral->currencyExchangeRate((int) $PC, (int) $Currency, 0);
                                $COSTDO = $exchangerate * $PriceAdditionaltemp['COSTDO'];
                                //$Currency = $PC;
                            }
                            
                            $MarkValue = $PriceAdditionaltemp['MarkValue'];
                            $MarkType = $PriceAdditionaltemp['MarkType'];
                            if ($MarkType == 'FixedPercent') {
                                $COSTDOPre = $COSTDO;
                                $COSTDOWOMarkup = 100 * $COSTDO / ($MarkValue + 100);
                                $MarkupCost = $COSTDOPre - $COSTDOWOMarkup;
                            } else {
                                $MarkupCost = (int) $MarkValue;
                                $COSTDOWOMarkup = (int) $COSTDO - (int) $MarkValue;
                            }

                            if ($_SESSION['User']['data']['Markup'] > 0 && $MarkType == 'FixedPercent') {
                                $COSTDO = Catabatic_Helper::calculateMarkup($COSTDOWOMarkup);
                                $MarkupCost = Catabatic_Helper::calculateReturnOnlyMarkup($COSTDOWOMarkup);
                            }
            
                            $CommissionValueFg = 0;
                            
                            if($_SESSION['User']['AgencyType'] == 3 && $_SESSION['User']['IsFranchise'] == 2 && !empty($_SESSION['User']['FranchiseeCT'])){
                                if($IsFixedDeparturePackage == 1){
                                    $FranchiseeCT = isset($_SESSION['User']['FranchiseeCT'][1]) ? $_SESSION['User']['FranchiseeCT'][1] : array();
                                }else{
                                    $FranchiseeCT = isset($_SESSION['User']['FranchiseeCT'][0]) ? $_SESSION['User']['FranchiseeCT'][0] : array();
                                }
                                
                                if(!empty($FranchiseeCT)){
                                    $CommissionType = $FranchiseeCT['CommissionType']; 
                                    $CommissionValue = $FranchiseeCT['CommissionValue'];
                                    if($CommissionType == 1){
                                        $CommissionValueFg = $MarkupCost * $CommissionValue / 100; 
                                    }else{
                                        $CommissionValueFg = ($COSTDOWOMarkup + $MarkupCost) * $CommissionValue / 100; 
                                    } 
                                } 
                            }
            
                            if ($TaxType == 1) {
                                $GSTAmountF = ((int) ($COSTDO) * ((int) $TaxPercentage / 100));
                            } else if ($TaxType == 2) {
                                $GSTAmountF = ((int) $MarkupCost * ((int) $TaxPercentage / 100));
                            }
                            
                            $PriceAdditionaltemp['PricePerPerson'] = round(($COSTDO + $GSTAmountF), 2);
                            $PriceAdditionaltemp['CommissionValueFg'] = round(($CommissionValueFg), 2); 
                            $PriceAdditionaltemp['Currency'] = $Currency;
                            $PriceAdditional[0] = $PriceAdditionaltemp;
                            
                            $tempCategory[$valueCat['CategoryId']] = [
                                'TPId' => $valueCat['TPSysId'],
                                'CategoryTitle' => $valueCat['Type'],
                                'SFP' => $valueCat['SeletedForPackage'],
                                //                                    'price'=> $valueCat['PriceAdditional'] // this was old pattern
                                'price' => $PriceAdditional,
                                'GroupSize' => $valueCat['GroupSize'],
                                'exchangerate' => $exchangerate,
                                'sharing_Type' => $sharing_type,
                                'adulttypeArr' => $adulttypeArr,
                            ];
                            if ($keyCat == 0) {
                                $TPId = $valueCat['TPSysId'];
                                $defaultCategory = $valueCat['Type'];
                                $defaultCategoryId = $valueCat['CategoryId']; // set default category for package on load
                            }
                        }
                    }
                    $tourTypeArrayOfIds[] = $v['TourType']; // get the current loop package tour type id only to create radio button
                    $priceArrJsonInner[$v['TourTypeTitle'][0]] = $tempCategory;

                    if ($k == 0) {
                        $defaultTourType = $v['TourType'];
                    }

                    $tourtypeArray[$v['TourType']] = ['TourTypeTitle' => $v['TourTypeTitle'], 'TourType' => $v['TourType']];
                }
                $priceArrJsonInner1 = $priceArrJsonInner;
            }
        }
                           
        $MPType = $this->getMpTypeByCategory(!empty($categoryArray) ? $categoryArray : array(), $defaultCategoryId);

        $priceArrJson = !empty($priceArrJsonInner) ? $priceArrJsonInner : array(); // assign the inner created to outer loop variable

        return [
            "TPId" => isset($TPId) ? $TPId : '',
            "priceArrJson" => $priceArrJson,
            "hotelStandardArr" => isset($hotelStandardArr) ? $hotelStandardArr : array(),
            "defaultCategory" => isset($defaultCategory) ? $defaultCategory : '',
            "defaultCategoryId" => $defaultCategoryId,
            "tourTypeArrayOfIds" => isset($tourTypeArrayOfIds) ? $tourTypeArrayOfIds : array(),
            "defaultTourType" => $defaultTourType,
            "category" => isset($categoryArray) ? $categoryArray : array(),
            "tourtype" => isset($tourtypeArray) ? $tourtypeArray : array(),
            "MPType" => $MPType,
        ];
    }

    /*
     * getPriceArrayFullyDynamic function is used to get array
     */

    function getPriceArrayFullyDynamicJSON(array $tourType, $market, $PackageType = null, $PackageSubType = null) {

        $priceArrJson = [];
        foreach ($tourType as $tourKey => $tourVal) {

            // check the market type is b2b or b2c
            if ($tourVal['MarketTypeTitle'] === $market) {

                $priceArrJsonInner = $categoryArray = $tourtypeArray = [];
                foreach ($tourVal['TourType'] as $k => $v) {

                    $category = $v['Categories']['Category'];

                    if (is_array($category) && count($category)) {

                        $tempCategory = [];
                        $MPType = '';

                        foreach ($category as $keyCat => $valueCat) {

                            $tempCategory[$valueCat['Type']] = [
                                'TPId' => $valueCat['TPSysId'],
                                'SFP' => $valueCat['SeletedForPackage'],
                                    //                                    'price'=> $valueCat['PriceAdditional'] // this was old pattern
                                    //                                'price'=> $valueCat['MPType'][0]['PriceAdditional']
                            ];

                            // check only if dynamic package
                            // Lowest cost and meal plan type package : Dynamic package case only
                            if ($PackageType == $this->packageTypeStatic) {

                                if ($valueMP['MPTypeText'] == "LowestCost") {
                                    $tempCategory[$valueCat['Type']]['price'] = $this->getPriceFromMultiDatewise($valueCat['MPType'][0]['PriceAdditional']);
                                } else {
                                    $MPTypeArray = [];
                                    foreach ($valueCat['MPType'] as $valueMP) {
                                        if (isset($valueMP['SeletedForPackage']) && !empty($valueMP['SeletedForPackage'])) {
                                            $MPType = $valueMP['MPTypeText'];
                                        }
                                        if ($valueMP['MPTypeText'] != "LowestCost") {
                                            $MPTypeArray[$valueMP['MPTypeId']] = $valueMP['MPTypeText'];
                                        }

                                        $MPTypeArray[$valueMP['MPTypeId']] = [
                                            'id' => $valueMP['MPTypeId'],
                                            'txt' => $valueMP['MPTypeText'],
                                            'SFP' => $valueMP['SeletedForPackage'], // SFP* referse that this is selected for this package
                                            'price' => $this->getPriceFromMultiDatewise($valueMP['PriceAdditional'])
                                        ];
                                    }
                                    $tempCategory[$valueCat['Type']]['mptype'] = $MPTypeArray;
                                }
                            } else {
                                if (is_array($valueCat['MPType']) && count($valueCat['MPType'])) {

                                    // ITENARYWISE : readymade package case only
                                    $tempCategory[$valueCat['Type']]['price'] = $this->getPriceFromMultiDatewise($valueCat['MPType'][0]['PriceAdditional']);
                                } else {
                                    // Hotel only : readymade package case only
                                    $tempCategory[$valueCat['Type']]['price'] = $this->getPriceFromMultiDatewise($valueCat['PriceAdditional']);
                                }
                            }
                        }
                    }
                    $priceArrJsonInner[$v['TourTypeTitle'][0]] = $tempCategory;
                }

                $this->createJsonFile($tempCategory, 'ra.json'); // remove this line
            }
        }

        $priceArrJson = $priceArrJsonInner; // assign the inner created to outer loop variable
        return $priceArrJson;
    }

    function getMpTypeByCategory(array $categoryArray = null, $categoryid) {
        if (isset($categoryArray[$categoryid]['mptype'][0]) && ($categoryArray[$categoryid]['mptype'][0] != NULL))
            return reset($categoryArray[$categoryid]['mptype'][0]);
        else
            return [];
    }

    function getCategoryAndPriceArrayJSON(array $tourType = null, $market, $PackageType = null, $PackageSubType = null) {

        $defaultCategoryId = $priceArrJson = $defaultTourType = '';

        foreach ($tourType as $tourKey => $tourVal) {

            $priceArrJsonInner1 = [];

            // check the market type is b2b or b2c
            if ($tourVal['MarketTypeTitle'] === $market) {

                $priceArrJsonInner = $categoryArray = $tourtypeArray = [];
                foreach ($tourVal['TourType'] as $k => $v) {

                    $category = $v['Categories']['Category'];

                    if (is_array($category) && count($category)) {

                        $tempCategory = [];
                        $MPType = '';
                        //echo "<pre>";print_r($category);die;
                        foreach ($category as $keyCat => $valueCat) {
                            //                              echo $valueCat['Type'] = $keyCat.'SSSS'; // this is temporary code need to delete this line of code
                            // if dynamic package
                            if (($PackageType) && ($PackageType == $this->packageTypeStatic)) {
                                $MPTypeArray = [];
                                foreach ($valueCat['MPType'] as $valueMP) {
                                    if (isset($valueMP['SeletedForPackage']) && !empty($valueMP['SeletedForPackage'])) {
                                        $MPType = $valueMP['MPTypeText'];
                                    }
                                    if ($valueMP['MPTypeText'] != "LowestCost") {

                                        $MPTypeArray[$valueMP['MPTypeId']] = [
                                            'id' => $valueMP['MPTypeId'],
                                            'txt' => $valueMP['MPTypeText'],
                                            'sfp' => $valueMP['SeletedForPackage'],
                                            'price' => $valueMP['PriceAdditional'],
                                        ];
                                    }
                                }
                            }

                            $tempCategory[$valueCat['CategoryId']] = [
                                'CategoryTitle' => $valueCat['Type'],
                                'TPId' => $valueCat['TPSysId'],
                                'SFP' => $valueCat['SeletedForPackage'],
                                //                                    'price'=> $valueCat['PriceAdditional'] // this was old pattern
                                'price' => $valueCat['MPType'][0]['PriceAdditional'],
                                'GroupSize' => $valueCat['GroupSize'],
                            ];

                            // if meal plan type array has value
                            if (isset($MPTypeArray) && count($MPTypeArray)) {
                                $tempCategory[$valueCat['CategoryId']]['mptype'] = $MPTypeArray;
                            }
                        }
                    }
                    $priceArrJsonInner[$v['TourTypeTitle'][0]] = $tempCategory;
                }
                $priceArrJsonInner1 = $priceArrJsonInner;
            }
        }
        $priceArrJson = isset($priceArrJsonInner) ? $priceArrJsonInner : array(); // assign the inner created to outer loop variable

        return [
            "priceArrJson" => $priceArrJson,
        ];
    }

    public function getTourType(array $tourType, array $tourTypeArrayOfIds, $type = 'RADIO_BUTTON') {

        if ($type === 'RADIO_BUTTON') {
            $tempActive = $active = '';
            foreach ($tourType as $ky => $valu) {

                if (in_array($valu['TourType'], $tourTypeArrayOfIds)) {
                    //                if( in_array( $valu['TourType'] , $tourTypeArrayOfIds) && !($active)){
                    $active = true;
                    $tempActive = 1;
                    $defaultTourType = $valu['TourType'];
                } else {
                    $active = false;
                }

                $tourTypeRadio[] = ['TourType' => $valu['TourType'], 'TourTypeTitle' => $valu['TourTypeTitle'], 'active' => $active];
            }

            return [
                "defaultTourType" => 1, // $defaultTourType
                "tourTypeRadio" => $tourTypeRadio,
            ];
        }
    }

    public function getTourTypeV2(array $tourType, array $tourTypeArrayOfIds, $type = 'RADIO_BUTTON') {

        if ($type === 'RADIO_BUTTON') {
            $tempActive = $active = $defaultTourType = '';
            foreach ($tourType as $ky => $valu) {

                if (in_array($valu['TourType'], $tourTypeArrayOfIds)) {
                    //                if( in_array( $valu['TourType'] , $tourTypeArrayOfIds) && !($active)){
                    $active = true;
                    $tempActive = 1;

                    if ($defaultTourType == '') {
                        $defaultTourType = $valu['TourType'];
                    }
                    $tourTypeRadio[] = ['TourType' => $valu['TourType'], 'TourTypeTitle' => $valu['TourTypeTitle'], 'active' => $active];
                }
            }
            //echo $defaultTourType;

            return [
                "defaultTourType" => $defaultTourType, // $defaultTourType // defalut tour type
                "tourTypeRadio" => $tourTypeRadio,
            ];
        }
    }

    public function getPackageCardDetails(array $relatedPackages) {
        $relatedPackagesArray = [];

        if (isset($relatedPackages)) {

            foreach ($relatedPackages as $key => $value) {

                if ($value['LongJsonInfo']) {
                    $LongJsonInfo = Zend_Json::decode($value['LongJsonInfo']);
                }

                $categoryDetails = $this->getCategoryAndPriceArray($LongJsonInfo['package']['TourTypes']['MarketType'], 'B2B', $value['PackageType'], $value['PackageSubType']); // get default category

                $defaultCategoryId = $categoryDetails['defaultCategoryId'];
                $defaultCategory = $categoryDetails['defaultCategory'];
                $defaultTourType = $categoryDetails['defaultTourType'];
                $TPId = $categoryDetails['TPId'];
                $MPType = (!empty($categoryDetails['MPType']) && ($categoryDetails['MPType'] != 'LowestCost')) ? array_search($categoryDetails['MPType'], unserialize(CONST_MEAL_PLAN_ARR)) : 0;

                $tourTypeChar = $this->getTourTypeChar($defaultTourType); // if private than P else G for Group tour type
                $priceArrJson = $categoryDetails['priceArrJson'];

                $displayFinalPrice = $this->getPackagePriceV2($defaultCategory, $tourTypeChar, $priceArrJson, true);  // Param 4: true ( if calculate discounted price )
                $displayFinalPriceDisc = $this->getPackagePriceV2($defaultCategory, $tourTypeChar, $priceArrJson); // get with discount included

                $relatedPackagesArray[] = [
                    'name' => $this->trimContent($LongJsonInfo['package']['Name'], 18),
                    'nameF' => $LongJsonInfo['package']['Name'], // full name of package name
                    'img' => ($value['Image']) ? $value['Image'] : $this->getImageFromJson('ImgThumbnail', $LongJsonInfo['package']),
                    'night' => $value['Nights'],
                    'price' => $this->moneyFormatINR($displayFinalPrice),
                    'priceDisc' => $this->moneyFormatINR($displayFinalPriceDisc),
                    'star' => $value['StarRating'],
                    'Destination' => $value['Destinations'],
                    'PkgSysId' => $value['PkgSysId'],
                    'GTXPkgId' => $value['GTXPkgId'],
                    'tourtype' => $defaultTourType,
                    'PackageType' => $value['PackageType'],
                    'TPId' => ($value['PackageType'] == $this->packageTypeStatic) ? $value['GTXPkgId'] : $TPId, // if dynamic package then tpid is same for all
                    'HotDeal' => $value['HotDeal'],
                    'defaultCategoryId' => $defaultCategoryId,
                    'defaultCategory' => $defaultCategory,
                    'mp' => $MPType,
                ];
            }
        }
        return $relatedPackagesArray;
    }

    public function getImageFromJson($keyname, array $json) {

        if (array_key_exists($keyname, $json)) {
            return $json[$keyname];
        }
        return null;
    }

    // incomplete function     
    public function deleteJsonFile($filename, $path) {

        if (empty($filename)) {
            throw new Exception("Unable to delete file, please give file name to function : " . __FUNCTION__);
            return;
        } else {
            file_put_contents($folder . $filename, Zend_Json::encode($dataArray));
        }
    }

    public function createJsonFile(array $dataArray, $filename, $path = false) {

        $folder = ($path) ? $path : "public/upload/" . $this->gtxagencysysid . "/data/";

        if (!is_array($dataArray)) {
            throw new Exception("Unable to create array, please give price array as [ parameter 1 ] to " . __FUNCTION__);
            return;
        } else {
            file_put_contents($folder . $filename, Zend_Json::encode($dataArray));
        }
    }

    public function createPriceJson(array $myPriceArray) {
        if (!is_array($myPriceArray)) {
            throw new Exception("Unable to create array, please give price array as [ parameter 1 ] to " . __FUNCTION__);
            return;
        } else {
            file_put_contents('public/data/package_price.json', Zend_Json::encode($myPriceArray));
        }
    }

    public function getPackagePriceV2($defaultCategory, $tourTypeChar, array $priceArray, $discounted = false) {
        $objHelperGeneral = Zend_Controller_Action_HelperBroker::getStaticHelper('General');
        $PriceResultArr = $priceArray[$tourTypeChar][$defaultCategory]['price'][0];
        $PricePerPerson = (float) $PriceResultArr['PricePerPerson'];
        //        if($priceArray[$tourTypeChar][$defaultCategory]['TPId'] == 37058){
        //        }
        // discounted true means lesser amount | discount excluded in amount 
        if ($discounted) {
            $finalp = $PricePerPerson;
        } else {
            $discountValue = 0;

            if ($PriceResultArr['DiscountType'] === 1) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else if ($PriceResultArr['DiscountType'] === 2) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else {
                $discountValue = 0;
            }

            $finalp = $PricePerPerson + $discountValue;
        }

        return $finalp;
    }

    public function getPackagePriceV3($defaultCategory, $tourTypeChar, array $priceArray = null, $mptype, $discounted = false) {
        
        if ($mptype) {
            $PriceResultArr = $priceArray[$tourTypeChar][$defaultCategory]['mptype'][$mptype]['price'][0];
        } else {
            $PriceResultArr = $priceArray[$tourTypeChar][$defaultCategory]['price'][0];
        }

        // discounted true means lesser amount | discount excluded in amount 
        if ($discounted) {
            $finalp = (float) $PriceResultArr['PricePerPerson'];
        } else {
            $discountValue = 0;

            if ($PriceResultArr['DiscountType'] === 1) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else if ($PriceResultArr['DiscountType'] === 2) {
                $discountValue = (float) $PriceResultArr['DiscountVal'];
            } else {
                $discountValue = 0;
            }

            $finalp = (float) $PriceResultArr['PricePerPerson'] + $discountValue;
        }

        return $finalp;
    }

    // prepare the json for front end as per need for listing page
    public function customiseForJsonSendquery(array $resultset) {
        error_reporting(0);

        $result = $myCategoryArray = $hotelStandardArr = [];
        $temp = $shortJSON = $longJSON = '';

        $resultval = $resultset;

        // get package type array from json string
        //            $shortJSON  = Zend_Json::decode($resultval['ShortJsonInfo'], true);
        $longJSON = Zend_Json::decode($resultval['LongJsonInfo'], true);
        //                                die('herere');

        $temp['package'] = $longJSON['package']; // get package type array
        $temp['packageTypeArr'] = $longJSON['package']['PackageType']; // get package type array

        $temp['hotelTypeArr'] = $longJSON['package']['TourTypes']['TourType'][0]['Categories']['Category'];   // get package Category
        $temp['cityArr'] = $longJSON['package']['Cities']['City'];   // get cities included in package
        $temp['inclusionsArr'] = $longJSON['package']['Inclusions']; // get inclusions of package

        $temp['tourType'] = $longJSON['package']['TourTypes']['TourType']; // get package validity
        //            $temp['Validity']           = $longJSON['package']['Validity']; // get package validity
        $temp['itineraryArr'] = $longJSON['package']['Itineraries']['Itinerary']; // get Itineraries 


        $package_hotelcategoryid = $resultval['package_hotelcategoryid'];

        if ($package_hotelcategoryid) {
            
            foreach ($temp['hotelTypeArr'] as $keyHS => $valueHS) {

                if ($valueHS['CategoryId'] === $package_hotelcategoryid) {
                    $hotelStandardArr[$package_hotelcategoryid] = $valueHS['Type'];
                }
            }
        } else {
            foreach ($temp['hotelTypeArr'] as $keyHS => $valueHS) {
                $hotelStandardArr[$valueHS['CategoryId']] = $valueHS['Type'];
            }
        }
        $this->hotelTypeArr = $hotelStandardArr; // get hotel standard value dynamic
        //            $resultval['package_hotelcategoryid']
        //            echo count($hotelStandardArr);
        //  start : prepare the array for itineray

        $itineraryArr = $temp['itineraryArr'];
        $count_Itinerary = count($itineraryArr);

        $itineraryArrCustom = $hotelTypeArr = $hotelsArr = $ActivityItineraryArr = $ActivityITINERARY_ITEM_Result = [];
        $SightSeeingItineraryArr = $SightSeeingITINERARY_ITEM_Result = [];

        $cityITINERARY = $cityITINERARYTitle = $hotelsInCity = '';
        $ActivityITINERARY = $ActivityITINERARY_ITEM = $ActivityITINERARY_Result = $ActItiArray = '';
        $SightSeeingITINERARY = $SightSeeingITINERARY_ITEM = $SightSeeingITINERARY_Result = $SSItiArray = '';

        for ($i = 0; $i < $count_Itinerary; $i++) {

            $cityITINERARY = $this->filterArrayByValueKeyPair(['Type', 'CITY'], $itineraryArr[$i]['ItineraryItem']);

            $cityITINERARYTitle = $this->filterArrayByValueKeyPair(['CityId', $cityITINERARY[0]['Id']], $temp['cityArr']);

            $HotelITINERARY = $this->filterArrayByValueKeyPair(['Type', 'HOTEL'], $itineraryArr[$i]['ItineraryItem']);

            $ActivityITINERARY = $this->filterArrayByValueKeyPair(['Type', 'ACTIVITY'], $itineraryArr[$i]['ItineraryItem']);

            $SightSeeingITINERARY = $this->filterArrayByValueKeyPair(['Type', 'SIGHTSEEING'], $itineraryArr[$i]['ItineraryItem']);

            // filter the days Itinerary on the basis of hotel || hotel must be in last day of repeated day
            if (($HotelITINERARY[0]['Type']) == 'HOTEL') {


                $HotelITINERARY_ITEM = $hotelsInCity = $hotelsArrInner = $hotelPriceResultArr = $HotelITINERARY_ITEM_Result = [];
                $hotelDetailsResult = $hotelID = $hotelName = $hotelStar = $hotelTARating = $hotelPrice = $hotelPriceAdditional = $hotelIncluded = '';

                foreach ($this->hotelTypeArr as $hotelTypeKey => $hotelTypeValue) {

                    // fetch hotel ids only
                    $HotelITINERARY_ITEM = $this->filterArrayByValueKeyPair(['Type', ($hotelTypeValue)], $HotelITINERARY[0]['Items']);

                    // fetch which hotel is included true / false
                    if (count($HotelITINERARY_ITEM[0]['Item'])) {
                        $HotelITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                    }

                    $hotelIncluded = ($hotelID) ? $HotelITINERARY_ITEM_Result[0]['IsIncluded'] : false;

                    if (count($hotelsInCity)) {
                        $hotelDetailsResult = $this->filterArrayByValueKeyPair(['RefHotelId', $hotelID], $hotelsInCity); // fetch hotel details
                    }
                    $hotelName = ($hotelDetailsResult[0]['Name']) ? $hotelDetailsResult[0]['Name'] : '-';

                    $hotelsArrInner[$hotelTypeKey] = [
                        //                                'TPSysId' => $TPSysId,
                        'hotelID' => $hotelID,
                        'hotelName' => $hotelName,
                        'hotelIncluded' => $hotelIncluded,
                    ];
                }
                $ItineraryId = $this->getValueByKeyFromArray('ItineraryId', $itineraryArr[$i]);

                $itineraryArrCustom[$ItineraryId] = [
                    'hotel' => $hotelsArrInner,
                ];
            }


            // get acitivities of the days Itinerary
            if ($ActivityITINERARY[0]['Type'] === 'ACTIVITY') {


                // fetch which hotel is included true / false
                if (count($ActivityITINERARY[0]['Items'])) {

                    $ActItiArray = $ActivityITINERARY[0]['Items'][0]['Item']; // get single day activities list
                    // if result go to fetch Activity Ids
                    if (count($ActItiArray)) {

                        // note : multi array result may be multi for single day
                        $ActivityITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $ActItiArray);
                        // if has results than create array
                        if (is_array($ActivityITINERARY_ITEM_Result)) {

                            $ActivityItineraryArrTemp = $ActivityItineraryArrResultsTemp = $ActivityItineraryArr = [];
                            foreach ($ActivityITINERARY_ITEM_Result as $keyAct => $valueAct) {

                                $activitiesInCity = $cityITINERARYTitle[0]['Activities']['Activity']; // get all activities in city

                                $ActivityItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefActivityId', $valueAct['Id']], $activitiesInCity)[0];
                                $ActivityItineraryArrTemp[] = ['RefActivityId' => $ActivityItineraryArrResultsTemp['RefActivityId'], 'Title' => $ActivityItineraryArrResultsTemp['Title']];
                            }
                            $ActivityItineraryArr = $ActivityItineraryArrTemp;
                        }
                    }
                    // else part of : result go to fetch Activity Ids (define array as blank)
                    else {
                        $ActivityItineraryArr = [];
                    }
                }
                $itineraryArrCustom[$ItineraryId]['activity'] = $ActivityItineraryArr;
            }


            // get sightseeing of the days Itinerary
            if ($SightSeeingITINERARY[0]['Type'] === 'SIGHTSEEING') {


                // fetch which hotel is included true / false
                if (count($SightSeeingITINERARY[0]['Items'])) {

                    $SSItiArray = $SightSeeingITINERARY[0]['Items'][0]['Item']; // get single day sightsing list
                    // if result go to fetch Activity Ids
                    if (count($SSItiArray)) {

                        // note : multi array result may be multi for single day
                        $SightSeeingITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $SSItiArray);

                        // if has results than create array
                        if (is_array($SightSeeingITINERARY_ITEM_Result)) {

                            $SightSeeingItineraryArrTemp = $SightSeeingItineraryArrResultsTemp = $SightSeeingItineraryArr = [];
                            foreach ($SightSeeingITINERARY_ITEM_Result as $keySS => $valueSS) {

                                $sightseeingInCity = $cityITINERARYTitle[0]['SightSeeings']['SightSeeing']; // get all SightSeeing in city

                                $SightSeeingItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefSSId', $valueSS['Id']], $sightseeingInCity)[0];
                                $SightSeeingItineraryArrTemp[] = ['RefSSId' => $SightSeeingItineraryArrResultsTemp['RefSSId'], 'Title' => $SightSeeingItineraryArrResultsTemp['Title']];
                            }
                            $SightSeeingItineraryArr = $SightSeeingItineraryArrTemp;
                        }
                    }
                    // else part of : result go to fetch Activity Ids (define array as blank)
                    else {
                        $SightSeeingItineraryArr = [];
                    }
                }
                $itineraryArrCustom[$ItineraryId]['sightSeeing'] = $SightSeeingItineraryArr;
            }


            // prepare the hotel type
            if ($temp['hotelTypeArr'][$i]['Type'] != null) {
                $hotelTypeArr[] = [
                    'type' => $temp['hotelTypeArr'][$i]['Type']
                ];
            }

            $priceArr[] = $hotelPrice;
        } // outer for loop ends here
        //  end : prepare the array for itineray
        // start : tour type + hotel type price calculations
        $tourType = $this->tourTypeArr;

        $tempArray = [];
        for ($a = 0; $a < count($tourType); $a++) {
            //                $tourType[] = [ 'TourType' => $temp['tourType'][$a]['TourType'] , 'TourTypeTitle' => $temp['tourType'][$a]['TourTypeTitle'] ];
            $tourType[$a]['active'] = (isset($temp['tourType'][$a]['TourType'])) ? true : false;
        }
        // end : tour type + hotel type price calculations
        // start : code for getting price in all category and tour type
        // 
        $priceArrJson = [];
        $category = '';
        foreach ($temp['tourType'] as $tourKey => $tourVal) {
            $category = $tourVal['Categories']['Category'];
            if (is_array($category) && count($category)) {
                $tempCategory = [];
                foreach ($category as $keyCat => $valueCat) {
                    $tempCategory[$valueCat['Type']] = ['price' => $valueCat['PriceAdditional']];
                }
            }
            $priceArrJson[$tourVal['TourTypeTitle'][0]] = $tempCategory;
        }
        $result = [
            //'package_hotelcategoryid' => $resultval['package_hotelcategoryid'],
            'MinPax' => $resultval['MinPax'],
            'IsFixPriceCalculate' => $longJSON['package']['IsFixPriceCalculate'],
            'Nights' => $resultval['Nights'],
            'status' => $resultval['status'],
            'Destinations' => $resultval['Destinations'],
            'DestinationID' => $resultval['DestinationsId'],
            'PriceRange' => $resultval['MinPrice'] . '-' . $resultval['MaxPrice'],
            'hotelTypeArr' => $this->array_filter_rv($hotelTypeArr), // custom field
            'package' => ['Name' => trim(str_replace('/', ' ', $temp['package']['Name'])), 'Tagline1' => trim($temp['package']['Tagline1'])], // custom field
            'itineraryArr' => $itineraryArrCustom, // custom field
                //'tourtype' => $defaultTourtype, // custom field
        ];

        return Zend_Json::encode($result);
    }

    // prepare the json for front end as per need for listing page
    public function customiseForJsonSendqueryV2(array $resultval, $market = 'B2B', $package_hotelcategoryid = 0, $package_mealplantype = 0) {
        // error_reporting(E_ALL);

        $result = $myCategoryArray = $hotelStandardArr = $tourTypeArray = [];
        $shortJSON = $longJSON = $PackageCategoryStr = $PackageDestinationStr = '';
        $temp = array();

        $PackageType = $PackageSubType = $tourTypeRadio = $categoryDetails = $destinationTitleCustomFinalStr = $MPType = '';
        $priceArrJson = $tourTypeArrayOfIds = $destinationNightCountsArray = $destinationTitleCustomArray = [];

        $longJSON = Zend_Json::decode($resultval['LongJsonInfo'], true);
        $PackageType = $resultval['PackageType'];
        $PackageSubType = $resultval['PackageSubType'];

        if ($longJSON != "error") {

            $temp['package'] = $longJSON['package']; // get package type array
            $temp['packageTypeArr'] = $longJSON['package']['PackageType']; // get package type array
            $temp['cityArr'] = $longJSON['package']['Cities']['City'];   // get cities included in package

            $temp['tourType'] = $longJSON['package']['TourTypes']['MarketType']; // get package validity
            $temp['itineraryArr'] = $longJSON['package']['Itineraries']['Itinerary']; // get Itineraries 
            $temp['Transfers'] = $longJSON['package']['Transfers']; // get package transfers
            $temp['OtherServices'] = $longJSON['package']['OtherServices']; // get package other services if available

            $hotelStandardArr = [];

            // start : code for getting price in all category and tour type
            //

            $category = $TPId = '';

            /* get default category 
             * hotel standard array
             * Tour type defualt
             */

            $categoryDetails = $this->getCategoryAndPriceArray($temp['tourType'], $market, $PackageType, $PackageSubType);

            $TPId = ($resultval['PackageType'] == 2) ? $longJSON['package']['TPId'] : $categoryDetails['TPId']; // get tpid all same for dynamic package

            $defaultCategoryId = $categoryDetails['defaultCategoryId'];
            $defaultCategory = $categoryDetails['defaultCategory'];
            $defaultTourType = $categoryDetails['defaultTourType'];

            $hotelStandardArr = $categoryDetails['hotelStandardArr'];
            $tourTypeArrayOfIds = $categoryDetails['tourTypeArrayOfIds'];
            $priceArrJson = $categoryDetails['priceArrJson'];

            //            $MPType = (!empty($categoryDetails['MPType']) && ($categoryDetails['MPType']!='LowestCost')) ? array_search($categoryDetails['MPType'], unserialize(CONST_MEAL_PLAN_ARR)) : 0;

            $MPType = ($package_mealplantype) ? $package_mealplantype : '0';
            $this->hotelTypeArr = $hotelStandardArr; // get hotel standard value dynamic

            $tourType = $this->tourTypeArr; // static value private and group
            //  start : prepare the array for itineray

            $itineraryArr = $temp['itineraryArr'];
            $count_Itinerary = count($itineraryArr);

            $itineraryArrCustom = $hotelTypeArr = $hotelsArr = $ActivityItineraryArr = $ActivityITINERARY_ITEM_Result = [];

            $cityITINERARY = $cityITINERARYTitle = $hotelsInCity = $destinationTitleCustomStr = '';
            $SightSeeingITINERARY = $SightSeeingITINERARY_ITEM = $SightSeeingITINERARY_Result = $SSItiArray = '';

            $destinationTitleCustomArray1 = [];
            for ($i = 0; $i < $count_Itinerary; $i++) {

                $cityITINERARY = $this->filterArrayByValueKeyPair(['Type', 'CITY'], $itineraryArr[$i]['ItineraryItem']);

                $cityITINERARYTitle = $this->filterArrayByValueKeyPair(['CityId', $cityITINERARY[0]['Id']], $temp['cityArr']);

                $HotelITINERARY = $this->filterArrayByValueKeyPair(['Type', 'HOTEL'], $itineraryArr[$i]['ItineraryItem']);

                $ActivityITINERARY = $this->filterArrayByValueKeyPair(['Type', 'ACTIVITY'], $itineraryArr[$i]['ItineraryItem']);

                $SightSeeingITINERARY = $this->filterArrayByValueKeyPair(['Type', 'SIGHTSEEING'], $itineraryArr[$i]['ItineraryItem']);

                // filter the days Itinerary on the basis of hotel || hotel must be in last day of repeated day
                if (($HotelITINERARY[0]['Type']) == 'HOTEL') {

                    $HotelITINERARY_ITEM = $hotelsInCity = $hotelsArrInner = $hotelPriceResultArr = $HotelITINERARY_ITEM_Result = [];
                    $hotelDetailsResult = $hotelID = $hotelName = $hotelStar = $hotelTARating = $hotelPrice = $hotelPriceAdditional = $hotelIncluded = '';

                    foreach ($this->hotelTypeArr as $hotelTypeKey => $hotelTypeValue) {

                        if ($package_hotelcategoryid == $hotelTypeKey) {
                            // fetch hotel ids only
                            $HotelITINERARY_ITEM = $this->filterArrayByValueKeyPair(['Type', ($hotelTypeValue)], $HotelITINERARY[0]['Items']);

                            // fetch which hotel is included true / false
                            if (!empty($HotelITINERARY_ITEM[0]['Item']) && count($HotelITINERARY_ITEM[0]['Item'])) {
                                $HotelITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', true], $HotelITINERARY_ITEM[0]['Item']);
                            }

                            // filter the data because here are multy true condition in all type of meal plan 
                            if (($MPType)) {
                                $HotelITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['MealPlanId', $MPType], $HotelITINERARY_ITEM_Result);
                            }



                            $hotelID = ($HotelITINERARY_ITEM_Result) ? $HotelITINERARY_ITEM_Result[0]['Id'] : 0;
                            $MealPlanId = isset($HotelITINERARY_ITEM_Result[0]['MealPlanId']) ? $HotelITINERARY_ITEM_Result[0]['MealPlanId'] : $HotelITINERARY_ITEM_Result[0]['MealPlanId'] = '';
                            $hotelIncluded = ($hotelID) ? $HotelITINERARY_ITEM_Result[0]['IsIncluded'] : 0;

                            //echo $hotelID ."# ";
                            //echo $MealPlanId , $MPType;
                            if ($hotelID) {
                                if (($MPType) && ($MealPlanId == $MPType)) {
                                    $hotelsArrInner[$hotelTypeKey] = ['itemid' => $hotelID, 'MealPlanId' => $MealPlanId, 'IsIncluded' => $hotelIncluded];
                                } else {
                                    $hotelsArrInner[$hotelTypeKey] = ['itemid' => $hotelID, 'MealPlanId' => $MealPlanId, 'IsIncluded' => $hotelIncluded];
                                }
                            }
                        }
                    }
                    
                    $ItineraryId = $this->getValueByKeyFromArray('ItineraryId', $itineraryArr[$i]);

                    $itineraryArrCustom[$ItineraryId] = [
                        'hotel' => $hotelsArrInner,
                    ];
                }


                // get acitivities of the days Itinerary
                if ($ActivityITINERARY[0]['Type'] === 'ACTIVITY') {


                    // fetch which hotel is included true / false
                    if (count($ActivityITINERARY[0]['Items'])) {

                        $ActItiArray = $ActivityITINERARY[0]['Items'][0]['Item']; // get single day activities list
                        // if result go to fetch Activity Ids
                        if (count($ActItiArray)) {

                            // note : multi array result may be multi for single day
                            $ActivityITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $ActItiArray);
                            // if has results than create array
                            if (is_array($ActivityITINERARY_ITEM_Result)) {

                                $ActivityItineraryArrTemp = $ActivityItineraryArrResultsTemp = $ActivityItineraryArr = [];
                                foreach ($ActivityITINERARY_ITEM_Result as $keyAct => $valueAct) {

                                    $activitiesInCity = (isset($cityITINERARYTitle[0]['Activities']['Activity']) ? $cityITINERARYTitle[0]['Activities']['Activity'] : array()); // get all activities in city

                                    $ActivityItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefActivityId', $valueAct['Id']], $activitiesInCity)[0];
                                    $ActivityItineraryArrTemp[] = [
                                        'itemid' => $ActivityItineraryArrResultsTemp['RefActivityId'],
                                        //                                        'Title'=> $ActivityItineraryArrResultsTemp['Title'] ,
                                        'IsIncluded' => $valueAct['IsIncluded']
                                    ];
                                }

                                $ActivityItineraryArr = $ActivityItineraryArrTemp;
                            }
                        }
                        // else part of : result go to fetch Activity Ids (define array as blank)
                        else {
                            $ActivityItineraryArr = [];
                        }
                    }
                    $itineraryArrCustom[$ItineraryId]['activity'] = $ActivityItineraryArr;
                }


                // get sightseeing of the days Itinerary
                if ($SightSeeingITINERARY[0]['Type'] === 'SIGHTSEEING') {


                    // fetch which hotel is included true / false
                    if (count($SightSeeingITINERARY[0]['Items'])) {

                        $SSItiArray = $SightSeeingITINERARY[0]['Items'][0]['Item']; // get single day sightsing list
                        // if result go to fetch Activity Ids
                        if (count($SSItiArray)) {

                            // note : multi array result may be multi for single day
                            $SightSeeingITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $SSItiArray);

                            // if has results than create array
                            if (is_array($SightSeeingITINERARY_ITEM_Result)) {

                                $SightSeeingItineraryArrTemp = $SightSeeingItineraryArrResultsTemp = $SightSeeingItineraryArr = [];
                                foreach ($SightSeeingITINERARY_ITEM_Result as $keySS => $valueSS) {

                                    $sightseeingInCity = isset($cityITINERARYTitle[0]['SightSeeings']['SightSeeing']) ? $cityITINERARYTitle[0]['SightSeeings']['SightSeeing'] : array(); // get all SightSeeing in city

                                    $SightSeeingItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefSSId', $valueSS['Id']], $sightseeingInCity)[0];
                                    $SightSeeingItineraryArrTemp[] = [
                                        'itemid' => $SightSeeingItineraryArrResultsTemp['RefSSId'],
                                        //                                        'Title'=> $SightSeeingItineraryArrResultsTemp['Title'] ,
                                        'IsIncluded' => $valueSS['IsIncluded']
                                    ];
                                }
                                $SightSeeingItineraryArr = $SightSeeingItineraryArrTemp;
                            }
                        }
                        // else part of : result go to fetch Activity Ids (define array as blank)
                        else {
                            $SightSeeingItineraryArr = [];
                        }
                    }
                    $itineraryArrCustom[$ItineraryId]['sightSeeing'] = $SightSeeingItineraryArr;
                }

                // itinerary transfers is not in use right now (02 Nov 2017)
                // 
                // get sightseeing of the days Itinerary
                if ($SightSeeingITINERARY[0]['Type'] === 'TRANSFERS') {


                    // fetch which hotel is included true / false
                    if (count($SightSeeingITINERARY[0]['Items'])) {

                        $SSItiArray = $SightSeeingITINERARY[0]['Items'][0]['Item']; // get single day sightsing list
                        // if result go to fetch Activity Ids
                        if (count($SSItiArray)) {

                            // note : multi array result may be multi for single day
                            $SightSeeingITINERARY_ITEM_Result = $this->filterArrayByValueKeyPair(['IsIncluded', 1], $SSItiArray);

                            // if has results than create array
                            if (is_array($SightSeeingITINERARY_ITEM_Result)) {

                                $SightSeeingItineraryArrTemp = $SightSeeingItineraryArrResultsTemp = $SightSeeingItineraryArr = [];
                                foreach ($SightSeeingITINERARY_ITEM_Result as $keySS => $valueSS) {

                                    $sightseeingInCity = $cityITINERARYTitle[0]['SightSeeings']['SightSeeing']; // get all SightSeeing in city

                                    $SightSeeingItineraryArrResultsTemp = $this->filterArrayByValueKeyPair(['RefSSId', $valueSS['Id']], $sightseeingInCity)[0];
                                    $SightSeeingItineraryArrTemp[] = [
                                        'itemid' => $SightSeeingItineraryArrResultsTemp['RefSSId'],
                                        //                                        'Title'=> $SightSeeingItineraryArrResultsTemp['Title'] ,
                                        'IsIncluded' => $valueSS['IsIncluded']
                                    ];
                                }
                                $SightSeeingItineraryArr = $SightSeeingItineraryArrTemp;
                            }
                        }
                        // else part of : result go to fetch Activity Ids (define array as blank)
                        else {
                            $SightSeeingItineraryArr = [];
                        }
                    }
                    $itineraryArrCustom[$ItineraryId]['sightSeeing'] = $SightSeeingItineraryArr;
                }


                // prepare the hotel type
                if ($temp['hotelTypeArr'][$i]['Type'] != null) {
                    $hotelTypeArr[] = [
                        'type' => $temp['hotelTypeArr'][$i]['Type']
                    ];
                }

                $priceArr[] = $hotelPrice;
            } // outer for loop ends here
           
            $itineraryArrCustom1['itineraries'] = $itineraryArrCustom;

            // collect transfers here in package
            if (isset($temp['Transfers']) && count($temp['Transfers'])) {
                $transfersOUTArr = [];
                foreach ($temp['Transfers'] as $key2 => $value2) {
                    $transfersOUTArr[] = ['itemid' => $value2['fixTransSysId'], 'IsIncluded' => $value2['isIncluded']];
                }
            }
            // collect other services here in package
            if (isset($temp['OtherServices']) && count($temp['OtherServices'])) {
                $servicesArr = [];
                foreach ($temp['OtherServices'] as $key2 => $value2) {
                    $servicesArr[] = ['itemid' => $value2['otherSrvSysId'], 'IsIncluded' => $value2['isCostInclInTP']];
                }
            }

            $itineraryArrCustom1['others'] = ['services' => $servicesArr, 'transfers' => $transfersOUTArr];  // append iteration array here for other services and transfers
        }


        $result = [
            //                'package_hotelcategoryid' => $resultval['package_hotelcategoryid'],
            'MinPax' => $resultval['MinPax'],
            'IsFixPriceCalculate' => $longJSON['package']['IsFixPriceCalculate'],
            'Nights' => $resultval['Nights'],
            'status' => $resultval['status'],
            'Destinations' => $resultval['Destinations'],
            'DestinationID' => $resultval['DestinationsId'],
            'PriceRange' => $resultval['MinPrice'] . '-' . $resultval['MaxPrice'],
            'hotelTypeArr' => $this->array_filter_rv($hotelTypeArr), // custom field
            'package' => ['Name' => trim(str_replace('/', ' ', $temp['package']['Name'])), 'Tagline1' => trim($temp['package']['Tagline1']), 'category' => Catabatic_Helper::getPackageType($package_hotelcategoryid)], // custom field
            'itineraryArr' => $itineraryArrCustom1, // custom field
            'fixedInventory' => $temp['package']['fixedInventory'], // custom field
            'AgencyIdB2C' => $temp['package']['AgencyIdB2C'],
            'AgencyIdB2B' => $temp['package']['AgencyIdB2B'],
                //'tourtype' => $defaultTourtype, // custom field
        ];

        return Zend_Json::encode($result);
    }

    /*
     * Function to get price after itenary change
     */

    public function prepareItineraryArrayForSendingQuery(array $array) {
        $tempArray = [];
        foreach ($array as $key => $value) {

            if ($key == 'itineraries') {
                $itiArr = [];
                foreach ($value as $key1 => $value1) {

                    // collect city here
                    if (isset($value1['city'])) {
                        $cityArr = [];
                        foreach ($value1['city'] as $key2 => $value2) {
                            $cityArr[] = $value2;
                        }
                    }
                    // collect hotels here
                    if (isset($value1['hotel'])) {
                        $hotelArr = [];
                        foreach ($value1['hotel'] as $key2 => $value2) {
                            if ($value2['IsIncluded']) {
                                $hotelArr[] = $value2;
                            }
                        }
                    }
                    //                     collect activity here
                    if (isset($value1['activity'])) {
                        $activityArr = [];
                        foreach ($value1['activity'] as $key2 => $value2) {
                            $activityArr[] = ['itemid' => $value2['itemid'], 'IsIncluded' => ((isset($value2['IsIncludedNew']) && $value2['IsIncludedNew']) ? $value2['IsIncludedNew'] : $value2['IsIncluded'])];
                        }
                    }
                    //                    // collect sightseeing here
                    if (isset($value1['sightSeeing'])) {
                        $sightSeeingArr = [];
                        foreach ($value1['sightSeeing'] as $key2 => $value2) {
                            $sightSeeingArr[] = ['itemid' => $value2['itemid'], 'IsIncluded' => ((isset($value2['IsIncludedNew']) && $value2['IsIncludedNew']) ? $value2['IsIncludedNew'] : $value2['IsIncluded'])];
                        }
                    }
                    //                    // collect sightseeing here
                    if (isset($value1['transfers'])) {
                        $transfersArr = [];
                        foreach ($value1['transfers'] as $key2 => $value2) {
                            $transfersArr[] = [
                                'itemid' => $value2['itemid'],
                                'RouteVechSysId' => $value2['RouteVechSysId'],
                                'RouteSysId' => $value2['RouteSysId'],
                                'VehSysId' => $value2['VehSysId'],
                                'VehicleTypeSysId' => $value2['VehicleTypeSysId'],
                                'TransType' => $value2['TransType'],
                                'FromPlace' => $value2['FromPlace'],
                                'ToPlace' => $value2['ToPlace'],
                                'Capacity' => $value2['Capacity'],
                                'VehName' => $value2['VehName'],
                                'SupplierSysId' => $value2['SupplierSysId'],
                                'Qty' => $value2['Qty'],
                                'SubCategory' => $value2['SubCategory'],
                                'TransportSubType' => $value2['TransportSubType'],
                            ];
                        }
                    }

                    $itiArr[$key1] = [
                        'day' => $value1['day'],
                        'city' => $cityArr,
                        'hotel' => $hotelArr,
                        'activity' => $activityArr,
                        'sightSeeing' => $sightSeeingArr,
                        'transfers' => $transfersArr,
                    ];
                }
                $tempArray[$key] = $itiArr;
            }

            if ($key == 'others') {
                // collect city here
                if (isset($array['others']['services'])) {
                    $servicesArr = [];
                    foreach ($array['others']['services'] as $key2 => $value2) {
                        $servicesArr[] = ['itemid' => $value2['itemid'], 'IsIncluded' => ((isset($value2['IsIncludedNew']) && $value2['IsIncludedNew']) ? $value2['IsIncludedNew'] : $value2['IsIncluded'])];
                    }
                }
                // collect city here
                if (isset($array['others']['transfers'])) {
                    $transfersOUTArr = [];
                    foreach ($array['others']['transfers'] as $key2 => $value2) {
                        $transfersOUTArr[] = $value2;
                    }
                }

                $tempArray['others'] = ['services' => $servicesArr, 'transfers' => $transfersOUTArr];
            }
        }

        return $tempArray;
    }

    public function trimContent($content, $limit) {
        return substr($content, 0, $limit) . (($limit < strlen($content)) ? "..." : "");
    }

    // arrry to find range by any value
    public function getRangeByValue($ratearray, $input) {
        foreach ($ratearray as $key => $value) {
            $keyex = explode('-', $value);
            if ($keyex[0] <= $input && $keyex[1] >= $input) {
                return $value;
            }
        }
    }

    public function count_values_2d_array(array $arr, $index) {

        $out = $out1 = [];
        foreach ($arr as $key => $value) {

            foreach ($value as $key2 => $value2) {
                if (array_key_exists($value2, $out)) {
                    $out[$value2] = $out[$value2] + 1;
                } else {
                    $out[$value2] = 1;
                }
            }
            //            $out[] = array_count_values($value);
            $out1[] = $out;
        }
        return $out;
    }

    public function update_json_footer_file($resultset, $footer_destination) {

        $mergeArray = ["social_links" => $resultset, "footer_destination" => $footer_destination];
        $this->createJsonFile($mergeArray, 'footer.json', "public/data/static/"); // create json file
    }

    public function getHours($min) {
        //        return gmdate("H:i", $min);
        $init = $min * 60; // seconds
        $hours = floor($init / 3600);
        $minutes = floor(($init / 60) % 60);
        $seconds = $init % 60;

        $minlen = strlen($minutes);
        $minutes = ($minlen == 1) ? '0' . $minutes : $minutes;

        $return = '';

        if ($hours) {
            $return .= "{$hours} Hours";
        }
        if ($minutes) {
            if ($hours && $minutes != '00') {
                $return .= " : ";
            }
            if ($minutes != '00') {
                $return .= "{$minutes} Minutes";
            }
        }

        return $return;
        ;
    }

    public function getDevice() {
        $mobile_detect = new Catabatic_MobileDetect();

        if ($mobile_detect->isMobile() == "mobile") {
            $deviceType = "mobile";
        } else if ($mobile_detect->isTablet() == "tablet") {
            $deviceType = "tablet";
        } else {
            $deviceType = "desktop";
        }
        return $deviceType;
    }

    /*
     * function is used to get price from multiple date wise price arry
     */

    public function getPriceFromMultiDatewise($priceArray) {
        //        return ['price' => $priceArray];
        return $priceArray;
    }

    /*
     * Get popup sessions for send enquiry
     */

    public function getMypopSess() {
        $this->myNamespace = new Zend_Session_Namespace('MypopSess'); // get user end infomations
        return $this->myNamespace->MypopSess;
    }

    /*
     * Params : config for to email, cc email, subject, body | type (package/hotel/activity)
     */

    public function sendEmail(array $configs, $type) {
        $fromName = $configs['fromName'];
        $emailId = $configs['to'];
        $emailIdcc = $configs['cc'];
        $mailSubject = $configs['subject'];
        $bodyText = $configs['body'];

        $mail = new Zend_Mail("iso-8859-1");
        $mail->addTo($emailId)
                //            ->addCc($emailIdcc)
                ->setSubject($mailSubject)
                ->setBodyHtml($bodyText)
                ->setFrom($emailId, $fromName);

        if (isset($configs['to']) && ($configs['to'] != '')) {
            $mail->addCc($emailIdcc);
        }

        $mail->addHeader('X-Priority', '1');
        $mail->addHeader('X-MSMail-Priority', 'High');
        $mail->addHeader('Importance', 'High');

        try {
            $issend = $mail->send(); //send mail
        } catch (Exception $err) {
            $err->getMessage();
            $issend = FALSE;
        }

        //            echo "<pre>";
        //            var_dump($issend);
    }

    public function sendEmailPackage(array $configs, $type) {
        $fromName = $configs['fromName'];
        $fromEmail = $configs['fromEmail'];
        $emailId = $configs['to'];
        $emailIdcc = $configs['cc'];
        $mailSubject = $configs['subject'];
        $bodyText = $configs['bodyHtml'];

        $mail = new Zend_Mail("iso-8859-1");
        $mail->addTo($emailId)
                //            ->addCc($emailIdcc)
                ->setSubject($mailSubject)
                ->setBodyHtml($bodyText)
                ->setFrom($fromEmail, $fromName);

        if (isset($configs['to']) && ($configs['to'] != '')) {
            $mail->addCc($emailIdcc);
        }

        $mail->addHeader('X-Priority', '1');
        $mail->addHeader('X-MSMail-Priority', 'High');
        $mail->addHeader('Importance', 'High');

        try {
            $issend = $mail->send(); //send mail
        } catch (Exception $err) {
            $err->getMessage();
            $issend = FALSE;
        }

        //            echo "<pre>";
        //            var_dump($issend);
    }

    public function mailSentByElastice($emailData, $arrEmailStatistics = array()) {
        $url = 'https://api.elasticemail.com/v2/email/send';
        try {
            $emailSenderKey = ELASTIKKEY;
            $post = array(
                'from' => $emailData['fromEmail'],
                'fromName' => $emailData['fromName'],
                'apikey' => $emailSenderKey,
                'subject' => $emailData['subject'],
                'to' => $emailData['to'],
                'bodyHtml' => $emailData['bodyHtml'],
                //'bodyText' => $emailData['bodyText'],
                'isTransactional' => true
            );

            $ch = curl_init();
            curl_setopt_array($ch, array(
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $post,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HEADER => false,
                CURLOPT_SSL_VERIFYPEER => false,
            ));

            $result = curl_exec($ch);

            curl_close($ch);
        } catch (Exception $ex) {

            $result = $ex->getMessage();
        }

        return $result;
    }

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

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

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

    public function footerOurPartner() {
        $this->objMdl = new Admin_Model_CRUD();
        $ourPartners = $this->objMdl->rv_select_all('tbl_ourpartner', ['*'], ['status' => 1], ['id' => 'ASC']);
        return $ourPartners;
    }

    public function deleteSearchJsonFile($path) {
        $now = time();
        if (is_dir($path)) {
            $files = scandir($path, 1);
            foreach ($files as $file) {
                if ($now - @filemtime($file) >= 60 * 60 * 24 * 1) {
                    unlink($path . "/" . $file);
                }
            }
        }
    }

    /// for flight some helpers

    public function getDateFormatFromDbDates($string) { // get date & time
        $arrFormatedDateTime = array();
        $arr = explode(" ", $string);
        if (count($arr) > 0) {
            $date = new DateTime($arr[0]);
            $strDate = $date->format('d M y');
            $strTime = @substr($arr[1], 0, 5);
            $arrFormatedDateTime = array(
                'strDate' => $strDate,
                'strTime' => $strTime
            );
        }

        return $arrFormatedDateTime;
    }

    public function getDateTimeFormatFromApiString($string) { // get date & time
        $arrFormatedDateTime = array();
        $arr = explode("T", $string);
        if (count($arr) > 0) {
            $date = new DateTime($arr[0]);
            $strDate = $date->format('d M y');
            $strTime = @substr($arr[1], 0, 5);
            $arrFormatedDateTime = array(
                'strDate' => $strDate,
                'strTime' => $strTime
            );
        }

        return $arrFormatedDateTime;
    }

    public function convertAmountToWords($number) {

        $hyphen = '-';
        $conjunction = ' and ';
        $separator = ', ';
        $negative = 'negative ';
        $decimal = ' point ';
        $dictionary = array(
            0 => 'zero',
            1 => 'one',
            2 => 'two',
            3 => 'three',
            4 => 'four',
            5 => 'five',
            6 => 'six',
            7 => 'seven',
            8 => 'eight',
            9 => 'nine',
            10 => 'ten',
            11 => 'eleven',
            12 => 'twelve',
            13 => 'thirteen',
            14 => 'fourteen',
            15 => 'fifteen',
            16 => 'sixteen',
            17 => 'seventeen',
            18 => 'eighteen',
            19 => 'nineteen',
            20 => 'twenty',
            30 => 'thirty',
            40 => 'fourty',
            50 => 'fifty',
            60 => 'sixty',
            70 => 'seventy',
            80 => 'eighty',
            90 => 'ninety',
            100 => 'hundred',
            1000 => 'thousand',
            1000000 => 'million',
            1000000000 => 'billion',
            1000000000000 => 'trillion',
            1000000000000000 => 'quadrillion',
            1000000000000000000 => 'quintillion'
        );

        if (!is_numeric($number)) {
            return false;
        }

        if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
            // overflow
            trigger_error(
                    'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
                    E_USER_WARNING
            );
            return false;
        }

        if ($number < 0) {
            return $negative . $this->convertAmountToWords(abs($number));
        }

        $string = $fraction = null;

        if (strpos($number, '.') !== false) {
            list($number, $fraction) = explode('.', $number);
        }

        switch (true) {
            case $number < 21:
                $string = $dictionary[$number];
                break;
            case $number < 100:
                $tens = ((int) ($number / 10)) * 10;
                $units = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    $string .= $hyphen . $dictionary[$units];
                }
                break;
            case $number < 1000:
                $hundreds = $number / 100;
                $remainder = $number % 100;
                $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
                if ($remainder) {
                    $string .= $conjunction . $this->convertAmountToWords($remainder);
                }
                break;
            default:
                $baseUnit = pow(1000, floor(log($number, 1000)));
                $numBaseUnits = (int) ($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = $this->convertAmountToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
                if ($remainder) {
                    $string .= $remainder < 100 ? $conjunction : $separator;
                    $string .= $this->convertAmountToWords($remainder);
                }
                break;
        }

        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal;
            $words = array();
            foreach (str_split((string) $fraction) as $number) {
                $words[] = $dictionary[$number];
            }
            $string .= implode(' ', $words);
        }

        return $string;
    }

    public function currencyExchangeRate($fromcurrency, $tocurrency, $MarkUpPersentage = 0, $AgencySysId = NULL) {
        
        $apiData = array(
            'AgencySysId' => ($AgencySysId > 0) ? $AgencySysId : $this->gtxagencysysid,
            'FCurrency' => $fromcurrency, 
            'TCurrency' =>  $tocurrency
        );
        $curl = curl_init("http://currency.hellogtx.com/getCurrencyAgencyWise.php");
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiData));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $curl_response = curl_exec($curl);
        curl_close($curl);

        $response = json_decode($curl_response, true);
        if(is_array($fromcurrency)){
            foreach($response as $key => $value){
                $returnVal[$value['FCurrencyType'].'-'.$value['TCurrencyType']] = $value['Rate'];
            } 
        }else{
            $returnVal = (isset($response[0]['Rate'])) ? (float)$response[0]['Rate'] : 1;
        }
        
        
        return $returnVal;
    }

    public function createApiCallLogs($strDestination, $data) {

        $strPath = $_SERVER["DOCUMENT_ROOT"] . "/public/logs/" . $strDestination;

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

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

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

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

            $curl_IV = curl_init(API_SUPPORT_CONTACT);
            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';
        }
    }

    public function getCurrencyData() {
        $this->objMdl = new Admin_Model_CRUD();
        $resullatest = $this->objMdl->rv_select_all('tbl_currency', ['*'], ['isActive' => 1], ['id' => 'ASC']);
        foreach ($resullatest as $key => $value) {
            $returnArray[$value['CurrencyId']] = $value['Title'];
        }
        return $returnArray;
    }

    public function createApiXMLLogs($strDestination, $data) {

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

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

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

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

    public function GetFullUrl() {
        $s = &$_SERVER;
        $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true : false;
        $sp = strtolower($s['SERVER_PROTOCOL']);
        $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
        $port = $s['SERVER_PORT'];
        $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
        $host = isset($s['HTTP_X_FORWARDED_HOST']) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
        $host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
        $uri = $protocol . '://' . $host . $s['REQUEST_URI'];
        $segments = explode('?', $uri, 2);
        $url = $segments[0];
        return $url;
    }

    public function CreateLogs($data) {
        $agencyData = new Zend_Session_Namespace('User');
        $agency_sys_id = $agencyData->data['AgencySysId'];
        if (!isset($agency_sys_id) && empty($agency_sys_id)) {
            $agency_sys_id = $data['AgencySysId'];
        }
        // $aConfig = $this->getInvokeArg('bootstrap')->getOptions();
        $aConfig = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
        $BootStrap = $aConfig['bootstrap'];

        $requests = $this->getRequest()->getParams();

        $data = [
            "user_id" => isset($data['user_id']) ? $data['user_id'] : 1,
            "agency_sys_id" => isset($agency_sys_id) ? $agency_sys_id : '',
            "application_name" => isset($BootStrap['siteName']) ? $BootStrap['siteName'] : $_SERVER['HTTP_HOST'],
            "site_url" => $this->GetFullUrl(),
            "module_name" => isset($requests['module']) ? ucfirst($requests['module']) : '',
            "controller_name" => isset($requests['controller']) ? ucfirst($requests['controller']) : '',
            "action_name" => isset($requests['action']) ? ucfirst($requests['action']) : '',
            "custom_error" => isset($data['custom_error']) ? $data['custom_error'] : '',
            "error" => isset($data['error']) ? $data['error'] : '',
            "ip_address" => $_SERVER['REMOTE_ADDR'],
            "text_udf" => isset($data['text_udf']) ? json_encode($data['text_udf']) : '', // Response
            "char_udf" => isset($data['char_udf']) ? json_encode($data['char_udf']) : '', // Request
            "udf1" => isset($data['udf1']) ? $data['udf1'] : '',
            "udf2" => isset($data['udf2']) ? $data['udf2'] : '',
            "udf5" => isset($data['udf5']) ? $data['udf5'] : '',
            "from_destination" => isset($data['from_destination']) ? $data['from_destination'] : '',
            "to_destination" => isset($data['to_destination']) ? $data['to_destination'] : '',
            "flight_type" => isset($data['flight_type']) ? $data['flight_type'] : '',
            "source" => isset($data['source']) ? $data['source'] : '',
            "Pax" => isset($data['Pax']) ? $data['Pax'] : '',
            "Supplier" => isset($data['Supplier']) ? $data['Supplier'] : '',
            "Airline" => isset($data['Airline']) ? $data['Airline'] : '',
            "status" => isset($data['status']) ? $data['status'] : 1, //
            "created_on" => date('Y-m-d H:i:s'),
            "updated_on" => date('Y-m-d'),
            "is_active" => isset($data['is_active']) ? $data['is_active'] : true, //,
            "is_mark_for_delete" => isset($data['is_mark_for_delete']) ? $data['is_mark_for_delete'] : false, //,
        ];

        $url = 'https://logs.hellogtx.com/api/v1/create-logs/';
        $data_stringh = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        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);
        return $response;
    }

    public function getAgencyMarkupData($MPType = 1, $AccomType = 1, $ItemSourceType = 0, $IsForCancellation = 0) {
        $this->objMdl = new Admin_Model_CRUD();
        $staticPage = $this->objMdl->rv_select_row('tb_mp_stdmarkup_accom', ['AgencySysId', 'MarkUpType', 'MarkUp', 'Currency'], ['MPType' => $MPType, 'AccomType' => $AccomType, 'ItemSourceType' => $ItemSourceType, 'IsForCancellation' => $IsForCancellation], ['AgencySysId' => 'ASC']);
        return $staticPage;
    }

    public function getSightseeingDetailsArray($LongJsonInfo) {

        $Cities = $LongJsonInfo['Cities']['City'];
        $SightseeingPriceArray = array();
        foreach ($Cities as $key => $value) {
            foreach ($value['SightSeeings']['SightSeeing'] as $key => $value) {
                $SightseeingPriceArray[$value['RefSSId']] = $value;
            }
        }
        $ItinerariesArray = array();
        foreach ($LongJsonInfo['Itineraries']['Itinerary'] as $intkey => $intvalue) {
            $ItineraryItem = $intvalue['ItineraryItem'][3]['Items'][0]['Item'];
            foreach ($ItineraryItem as $itemkey => $itemvalue) {
                $ItinerariesArray[$intvalue['Day']][] = $itemvalue;
            }
        }
        $return = array('SightseeingPriceArray' => $SightseeingPriceArray, 'ItinerariesArray' => $ItinerariesArray);
        return $return;
    }

    public function getPriceWithMarkupAndServiceTax($data, $MarkupType = 0, $Markup = 0) {
        $price = (float)$data['Price'];
        $markup = (float)$data['Markup'];
        $ItemSourceType = (int)$data['ItemSourceType'];
        $agencyMarkupValue = $agencyTax = 0;
        $getTaxSettingDetail = $_SESSION['User']['getTaxSettingDetail'];
        $B2bAgencyMarkup = $_SESSION['User']['B2bAgencyMarkup'];
        $getTaxSettingDetailPlanTypeWise =  $getB2bAgencyMarkupItemSourceTypeWise = array();
        foreach ($getTaxSettingDetail as $key => $value) {
            $getTaxSettingDetailPlanTypeWise[$value['PlanType']] = $value;
        }
        
        if(empty($MarkupType)){
            if($ItemSourceType > 0){
                foreach ($B2bAgencyMarkup as $mKey => $mValue) {
                    if($ItemSourceType == $mValue['ItemSourceType']){
                        $MarkupType = $mValue['MarkUpType'];
                        $Markup = $mValue['MarkUpValue'];
                    }  
                } 
            }else{
                $MarkupType = $_SESSION['User']['data']['MarkupType'];
                $Markup = $_SESSION['User']['data']['Markup'];
            }  
        }   
        //echo "<pre>";print_r($B2bAgencyMarkup);die;
        $agencyMarkupType = $MarkupType;
        $agencyMarkup = $Markup;
        if ($agencyMarkupType == 4) {
            $agencyMarkupValue = ((int) ($markup) * ((int) $agencyMarkup / 100));
        } else if ($agencyMarkupType == 3) {
            $agencyMarkupValue = ((int) ($price) * ((int) $agencyMarkup / 100));
        } else if ($agencyMarkupType == 2) {
            $agencyMarkupValue = ((int) ($price + $markup) * ((int) $agencyMarkup / 100));
        } else {
            $agencyMarkupValue = (int) $agencyMarkup;
        }
        $priceWithAgencyMarkup = $price + $markup + $agencyMarkupValue;
        $TaxPercentage = trim($getTaxSettingDetailPlanTypeWise[5]['TaxPercentage']);
        $TaxType = trim($getTaxSettingDetailPlanTypeWise[5]['TaxType']);
        if ($TaxType == 1) {
            $agencyTax = ((int) $priceWithAgencyMarkup * ((int) $TaxPercentage / 100));
        } else if ($TaxType == 2) {
            $agencyTax = ((int) $agencyMarkupValue * ((int) $TaxPercentage / 100));
        }

        return $priceWithAgencyMarkup + $agencyTax;
    }

    public function getMonths($FromDate, $ToDate) {

        $start_date = new DateTime($FromDate);
        $end_date = new DateTime($ToDate);

        $interval = DateInterval::createFromDateString('1 month');
        $period = new DatePeriod($start_date, $interval, $end_date);

        $months = array();
        foreach ($period as $dt) {
            $months[] = $dt->format('F');
        }
        if ($FromDate == $ToDate && empty($months)) {
            $months[] = $start_date->format('F');
        }
        return $months;
    }

    public function getNewworkPackageId($AgencySysId) {
        $url = $this->gtxwebserviceurl . 'agency/check-network-package';
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_POSTFIELDS => array('term' => 'kan'),
            CURLOPT_HTTPHEADER => array(
                'AgencySysId: ' . $AgencySysId,
                'Cookie: PHPSESSID=bqa7o5bdepfda87r32218qg1bj'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit