403Webshell
Server IP : 103.234.187.230  /  Your IP : 216.73.216.216
Web Server : Apache
System : Linux lserver42043-ind.megavelocity.net 3.10.0-1160.108.1.el7.x86_64 #1 SMP Thu Jan 25 16:17:31 UTC 2024 x86_64
User : apache ( 48)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/b2bzend/application/models/CRM/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/b2bzend/application/models/CRM/CustomerTravelPlan.php
<?php

/*
 * Catabatic Technology Pvt. Ltd.
 * File Name :TblCRMCustomer.php
 * File Description :Manage to Customer Operation
 * Created By : Shobhit Srivastav 
 * Created Date: 03-Aug-2016
 */

class Travel_Model_CRM_CustomerTravelPlan
{

    // use Zend\Filter\HtmlPurifier;

    protected $_dbObj;
    protected $_crmcustObj;
    public $strCondition = "";
    public $strOrder = "";
    public $isAdmin = false;
    public $strConditionExpired = "";
    public $_custtravelObjFullfillment;
    public $_custtravelObj;
    public $_crmcustomerObj;
    public $_crmagencyleadaccountObj;
    public $_agencycustomerObj;
    public $_custtravelaccomObj;
    public $_crmAccomObj;
    public $_crmcusttravelplanItenaryAccom;
    public $_crmcustomertravelItenary;
    public $_crmcustomertravelFixed;
    public $_crmcustomertravelItenaryEvents;
    public $_crmcustomertravelItenaryPlaces;
    public $_crmcustomertravelMarketPlaces;
    public $_crmcustomertravelPlanRate;
    public $_crmcustomertravelSightSeeing;
    public $_custtraveltermObj;
    public $_crmcustomertravelTerm;
    public $_customermemberObj;
    public $_otherserviceObj;
    public $_crmcustomerTravelOtherServicesObj;
    public $ReportingToSysId;
    public $_custquerytravelObj;
    public $_dbObjQ;

    public function __construct()
    {

        $this->_custtravelObjFullfillment = new Travel_Model_TblCustomerTravelPlanFullfillment();
        $this->_custtravelObj = new Travel_Model_TblCustomerTravelPlan();
        $this->_custquerytravelObj = new Travel_Model_TblCustomerTravelPlanQuery();
        $this->_crmcustomerObj = new Travel_Model_CRM_Customer();
        $this->_crmagencyleadaccountObj = new Travel_Model_CRM_AgencyLeadAccount();
        $this->_agencycustomerObj = new Travel_Model_CRM_AgencyCustomer();
        $this->_crmcusttravelplanItenaryAccom = new Travel_Model_CRM_CustomerTravelPlanAccom();
        $this->_customermemberObj = new Travel_Model_CRM_CustomerMember();
        $this->_crmcustomertravelItenary = new Travel_Model_CRM_CustomerTravelItenary();
        $this->_crmcustomertravelFixed = new Travel_Model_CRM_CustomerTravelPlanFixed();
        $this->_crmcustomertravelItenaryEvents = new Travel_Model_CRM_CustomerTravelItenaryEvents();
        $this->_crmcustomertravelItenaryPlaces = new Travel_Model_CRM_CustomerTravelItenaryPlaces();
        $this->_crmcustomertravelMarketPlaces = new Travel_Model_CRM_CustomerTravelItenaryMarketRate();
        $this->_crmcustomertravelPlanRate = new Travel_Model_CRM_CustomerTravelPackRate();
        $this->_crmcustomertravelSightSeeing = new Travel_Model_CRM_CustomerTravelItenarySightSeeing();
        $this->_crmcustomertravelTerm = new Travel_Model_CRM_CustomerTravelTerm();
        $this->_crmcustomerTravelOtherServicesObj = new Travel_Model_CRM_CustomerTravelOtherServices();
        $this->_dbObj = Zend_Db_Table::getDefaultAdapter();
        $this->_dbObjQ = Zend_Db_Table::getDefaultAdapter();
        // echo "<pre>";print_r($this->_dbObj);die('Hello Nitesh');
        //$this->_HtmlPurifier = new Zend_Filter_HtmlPurifier();
    }

    public function addCustomerTravelPlan(array $data)
    {
        try {
            $dbtable = new Zend_Db_Table("TB_Agency_Customer_TravelPlan");
            return $dbtable->insert($data);
        } catch (Zend_Exception $e) {
            return $e->getMessage();
        }
    }

    public function addCustomerTravelPlanQuery(array $data)
    {
        try {
            $dbtable = new Zend_Db_Table("TB_Agency_Customer_TravelPlan_Query");
            return $dbtable->insert($data);
        } catch (Zend_Exception $e) {
            return $e->getMessage();
        }
    }

    public function GetLeadList($CustomerSysId, $agencySysID, $leadId = null)
    {
        $travel = array('IsOnlySightseeingPkg','IsB2bProposal', 'B2BAgencySysId', 'CustomerRemark', 'TPSysId', 'StatusType', 'PackTypeMask', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Countries as countrySysId', 'Cities', 'CityIds', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details', 'PackSpecType', 'selectNationality', 'PKqueryType', 'EconomyMask', 'PriceRange', 'TPId', 'IsOperationalLead', 'OpsAgentSysId', 'ExpectedClosureDate', 'ExpectedValue', 'NoofNight');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName', 'UserSysId as currentOwnerSysId');
        $travel_air = array('TPIntSysId', 'AdultPax', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode', 'FlyingMinutes', 'TripType');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'RoomMemInfoJson', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId');
        $airport_code = array('AirportCode', 'AirportTitle');
        $city = array('Title as cityTitle', 'CityId');
        $arrLeadSource = array('tb7.Title as LeadSource');
        $arrMediumSource = array('tb8.CampaignName as LeadMedium');
        $arCampaignSource = array('tb9.CampaignName as LeadCampaign');
        $masterArrAirPort = array('AirportCode as masterAirportCode', 'AirportTitle as SourceAirportTitle');
        $masterArrDesAirPort = array('AirportTitle as DesctinationAirportTitle');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), $travel);
        //        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        //        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        //        $select->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb4.TPIntSysId", $travel_accom);
        //        $select->joinLeft(array('tb5' => "TB_Master_Airport"), "tb3.DestAirportCode = tb5.AirportCode", $airport_code);
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tbl.AgentSysId = tb6.UserSysId", $leadAgent_owner);
        $select->joinLeft(array('tb7' => "TB_Master_LeadSource"), "tb7.LeadSourceSysId = tbl.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb8' => "TB_Agency_Medium_Master"), "tb8.MediumSysId = tbl.MediumSysId", $arrMediumSource);
        $select->joinLeft(array('tb9' => "TB_Agency_Campaign_Master"), "tb9.CampSysId = tbl.CampaignSysId", $arCampaignSource);
        //$select->joinLeft(array('tb8' => "TB_Agency_Customer_TravelPlan_Mapping"), "tbl.TPSysId = tb8.TPSysId", array('ExpectedClosureDate', 'ExpectedValue'));
        $select->where("tbl.AgencySysId = $agencySysID OR tbl.AgencySysId IN (SELECT AgencySysId FROM TB_AGENCY AS AT1 WHERE AT1.MasterAgencySysId = $agencySysID AND AT1.AgencyType=2 AND AT1.IsActive = 1)");
        $select->where('tbl.CustomerSysId = ?', $CustomerSysId);
        //$select->Where('tbl.StatusType IN (?) ',array(1,2));
        $select->order("tbl.TPSysId DESC");
        $leadId ? $select->where('tbl.TPSysId = ?', $leadId) : '';
        $leadId ? $select->where('tbl.MasterTPSysId = ?', 0) : '';
        //echo $select; exit;
        $result = $this->_dbObj->fetchAll($select);
        //  echo "<pre>";print_r($result);die;
        return $result;
    }

    public function GetHotelProposal($leadId)
    {

        $travel = array('TPSysId', 'StatusType', 'PlanBookingId', 'PlanType', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);

        $select->where('tbl.MasterTPSysId = ?', $leadId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetHotelProposalWithHotelList($leadId)
    {

        $travel = array('TPSysId', 'StatusType', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);

        $select->where('tbl.MasterTPSysId = ?', $leadId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetFlightProposal($leadId)
    {

        $travel = array('TPSysId', 'StatusType', 'MasterTPSysId', 'PlanType', 'PlanBookingId', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'AdditionalReq', 'RoomInfoJson', 'UpdateDate', 'CurrencyType', 'Cities', 'SupplierSysId', 'ProposalEmailTo', 'AgentSysId', 'hasFollowUp', 'hasIteration', 'IsGTXNetwork', 'BookingConversionRate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_air = array('TPIntSysId', 'AdultPax', 'Cost', 'TotalCost', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode', 'XServiceTaxAmount', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'AgencyCommission');
        $airport_code = array('AirportCode', 'AirportTitle');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $Trans_API_Air = array('IsQuickProposal');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tbl.AgentSysId", array(new Zend_Db_Expr('tb5.FirstName as ownerName'), 'Designation'));
        $select->joinLeft(array('tb6' => "TB_IC_Trans_API_Air"), "tb3.InvnItemSysId = tb6.TBQAirInvenSysId", $Trans_API_Air);

        $select->where('tbl.MasterTPSysId = ?', $leadId);
        $select->where("tbl.IsActive = ?", 1);
        //$select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        //$select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->where('tbl.StatusType > ?', 3);
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function searchForInclusionId($id, $array, $pkey)
    {
        foreach ($array as $key => $val) {
            if ($key == $id) {
                $keyarr = $array[$id][$pkey];
            }
        }
        return $keyarr;
    }

    public function GetProposalCount($leadID)
    {
        $select = $this->_dbObj->select();
        $tpsysID = array('TPSysId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $tpsysID);
        $select->where('tbl.MasterTPSysId = ?', $leadID);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.CustomerSysId > ?', 0);
        $select->where('tbl.IsMarkForDel = ?', 0);
        //$select->where('tbl.StatusType > ?',3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllProposalList($leadID)
    {
        $select = $this->_dbObj->select();
        $tpsysID = array('TPSysId', 'MasterTPSysId', 'VersionId', 'Cities as hotelCityTitle', 'DestinationPlaces', 'StatusType', 'PlanBookingId', 'RoomInfoJson', 'PlanType', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'DiscountVal', 'SupplierSysId', 'AdditionalReq', 'UpdateDate', 'Readymade', 'PackSpecType', 'AgentSysId', 'hasFollowUp', 'hasIteration', 'selectNationality', 'IsGTXNetwork', 'IsHotelOnlyPackage');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'XrefBookingId', 'CurrencyType');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $tpsysID);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tbl.AgentSysId", array(new Zend_Db_Expr('tb5.FirstName as ownerName'), 'Designation'));
        $select->where('tbl.MasterTPSysId = ?', $leadID);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->where('tbl.StatusType > ?', 3);
        //$select->where('tbl.StatusType = ?', 4);
        $select->order("tbl.TPSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function UpdateCustomerTravelPlan(array $data, $where)
    {
        $this->_custtravelObj->update($data, $where);
    }

    public function UpdateCustomerTravelPlanQuery(array $data, $where)
    {
        $this->_custquerytravelObj->update($data, $where);
    }

    public function UpdateCustomerTravelPlanFullfillment(array $data, $where = NULL)
    {
        $this->_custtravelObjFullfillment->update($data, $where);
    }

    public function UpdatePriceRange(array $data, $where = NULL)
    {
        $this->_custtravelObj->update($data, $where);
    }

    public function CheckCustomerWithLeadId($leadId, $IdType = '')
    {
        $select = $this->_dbObj->select();
        if ($IdType == 'Query') {
            $travel = array('CustomerSysId', 'AgencySysId', 'AgentSysId', 'VersionId', 'MasterTPSysId', 'TPId', 'CreateDate', 'DownloadCount', 'StatusType', 'LeadSourceSysId', 'EmailText', 'IsB2Bproposal', 'B2BAgencySysId', 'CreatorSysId', 'LeadSysId');
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), $travel);
            $select->where('tbl.TPSysId = ?', $leadId);
        } else {
            $travel = array('CustomerSysId', 'AgencySysId', 'AgentSysId', 'VersionId', 'MasterTPSysId', 'TPId', 'CreateDate', 'DownloadCount', 'StatusType', 'LeadSourceSysId', 'EmailText', 'IsB2BProposal', 'B2BAgencySysId', 'EconomyMask', 'IsFixedDeparturePackage');
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
            $select->where('tbl.TPSysId = ?', $leadId);
        }
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetMarketWiseRate($tpID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPendingPaymentLeadList($CRMCustSysId, $agencySysID, $leadId = null)
    {

        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'MinPrice', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'CreateDate as leadCreateDate', 'IsActive');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->limit(5);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId != tbl.TPSysId AND tbl.AgencySysId = tb6.AgencySysId AND tbl.CustomerSysId = tb6.CustomerSysId");
        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CRMCustSysId);
        $select->where('tbl.StatusType = 1 OR StatusType = 2');
        $select->order("tbl.TPSysId DESC");
        //$select->where('tb6.TPSysId IS NULL ');
        $leadId ? $select->where('tbl.TPSysId = ?', $leadId) : '';
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetLatestLeadList($CRMCustSysId, $agencySysID, $leadId = 0, $B2BAgencySysId = 0)
    {

        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate as leadCreateDate', 'Price', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'RoomInfoJson', 'UpdateDate as leadUpdateDate');
        $select = $this->_dbObj->select();
        $select->limit(5);
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), $travel);
        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CRMCustSysId);
        $select->Where('tbl.StatusType IN (?) ', array(1, 2));
        $select->order("tbl.TPSysId DESC");
        if ($leadId > 0) {
            $select->where('tbl.TPSysId = ?', $leadId);
        }
        if ($B2BAgencySysId > 0) {
            $select->where('tbl.B2BAgencySysId = ?', $B2BAgencySysId);
        }

        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPaymentHistoryLeadList($CustomerSysId, $agencySysID, $leadId = null)
    {

        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'MasterTPSysId', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'MinPrice', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'CreateDate as leadCreateDate', 'IsActive');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'TotalCost', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId');
        $customer_trx = array('InvoiceId');
        $lead_remark = array('Remarks');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_Remarks"), "tbl.TPSysId = tb4.TPSysId", $lead_remark);
        //$select->limit(5);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId = tbl.TPSysId", $customer_trx);

        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CustomerSysId);
        $select->where('tbl.AgencySysId = tb6.AgencySysId');
        $select->where('tbl.CustomerSysId = tb6.CustomerSysId');
        $select->where('tbl.StatusType IN (?) ', array(1, 2, 4, 5, 6, 7)); // 1- for flight, 2-for hotel,4- for insurance,5-for package,6-for visa,7-for forex
        $select->order("tbl.TPSysId DESC");
        //echo $select;	
        //$select->where('tb6.TPSysId IS NULL ');
        $leadId ? $select->where('tbl.TPSysId = ?', $leadId) : '';
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetLeadMembersById($agencySysID, $CustomerSysId, $leadId, $IsLeadPax = '')
    {
        if ($leadId > 0) {
            $members = array('EmailId', 'Title', 'Contacts', 'UserName', 'FirstName', 'LastName', 'DOB', 'Gender', 'AgeInYr');
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => 'TB_Agency_Customer_Members'), $members);
            $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tb2.MemberSysId = tbl.MemberSysId", '');
            $select->where("tbl.CustomerSysId = ?", $CustomerSysId);
            $select->where("tb2.CustomerSysId = ?", $CustomerSysId);
            $select->where('tbl.AgencySysId = ?', $agencySysID);
            $select->where('tb2.TPSysId = ?', $leadId);
            if (!empty($IsLeadPax)) {
                $select->where('tb2.IsLeadPax = ?', $IsLeadPax);
            }
            $result = $this->_dbObj->fetchAll($select);
        } else {
            $result = array();
        }
        return $result;
    }

    public function GetTravelPlanRoomInfo($tpID)
    {
        $travel = array('RoomInfoJson');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->where('tbl.TPSysId = ?', $tpID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanCost($tpsysyID, $getroominfojson)
    {
        ini_set('display_errors', '0');
        $rominfojson = json_decode($getroominfojson, 1);
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpsysyID);
        $result = $this->_dbObj->fetchAll($select);
        $totalprice = 0;
        $adultPax = 0;
        $childPax = 0;
        foreach ($rominfojson as $roomarray) {
            $adult = $roomarray['Adult'];
            if ($adult == 1) {
                $totalprice += $result[0]['CostPPSO'];
                $adultPax = $adultPax + 1;
            }
            if ($adult == 2) {
                $totalprice += $result[0]['CostPPDO'];
                $adultPax = $adultPax + 2;
            }
            if ($adult == 3) {
                $totalprice += $result[0]['CostPPTO'];
                $adultPax = $adultPax + 3;
            }
            $child = $roomarray['Child'];
            $bedtype = $roomarray['bedtype'];
            if ($child == 1 && $bedtype == 'extrabed') {
                $childPax = $childPax + 1;
                $totalprice += $result[0]['CostExtraBed'];
            }
            if ($child == 1 && $bedtype == 'withoutbed') {
                $childPax = $childPax + 1;
                $totalprice += $result[0]['CostChildWithoutBed'];
            }
            if ($child == 2 && $bedtype == 'extrabed') {
                $childPax = $childPax + 2;
                $totalprice += 2 * $result[0]['CostExtraBed'];
            }
            if ($child == 2 && $bedtype == 'withoutbed') {
                $childPax = $childPax + 2;
                $totalprice += 2 * $result[0]['CostChildWithoutBed'];
            }
        }
        //$markup = $result[0]['MarkPercent']; 
        $totaltraveler = $adultPax + $childPax;
        $finalcost = ($totaltraveler > 0) ? ($totalprice / $totaltraveler) : $totalprice;
        $result['FinalCost'] = $finalcost;
        return $result;
    }

    public function GetCustomerTravelPlanCost($tpsysyID, $getroominfojson)
    {
        ini_set('display_errors', '0');
        $rominfojson = json_decode($getroominfojson, 1);
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpsysyID);
        $result = $this->_dbObj->fetchAll($select);
        $totalprice = 0;
        $adultPax = 0;
        $childPax = 0;
        foreach ($rominfojson as $roomarray) {
            $adult = $roomarray['Adult'];
            if ($adult == 1) {
                $totalprice += $result[0]['CostPPSO'];
                $adultPax = $adultPax + 1;
            }
            if ($adult == 2) {
                $totalprice += $result[0]['CostPPDO'];
                $adultPax = $adultPax + 2;
            }
            $child = $roomarray['Child'];
            $bedtype = $roomarray['bedtype'];
            if ($child == 1 && $bedtype == 'extrabed') {
                $childPax = $childPax + 1;
                $totalprice += $result[0]['CostExtraBed'];
            }
            if ($child == 1 && $bedtype == 'withoutbed') {
                $childPax = $childPax + 1;
                $totalprice += $result[0]['CostChildWithoutBed'];
            }
            if ($child == 2 && $bedtype == 'extrabed') {
                $childPax = $childPax + 2;
                $totalprice += 2 * $result[0]['CostExtraBed'];
            }
            if ($child == 2 && $bedtype == 'withoutbed') {
                $childPax = $childPax + 2;
                $totalprice += 2 * $result[0]['CostChildWithoutBed'];
            }
        }
        $totaltraveler = $adultPax + $childPax;
        $finalcost = ($totalprice) / ($totaltraveler);
        $result['FinalCost'] = $finalcost;
        return $result;
    }

    public function GetTravelPlanEvents($tpsysID)
    {

        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"));
        $select->joinLeft(array('tb2' => "TB_TravelPlan_Itenary_Events"), "tbl.TPIntSysId = tb2.TPIntSysId");
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanDetailForLendingPage($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan"), array("BookingType", "Title", "Readymade", "BYOPackTypeMask", "SearchString"));
        $select->joinLeft(array('tb2' => "TB_TravelPlan_Itenary_Places"), "tbl.TPSysId = tb2.TPSysId AND tb2.IsMarkForDel = '0' AND tb2.IsActive = '1' AND tb2.Sequence = '1'", array("PlaceSysId as DestinationPlacesSysId"));
        $select->joinLeft(array('tb3' => "TB_Master_Geo_City"), "tb2.PlaceSysId = tb3.CityId", array("Title as DestinationPlaces"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryForLendingPage($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary"), array('MAX(SEQUENCE) as Noofday'));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchRow($select);
        return (int) $result['Noofday'];
    }

    public function GetTravelPlan($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanHotel($hotel_id)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_IC_Accomdation"));
        $select->joinLeft(array('tb2' => "TB_MP_Inventory_Accom"), "tbl.AccomSysId = tb2.XRefAccoSysId", array('SupplierSysId', 'TrxCurrency'));
        $select->joinLeft(array('tb3' => "TB_Master_Geo_City"), "tbl.CitySysId = tb3.CityId", array('tb3.Title as Hotel_name_city'));
        $select->where('tbl.AccomSysId = ?', $hotel_id);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tb2.IsMarkForDelete = ?', 0);
        $select->where('tb2.XRefItemSysId != ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tb2.IsActive = ?', 1);
        //        echo $select;die;
        $result = $this->_dbObj->fetchRow($select);

        return $result;
    }

    public function GetAllTravelPlan($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        // $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetLatestVersionID($tpID, $status = NULL)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('VersionId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->where('tbl.MasterTPSysId = ?', $tpID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        if (!empty($status)) {
            $select->where('tbl.StatusType = ?', $status);
        }
        $select->order("tbl.TPSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanByCustomer($tpsysID, $TPType = '')
    {
        $select = $this->_dbObj->select();

        if ($TPType == 'Query') {
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"));
            $customerarray = array('CustomerSysId', 'EmailId', 'countrycode', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName', 'IsB2BAgent', 'Address', 'AgencySysId as CustomerAgencySysId');
            $b2bagencyColumn = array('Title as CompanyName', 'BusinessType', 'AgencyType', 'TrxCurrency');
            //            $select->joinLeft(array('tblM' => 'TB_Agency_Customer_TravelPlan_Mapping'), "tblM.TPSysId = tbl.TPSysId", array('RefTPSysId'));
            $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customerarray);
            $select->joinLeft(array('tb5' => "TB_Agency"), "tb4.AgencySysId = tb5.AgencySysId", $b2bagencyColumn);
            $select->joinLeft(array('tb2' => 'TB_IC_Supplier'), "tbl.SupplierSysId = tb2.SupplierSysId", array('SupplierName'));
            $select->joinLeft(array('tb7' => 'TB_Master_Currency'), "tb7.CurrencyType = tbl.CurrencyType", array('Symbol'));
            $select->joinLeft(array('tb6' => "TB_Agency_User"), "tbl.AgentSysId = tb6.UserSysId", array('EmailId as agEmailId', 'FirstName as agFirstName', 'LastName as agLastName', 'Signature as agSignature', 'countrycode as agcountrycodeNo1', 'ContactNo1 as agContactNo1', 'SignatureType'));
            $select->where('tbl.TPSysId = ?', $tpsysID);
        } else {
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"));
            $customerarray = array('CustomerSysId', 'EmailId', 'countrycode', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName', 'IsB2BAgent', 'Address', 'AgencySysId as CustomerAgencySysId');
            $b2bagencyColumn = array('Title as CompanyName', 'DisplayName as CompanyDisplayName', 'BusinessType', 'AgencyType', 'TrxCurrency');
            $select->joinLeft(array('tblM' => 'TB_Agency_Customer_TravelPlan_Mapping'), "tblM.TPSysId = tbl.TPSysId", array('RefTPSysId'));
            $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customerarray);
            $select->joinLeft(array('tb5' => "TB_Agency"), "tb4.AgencySysId = tb5.AgencySysId", $b2bagencyColumn);
            $select->joinLeft(array('tb2' => 'TB_IC_Supplier'), "tbl.SupplierSysId = tb2.SupplierSysId", array('SupplierName'));
            $select->joinLeft(array('tb7' => 'TB_Master_Currency'), "tb7.CurrencyType = tbl.CurrencyType", array('Symbol'));
            $select->joinLeft(array('tb6' => "TB_Agency_User"), "tbl.AgentSysId = tb6.UserSysId", array('EmailId as agEmailId', 'FirstName as agFirstName', 'LastName as agLastName', 'Signature as agSignature', 'countrycode as agcountrycodeNo1', 'ContactNo1 as agContactNo1', 'SignatureType'));
            $select->where('tbl.TPSysId = ?', $tpsysID);
        }

        $result = $this->_dbObj->fetchAll($select);
        //        echo "<pre>";print_r($result);die;
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanByTPID($tpsysID, $TPType = 'query')
    {
        if ($TPType == 'query') {
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"));
            $select->where('tbl.TPSysId = ?', $tpsysID);
            $select->where('tbl.IsMarkForDel = ?', 0);
            $select->where('tbl.IsActive = ?', 1);
        } else {
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"));
            $select->where('tbl.TPSysId = ?', $tpsysID);
            $select->where('tbl.IsMarkForDel = ?', 0);
            $select->where('tbl.IsActive = ?', 1);
        }
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenary($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order('tbl.Sequence ASC');
        $select->order('tbl.TotalMinDays ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanItenary($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"));
        //           $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanItenaryBYO($tpsysID, $cityID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary"));
        //           $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.CitySysId = ?', $cityID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        // echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanOnlyItenary($tpsysID)
    {
        $select = $this->_dbObj->select();
        $tpintsysID = array('TPIntSysId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"), $tpintsysID);
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanItenaryAir($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerSelectedFlight($tpintID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"));
        $select->where('tbl.TPIntSysId = ?', $tpintID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSelectedFlight($tpintsysID)
    {
        $select = $this->_dbObj->select();
        $selectedfields = array('InvnItemSysId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"), $selectedfields);
        $select->where('tbl.TPIntSysId = ?', $tpintsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanItenaryInvAir($tpitenarysysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"));
        $select->Where('tbl.TPIntSysId IN (' . $tpitenarysysID . ')');
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsFromAPI = ?', 0);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryAccom($tplanitenayvalues, $catID = NULL)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Accom"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        if (!empty($catID)) {
            $select->Where('tbl.BYOPackType = ?', $catID);
        }
        $select->Where('tbl.IsMarkForDel = ?', 0);
        $select->Where('tbl.IsActive = ?', 1);

        //echo $select;EXIT;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetTravelPlanCustomerItenaryAccom($tplanitenayvalues, $vid = null)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom"));
        $select->joinLeft(array('tb2' => "TB_Master_RoomType"), "tbl.RoomType = tb2.RoomType", array('Title as RoomName'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $vid ? $select->Where('tbl.VersionId = ?', $vid) : '';
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanCustomerItenaryAccomCopy($tplanitenayvalues, $vid = null)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $vid ? $select->Where('tbl.VersionId = ?', $vid) : '';
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /*
      public function GetTravelPlanItenaryAir($tplanitenayvalues){
      $select = $this->_dbObj->select();

      $select->from(array('tbl' => "TB_TravelPlan_Itenary_Air"));
      $select->Where('tbl.TPIntSysId IN ('.$tplanitenayvalues.')');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
     * 
     */

    public function GetCustomerTravelPlanItenaryAccom($tplanitenayvalues, $vid = null)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"), array('Sequence'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Accom"), "tbl.TPIntSysId = tb2.TPIntSysId");
        $select->joinLeft(array('tb3' => "TB_Master_RoomType"), "tb2.RoomType = tb3.RoomType", array('Title as RoomName'));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $vid ? $select->Where('tbl.VersionId = ?', $vid) : '';
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tb2.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanCustomterItenaryAir($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        // echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryAir($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Air"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryActivity($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Events"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryPaces($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Places"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanItenaryPaces($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary_Places"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /*
      public function GetTravelPlanItenaryPaces($tplanitenayvalues)
      {
      $select = $this->_dbObj->select();
      $select->from(array('tbl' => "TB_TravelPlan_Itenary_Places"));
      $select->Where('tbl.TPIntSysId IN ('.$tplanitenayvalues.')');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
     */

    public function GetTravelPlanItenaryEvents($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Events"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanItenaryEvents($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary_Events"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to fetch data for transport @amit */

    public function GetTravelPlanItenaryFixedTransport($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trans_Fixed"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryTransport($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Itenary_Transport"));
        $select->Where('tbl.TPInvnSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryTransFixed($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Trans_Fixed"));
        $select->joinLeft(array('tb2' => "TB_Agency_Area_Master"), "tb2.AreaSysId = tbl.FromPlace", array('Area as FromPlace'));
        $select->joinLeft(array('tb3' => "TB_Agency_Area_Master"), "tb3.AreaSysId = tbl.ToPlace", array('Area as ToPlace'));
        $select->joinLeft(array('tb4' => "TB_Master_Vehicle"), "tb4.VehSysId = tbl.VehSysId", array('VehName', 'IsAC', 'Capacity'));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->where("tbl.XrefSSInvnSysId = 0 OR tbl.XrefSSInvnSysId IS NULL");
        //           echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAgencyCustomerTravelPlanItenaryTransport($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trans_Fixed"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanOtherServices($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_OtherServices"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanOtherServices($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_OtherServices"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanOtherServicesDisplay($tpsysID, $IsSelected = null, $ServiceType = null, $IsNotIncludedInPackage = null)
    {

        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_OtherServices"));
        $select->joinLeft(array('tb2' => "TB_Master_SupplierServices"), "tbl.ServiceType = tb2.SupplierSerSysId", array('Title'));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan"), "tbl.TPIntSysId = tb3.TPSysId", array('AgencySysId', 'NetPrice', 'CurrencyType as SharedCurrencyType'));
        $select->joinLeft(array('tb4' => "TB_Master_Currency"), "tbl.CurrencyType = tb4.CurrencyType", array('Symbol as CurrencySymbol'));
        $select->joinLeft(array('tb5' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb5.SupplierSysId", array('SupplierName'));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDelete = ?', 0);
        if ($IsSelected == 1) {
            $select->where('tbl.IsSelected = ?', 1);
        }
        if ($ServiceType) {
            $select->where('tbl.ServiceType != ?', 5);
        }
        if ($IsNotIncludedInPackage) {
            $select->where('tbl.IsIncludedInPackage is null OR tbl.IsIncludedInPackage = 0');
        }

        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanItenaryTransport($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary_Transport"));
        $select->Where('tbl.TPInvnSysId IN (' . $tplanitenayvalues . ')');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanItenaryRules($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Rules"));
        $select->Where('tbl.TPInvnSysId IN (' . $tplanitenayvalues . ')');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /*
      public function GetTravelPlanSightSeeing($tplanitenayvalues)
      {
      $select = $this->_dbObj->select();
      $select->from(array('tbl' => "TB_TravelPlan_SightSeeing"));
      $select->Where('tbl.InvnItemSysId IN ('.$tplanitenayvalues.')');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
     * */

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanSightSeeing($tplanitenayvalues, $versionId = 0)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_SightSeeing"));
        $select->joinLeft(array('tb2' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb2.SupplierSysId", 'SupplierName');
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_Trans_Fixed"), "tbl.VersionId = tb3.XrefItemSysId", array('RouteVechSysId', 'AreaSysId', 'SupplierSysId as TransSupplierSysId', 'Capacity', 'Type_Text', 'FromPlace', 'ToPlace'));
        $select->joinLeft(array('tb4' => "TB_Master_Geo_City"), "tbl.CityId = tb4.CityId", array('Title as cityTitle'));
        $select->Where('tbl.InvnItemSysId IN (' . $tplanitenayvalues . ')');
        if ($versionId > 0) {
            $select->Where('tbl.VersionId = ?', $versionId);
        }
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanSightSeeing($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_SightSeeing"));
        $select->Where('tbl.InvnItemSysId IN (' . $tplanitenayvalues . ')');
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanTerms($tplanitenayvalues)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Terms_Conditions"));
        $select->Where('tbl.TPIntSysId IN (' . $tplanitenayvalues . ')');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanTransDaywise()
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Trans_Daywise"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelMarketPrice($tpsysID, $MarketPlaceId = NULL, $strStartDate = '')
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        if ($MarketPlaceId != '') {
            $select->where('tbl.MarketPlaceId = ?', $MarketPlaceId);
        }
        if(!empty($strStartDate)){
            $select->where('? BETWEEN CAST(tbl.FromDate AS DATE) AND CAST(tbl.ToDate AS DATE)', $strStartDate);
        }
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelRate($tpsysID, $MarketPlaceId = NULL,$strStartDate = '')
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Rate"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        if ($MarketPlaceId != '') {
            $select->where('tbl.MarketPlaceId = ?', $MarketPlaceId);
        }
        if(!empty($strStartDate)){
            $select->where('? BETWEEN CAST(tbl.StartDate AS DATE) AND CAST(tbl.ValidTill AS DATE)', $strStartDate);
        }
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanTerms($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Terms_Conditions"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanTermsCond($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Terms_Conditions"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanCancelPolicy($id)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Rules"));
        $select->where('tbl.TPSysId = ?', $id);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPlanTransFixed($id)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trans_Fixed"));
        $select->where('tbl.TPSysId = ?', $id);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getPackageCancelPolicy($id)
    {
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_Rules"));
        $select->where('TPRulesSysId = ?', $id);
        //        echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelMarketPrice($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $select->order('tbl.PAX ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* Function is used to copy data - so join is strictly prohibited @pooja */

    public function GetCustomerTravelPrice($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Rate"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsActive = ?', '1');
        $select->order('tbl.PAX ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPackageRateByTPID($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Rate"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetMPPackageRateByTPID($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanCustomerDetails($tpID)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'Title');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'countrycode', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'IsfromAPI', 'TotalPax', 'Discounts', 'XrefBookingId', 'SpecialRequest');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars', 'DetailImg');
        // $arrAccomdationInventory = array('Title as RoomType','SupplierSysId','NetDOccupCost','NetSOccupCost');
        $arrCancPolicy = array('RoomIndex as CANCELPOLICYroomIndex', 'ChargeType as CANCELPOLICYChargeType', 'Charge as CANCELPOLICYCharge', 'Fromdate as CANCELPOLICYFromdate', 'Todate as CANCELPOLICYTodate');
        $arrAccomRoomInfo = array('RoomNumber as ACCOMROOMRoomNumber', 'OtherDetails as ACCOMROOMOtherDetails', 'Title as ACCOMROOMTitle', 'HotelNorms as ACCOMROOMHotelNorms', 'Amenities as ACCOMROOMAmenities');
        $arrCustomerMembers = array('Title as MEMBERTitle', 'Title as MEMBERTitle', 'FirstName as MEMBERFirstName', 'LastName as MEMBERLastName');

        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        // $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId" , $arrAccomdationInventory);

        $select->joinLeft(array('tb7' => "TB_IC_Accomdation_Room_CancellationPolicy"), "tb7.Accosysid = tb3.AccoSysId AND tb7.RoomIndex = tb3.RoomIndex", $arrCancPolicy);
        $select->joinLeft(array('tb8' => "TB_IC_Accomdation_Room"), "tb8.AccomSysId = tb3.AccoSysId AND tb8.RoomIndex = tb3.RoomIndex AND tb8.RoomIndex = tb7.RoomIndex AND tb8.AccomSysId = tb7.Accosysid AND tb8.RoomNumber = tb7.RoomNumber", $arrAccomRoomInfo);
        $select->joinLeft(array('tb9' => "TB_Agency_Customer_Members"), "tb9.CustomerSysId = tb1.CustomerSysId", $arrCustomerMembers);

        $select->where('tb1.TPSysId = ?', $tpID);
        $select->limit(1);
        /* 			$select->where("tb1.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb4.IsActive = ?", 1);
          $select->where("tb5.IsActive = ?", 1);
          $select->where("tb6.IsActive = ?", 1);
          $select->where("tb1.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDel = ?", 0);
          $select->where("tb3.IsMarkForDel = ?", 0);
          $select->where("tb4.IsMarkForDelete = ?", 0);
          $select->where("tb5.IsMarkForDel = ?", 0);
          $select->where("tb6.IsMarkForDelete = ?", 0);
         */
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetVersionInfo($tpID)
    {
        $select = $this->_dbObj->select();
        $versionarray = array('TPSysId', 'VersionId', '((select sum(adT1.Tax) FROM TB_Agency_Customer_TravelPlan_AddonServices adT1 where adT1.IsMarkForDelete = "0" AND a.TPSysId = adT1.TPSysId AND (adT1.PlanType = 21 OR adT1.PlanType = 19))) as TotalTcs');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan", $versionarray));
        $select->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol');
        $select->where('tbl.MasterTPSysId = ?', $tpID);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->order("tbl.VersionId ASC");
        $select = "SELECT tbl.*,((select sum(adT1.Tax) FROM TB_Agency_Customer_TravelPlan_AddonServices adT1 where adT1.IsMarkForDelete = '0' AND tbl.TPSysId = adT1.TPSysId AND (adT1.PlanType = 21 OR adT1.PlanType = 19))) as TotalTcs, tb3.Symbol FROM TB_Agency_Customer_TravelPlan AS tbl "
            . "LEFT JOIN TB_Master_Currency AS tb3 ON tbl.CurrencyType = tb3.CurrencyType "
            . "WHERE (tbl.MasterTPSysId = '$tpID') AND "
            //                . "(tbl.StatusType NOT IN (15)) AND "   //
            . "(tbl.IsActive = 1) AND (tbl.IsMarkForDel = 0) ORDER BY tbl.VersionId ASC";
        $result = $this->_dbObj->query($select)->fetchAll();
        return $result;
    }

    public function GetProposalCustomerChatDetails($CustomerSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'MasterTPSysId', 'PlanBookingId', 'CreateDate', 'UpdateDate', 'CustomerSysId');
        $customerarray = array('FirstName', 'LastName');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId", '');
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->where('tb1.CustomerSysId = ?', $CustomerSysId);
        $select->where('tb2.UserSysId= ' . $CustomerSysId . ' or tb2.SenderSysId= ' . $CustomerSysId . '');
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDelete = ?", 0);
        $select->group(array('tb1.TPSysId', 'tb1.MasterTPSysId', 'tb1.PlanBookingId', 'tb1.CreateDate', 'tb1.UpdateDate', 'tb1.CustomerSysId', 'tb3.FirstName', 'tb3.LastName'));
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerChatHistoryDetails($leadId, $order = 'DESC')
    {
        /* $select = $this->_dbObj->select();
          $messagearray = array('MsgSysId','IsAgent','Message','CreatedDate','UpdateDate');
          $tb2array = array('FirstName','LastName');
          $tb5array = array('FirstName as AgentFirstName','LastName as AgentLastName');
          $select->from(array('tb1' => "TB_Agency_User_Inbox"), $messagearray);
          $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb1.SenderSysId" , $tb2array);
          $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.UserSysId" , '');
          $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.UserSysId and tb1.IsAgent=1" , '');
          $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tb1.SenderSysId and tb1.IsAgent=1" , $tb5array);
          $select->where('tb1.RefSysId = ?', $leadId);
          $select->where('tb1.UserSysId!=0');
          $select->where("tb1.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb1.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDelete = ?", 0);
          $select->where("tb3.IsMarkForDelete = ?", 0);
          $select->order("tb1.MsgSysId ".$order.""); */
        /* $select = 'SELECT 
          case when tb2.IsActive=1 then tb2.IsActive else tb3.IsActive End as IsActive,
          "tb1"."MsgSysId","tb1"."SenderSysId","tb1"."IsAgent", "tb1"."Message", "tb1"."CreatedDate", "tb1"."UpdateDate",
          "tb2"."FirstName", "tb2"."LastName", "tb3"."FirstName" AS "AgentFirstName",
          "tb3"."LastName" AS "AgentLastName" FROM "TB_Agency_User_Inbox" AS "tb1"
          LEFT JOIN "TB_Agency_Customer" AS "tb2" ON (tb2.CustomerSysId = tb1.SenderSysId
          OR tb2.CustomerSysId = tb1.SenderSysId) AND tb2.IsActive = 1
          LEFT JOIN "TB_Agency_User" AS "tb3" ON (tb3.UserSysId = tb1.UserSysId
          OR tb3.UserSysId = tb1.SenderSysId) AND tb3.IsActive = 1
          WHERE (tb1.RefSysId = ' . $leadId . ') AND (tb1.UserSysId!=0) AND (tb1.IsActive = 1)
          AND ((tb2.IsActive = 1 AND tb2.IsMarkForDelete = 0 AND tb1.IsAgent = 0) OR (tb3.IsActive = 1 and tb1.IsAgent = 1 AND tb3.IsMarkForDel = 0))
          AND (tb1.IsMarkForDel = 0) order by tb1.MsgSysId ' . $order . ''; */
        $select = 'SELECT 
			case when tb2.IsActive=1 then tb2.IsActive else tb3.IsActive End as IsActive,
			"tb1"."MsgSysId","tb1"."SenderSysId","tb1"."IsAgent", "tb1"."Message", "tb1"."CreatedDate", "tb1"."UpdateDate", 
			"tb2"."FirstName", "tb2"."LastName", "tb3"."FirstName" AS "AgentFirstName", 
			"tb3"."LastName" AS "AgentLastName" FROM "TB_Agency_User_Inbox" AS "tb1" 
			LEFT JOIN "TB_Agency_Customer" AS "tb2" ON tb2.CustomerSysId = tb1.SenderSysId AND tb1.IsAgent=0 AND tb2.IsActive = 1
			LEFT JOIN "TB_Agency_User" AS "tb3" ON tb3.UserSysId = tb1.SenderSysId AND tb1.IsAgent=1 AND tb3.IsActive = 1
			WHERE (tb1.RefSysId = ' . $leadId . ') AND (tb1.UserSysId!=0) AND (tb1.IsActive = 1) 
			AND ((tb2.IsActive = 1 AND tb2.IsMarkForDelete = 0 AND tb1.IsAgent = 0) OR (tb3.IsActive = 1 and tb1.IsAgent = 1 AND tb3.IsMarkForDel = 0)) 
			AND (tb1.IsMarkForDel = 0) order by tb1.MsgSysId ' . $order . '';
        // echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPublicProposalWithHotelList($leadId, $TPSysId)
    {

        $travel = array('TPSysId', 'MasterTPSysId', 'AgencySysId', 'AgentSysId', 'Rating', 'TPSysId', 'StatusType', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'Taxes', 'SourceSysId as ICSourceSysId', 'AllowBooking', 'RateType', 'SpecialRequest');
        $customer_details = array('CustomerSysId', 'EmailId');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars');
        $arrAccomdationInventory = array('SupplierSysId', 'NetDOccupCost', 'NetSOccupCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId", $arrAccomdationInventory);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tb5.IsActive = ?", 1);
        //$select->where("tb6.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->where("tb5.IsMarkForDel = ?", 0);
        //$select->where("tb6.IsMarkForDelete = ?", 0);

        $select->where('tbl.MasterTPSysId = ?', $leadId);
        //$select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where('tbl.StatusType > ?', 3);
        //        echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSupplierCount($leadID, $pkgType = NULL, $PlanType = NULL)
    {

        $select = $this->_dbObj->select();
        if ($pkgType == 2) {
            $result = array();
        } else {
            $tpsysID = array('SupplierSysId');
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $tpsysID);
            $select->where('tbl.TPSysId = ?', $leadID);
            // $select->where('tbl.MasterTPSysId = ?', $leadID);
            $select->where('tbl.StatusType > ?', 3);
            $select->where('tbl.SupplierSysId > ?', 0);
            $result = $this->_dbObj->fetchAll($select);
        }
        return $result;
    }

    public function GetPublicPageLeadList($CRMCustSysId, $agencySysID, $leadId = null)
    {
        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'AgentSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_air = array('TPIntSysId', 'AdultPax', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'SpecialRequest as hotelSpecialRequest', 'RoomMemInfoJson');
        $airport_code = array('AirportCode', 'AirportTitle');
        $city = array('Title', 'CityId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb4.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb5' => "TB_Master_Airport"), "tb3.DestAirportCode = tb5.AirportCode", $airport_code);
        //$select->joinLeft(array('tb6' => "TB_Master_Geo_City"), "tb6.CityId = tbl.DestPlaceSysId" , $city);

        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CRMCustSysId);
        $select->Where('tbl.StatusType > ?', 3);
        $select->order("tbl.TPSysId DESC");
        $leadId ? $select->where('tbl.TPSysId = ?', $leadId) : '';
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCurrencyByCurrencyType($CurrencyType)
    {
        if ((int) $CurrencyType == 0) {
            $CurrencyType = 1;
        }
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Master_Currency"));
        $select->where('tbl.CurrencyType = ?', $CurrencyType);
        $select->where('tbl.IsDelete = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetCurrencyTypeByCurrency($CurrencyName)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Master_Currency"));
        $select->where('tbl.Symbol = ?', $CurrencyName);
        $select->where('tbl.IsDelete = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getAllCurrency()
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Master_Currency"), array('CurrencyType', 'Symbol'));
        //$select->where('tbl.Symbol = ?', $CurrencyName);
        $select->where('tbl.IsDelete = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        //echo $select;exit;
        $result = $this->_dbObj->fetchAll($select);
        $currencyArray = array();
        foreach ($result as $currencyVal) {
            $currencyArray[trim($currencyVal['CurrencyType'])] = trim($currencyVal['Symbol']);
        }
        return $currencyArray;
    }

    public function GetTravelPlanByID($tpID)
    {
        $travel = array('*');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_CostSheet"), $travel);
        $select->where('tbl.TPSysId = ?', $tpID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetCustomerChatHistoryDetailsById($leadId, $order = 'DESC')
    {
        $select = $this->_dbObj->select();
        $messagearray = array('MsgSysId', 'IsAgent', 'Message', 'CreatedDate', 'UpdateDate');
        $tb2array = array('FirstName', 'LastName');
        $tb5array = array('FirstName as AgentFirstName', 'LastName as AgentLastName');
        $select->from(array('tb1' => "TB_Agency_User_Inbox"), $messagearray);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb1.SenderSysId", $tb2array);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.UserSysId", '');
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.UserSysId and tb1.IsAgent=1", '');
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tb1.SenderSysId and tb1.IsAgent=1", $tb5array);
        $select->where('tb1.RefSysId = ?', $leadId);
        $select->where('tb1.UserSysId!=0');
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        //$select->where("tb3.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDelete = ?", 0);
        //$select->where("tb3.IsMarkForDelete = ?", 0);

        $select->order("tb1.MsgSysId " . $order . "");
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetCityNamebyID($cityID)
    {
        $travel = array('Title');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Master_Geo_City"), $travel);
        $select->where('tbl.CityId = ?', $cityID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetPkgStartDate($pkgID)
    {
        $selectedfields = array('StartDate');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $selectedfields);
        $select->where('tbl.TPSysId = ?', $pkgID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetPkgStartDateByo($pkgID)
    {
        $selectedfields = array('StartDate');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan"), $selectedfields);
        $select->where('tbl.TPSysId = ?', $pkgID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetPurchasedPublicPageLeadList($CRMCustSysId, $agencySysID, $leadId = null)
    {
        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'AgentSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_air = array('TPIntSysId', 'AdultPax', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'SpecialRequest as hotelSpecialRequest', 'RoomMemInfoJson');
        $airport_code = array('AirportCode', 'AirportTitle');
        $city = array('Title', 'CityId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb4.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb5' => "TB_Master_Airport"), "tb3.DestAirportCode = tb5.AirportCode", $airport_code);
        //$select->joinLeft(array('tb6' => "TB_Master_Geo_City"), "tb6.CityId = tbl.DestPlaceSysId" , $city);

        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CRMCustSysId);
        //$select->Where('tbl.StatusType = ?',5);
        $select->order("tbl.TPSysId DESC");
        $leadId ? $select->where('tbl.TPSysId = ?', $leadId) : '';
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //function used for tax percentage value by agency id created by Ee Amit kumar Dubey on 7 feb 2017 for horelsearch popup propoasal
    public function getAgencyStandardTax($agencySysId)
    {
        $arrAllocMarkups = array('Currency', 'AccomType', 'MarkUpType', 'MarkUp', 'Tax');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_MP_StdMarkup_Accom"), $arrAllocMarkups);
        $select->where("tbl.AgencySysId = ?", $agencySysId);
        $select->where("tbl.ItemSourceType = ?", 1);
        $select->where("tbl.IsApproved = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tbl.IsActive = ?", 1);
        $select->limit(1);
        //echo $select; exit;
        $result = $this->_dbObj->fetchRow($select);

        return $result;
    }

    //get proposal details by masterid and planid created by Er amit kumar dubey on 9 feb 2017 at 3:48 PM
    public function GetPublicProposalWithHotelListByPlanId($MasterTPSysId, $leadId)
    {

        $travel = array('TPSysId', 'MasterTPSysId', 'AgencySysId', 'AgentSysId', 'Rating', 'TPSysId', 'StatusType', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'Taxes', 'SourceSysId as ICSourceSysId');
        $customer_details = array('CustomerSysId', 'EmailId');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars');
        $arrAccomdationInventory = array('Title as RoomType', 'SupplierSysId', 'NetDOccupCost', 'NetSOccupCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId", $arrAccomdationInventory);
        $select->where('tbl.MasterTPSysId = ?', $MasterTPSysId);
        $select->where('tbl.TPSysId = ?', $leadId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tb5.IsActive = ?", 1);
        //$select->where("tb6.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->where("tb5.IsMarkForDel = ?", 0);
        //$select->where("tb6.IsMarkForDelete = ?", 0);
        $select->where('tbl.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //get proposal details by masterid and planid created by Er amit kumar dubey on 9 feb 2017 at 3:48 PM
    public function GetPublicProposalWithHotListByStaus($MasterTPSysId = null, $leadId = null)
    {

        $travel = array('TPSysId', 'MasterTPSysId', 'AgencySysId', 'AgentSysId', 'Rating', 'TPSysId', 'StatusType', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'Taxes', 'SourceSysId as ICSourceSysId');
        $customer_details = array('CustomerSysId', 'EmailId');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars');
        $arrAccomdationInventory = array('Title as RoomType', 'SupplierSysId', 'NetDOccupCost', 'NetSOccupCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId", $arrAccomdationInventory);
        /* 		$select->where("tbl.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb4.IsActive = ?", 1);
          $select->where("tb5.IsActive = ?", 1);
          $select->where("tb6.IsActive = ?", 1);
          $select->where("tbl.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDel = ?", 0);
          $select->where("tb3.IsMarkForDel = ?", 0);
          $select->where("tb4.IsMarkForDelete = ?", 0);
          $select->where("tb5.IsMarkForDel = ?", 0);
          $select->where("tb6.IsMarkForDelete = ?", 0);
         */

        if (isset($MasterTPSysId) && !empty($MasterTPSysId)) {
            $select->where('tbl.MasterTPSysId = ?', $MasterTPSysId);
        }
        if (isset($leadId) && !empty($leadId)) {
            $select->where('tbl.TPSysId = ?', $leadId);
        }
        //$select->where('tbl.StatusType = ?', 4);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPublicPageLeadListForView($CustomerSysId, $agencySysID, $TPSysId = null, $MasterTPSysId = NULL)
    {
        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'AgentSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_air = array('TPIntSysId', 'AdultPax', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'SpecialRequest as hotelSpecialRequest', 'RoomMemInfoJson');
        $airport_code = array('AirportCode', 'AirportTitle');
        $city = array('Title', 'CityId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb4.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb5' => "TB_Master_Airport"), "tb3.DestAirportCode = tb5.AirportCode", $airport_code);
        //$select->joinLeft(array('tb6' => "TB_Master_Geo_City"), "tb6.CityId = tbl.DestPlaceSysId" , $city);

        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tbl.CustomerSysId = ?', $CustomerSysId);
        //$select->Where('tbl.StatusType = ?',4);
        $select->order("tbl.TPSysId DESC");
        $TPSysId ? $select->where('tbl.TPSysId = ?', $TPSysId) : '';
        $MasterTPSysId ? $select->where('tbl.MasterTPSysId = ?', $MasterTPSysId) : '';
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetProposalList($leadID)
    {
        $select = $this->_dbObj->select();
        $travelplanArray = array('*');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan", $travelplanArray));
        $select->where('tbl.MasterTPSysId = ?', $leadID);
        $select->where('tbl.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanType($leadID, $IDType = '')
    {
        $select = $this->_dbObj->select();
        if ($IDType == 'Query') {
            $travelplanArray = array('TPSysId as query_id', 'PlanType', 'IsPlanViewed', 'AgentSysId', 'AgencySysId', 'IsHotelOnlyPackage', 'OpsAgentSysId', 'TPId', 'IsB2BProposal', 'CustomerSysId', 'RoomInfoJson');
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), $travelplanArray);
            $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb2.CustomerSysId", array('AgencySysId as CustomerAgencySysId'));
        } else {
            $travelplanArray = array('MasterTPSysId as query_id', 'PlanType', 'IsPlanViewed', 'AgentSysId', 'AgencySysId', 'IsHotelOnlyPackage', 'OpsAgentSysId', 'TPId', 'IsB2BProposal', 'CustomerSysId');
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travelplanArray);
            $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb2.CustomerSysId", array('AgencySysId as CustomerAgencySysId'));
        }
        $select->where('tbl.TPSysId = ?', $leadID);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getCustPackRate($packid, $strStartDate, $MarketPlaceId = NULL)
    {
        //        $arrStartDate = (array) $tripdate;
        //        $strStartDate = $arrStartDate['date'];
        $cond = '';
        if ($MarketPlaceId != '') {
            $cond = " AND MarketPlaceId=" . $MarketPlaceId . "";
        }
        $sqlPackage = "SELECT TBTPMWR.*,TBACT.ExtraMarkUp,TBACT.CustomDiscount,TBMC.Symbol FROM TB_Agency_Customer_TravelPlan_MarketWise_Rate as TBTPMWR "
            . " LEFT JOIN TB_Agency_Customer_TravelPlan TBACT ON TBACT.TPSysId = TBTPMWR.TPIntSysId "
            . " LEFT JOIN TB_Master_Currency TBMC ON TBMC.CurrencyType = TBTPMWR.CurrencyType "
            . " WHERE TPIntSysId = '" . @$packid . "' AND TBTPMWR.IsMarkForDel = '0' AND TBTPMWR.IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) $cond";

        $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();
        return $resultPackage;
    }

    public function getCustPackRateRowWise($packid, $strStartDate, $MarketPlaceId = NULL, $paxCount = 0)
    {
        //        $arrStartDate = (array) $tripdate;
        //        $strStartDate = $arrStartDate['date'];
        if ((int) $paxCount > 2) {
            $totalAdult = $paxCount;
        } else {
            $totalAdult = 2;
        }
        $cond = '';
        if ($MarketPlaceId != '') {
            $cond = " AND MarketPlaceId=" . $MarketPlaceId . "";
        }
        $sqlPackage = "SELECT Top 1 TBTPMWR.*,TBMC.Symbol FROM TB_Agency_Customer_TravelPlan_MarketWise_Rate as TBTPMWR "
            . " LEFT JOIN TB_Master_Currency TBMC ON TBMC.CurrencyType = TBTPMWR.CurrencyType "
            . " WHERE PAX >= '" . $totalAdult . "' AND TPIntSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND TBTPMWR.IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) $cond ORDER BY Pax ASC";
        //echo $sqlPackage;exit;
        $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();

        if (empty($resultPackage)) {
            $PAXQUERY = "SELECT Top 1 TBTPMWR.*,TBMC.Symbol FROM TB_Agency_Customer_TravelPlan_MarketWise_Rate as TBTPMWR "
                . " LEFT JOIN TB_Master_Currency TBMC ON TBMC.CurrencyType = TBTPMWR.CurrencyType "
                . " WHERE PAX <= '" . $totalAdult . "' AND TPIntSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND TBTPMWR.IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) $cond ORDER BY Pax DESC";

            $resultPackagePax = $this->_dbObj->query($PAXQUERY)->fetchAll();
            if (!empty($resultPackagePax)) {
                $sqlPackage = "SELECT Top 1 TBTPMWR.*,TBMC.Symbol FROM TB_Agency_Customer_TravelPlan_MarketWise_Rate as TBTPMWR "
                    . " LEFT JOIN TB_Master_Currency TBMC ON TBMC.CurrencyType = TBTPMWR.CurrencyType "
                    . " WHERE PAX <= '" . $resultPackagePax[0]['Pax'] . "' AND TPIntSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND TBTPMWR.IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) $cond ORDER BY Pax DESC";

                $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();
            }
        }


        return $resultPackage;
    }

    public function getCustTravelPackRate($packid, $strStartDate, $MarketPlaceId = NULL)
    {
        //               $arrStartDate = (array) $tripdate;
        //        $strStartDate = $arrStartDate['date'];
        $cond = '';
        if ($MarketPlaceId != '') {
            $cond = " AND MarketPlaceId=" . $MarketPlaceId . "";
        }
        $sqlPackage = "SELECT * FROM TB_Agency_Customer_TravelPlan_Rate as TBTPMWR WHERE TPSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.StartDate AS DATE) AND CAST(TBTPMWR.ValidTill AS DATE) $cond";
        // echo $sqlPackage;
        $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();
        return $resultPackage;
    }

    public function getCustTravelPackRateRowWise($packid, $strStartDate, $MarketPlaceId = NULL, $paxCount = 0)
    {
        if ((int) $paxCount > 2) {
            $totalAdult = $paxCount;
        } else {
            $totalAdult = 2;
        }

        $cond = '';
        if ($MarketPlaceId != '') {
            $cond = " AND MarketPlaceId=" . $MarketPlaceId . "";
        }
        $sqlPackage = "SELECT Top 1 * FROM TB_Agency_Customer_TravelPlan_Rate as TBTPMWR WHERE PAX <= '" . $totalAdult . "' AND CostDO IS NOT NULL AND TPSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.StartDate AS DATE) AND CAST(TBTPMWR.ValidTill AS DATE) $cond ORDER BY Pax DESC";
        //echo "prashant-------". $sqlPackage; exit;
        $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();

        if (empty($resultPackage)) {
            $PAXQUERY = "SELECT Top 1 * FROM TB_Agency_Customer_TravelPlan_Rate as TBTPMWR WHERE PAX >= '" . $totalAdult . "' AND CostDO IS NOT NULL AND TPSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.StartDate AS DATE) AND CAST(TBTPMWR.ValidTill AS DATE) $cond ORDER BY Pax ASC";
            $resultPackagePax = $this->_dbObj->query($PAXQUERY)->fetchAll();
            //  echo "<pre>";print_r($resultPackagePax);exit;
            if (!empty($resultPackagePax)) {
                $sqlPackage = "SELECT Top 1 * FROM TB_Agency_Customer_TravelPlan_Rate as TBTPMWR WHERE PAX <= '" . $resultPackagePax[0]['Pax'] . "' AND CostDO IS NOT NULL AND TPSysId = '" . @$packid . "' AND IsMarkForDel = '0' AND IsActive = '1'  AND '$strStartDate' BETWEEN CAST(TBTPMWR.StartDate AS DATE) AND CAST(TBTPMWR.ValidTill AS DATE) $cond ORDER BY Pax DESC";
                $resultPackage = $this->_dbObj->query($sqlPackage)->fetchAll();
            }
        }


        return $resultPackage;
    }

    //function used for transaction tables for hotel created by Er Amit KUmar Dubey on 17 feb 2017
    public function GetTravelPlanCustomerDetailsTrx($tpID, $TrxType = 'H')
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'APIBookingRes', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'IsfromAPI', 'TotalPax', 'Discounts', 'XrefBookingId', 'SpecialRequest');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars', 'PrimaryContact as hotelPrimaryContact');
        $accom_detailsInv = array('Title as hotelName', 'ShortName', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars', 'PrimaryContact as hotelPrimaryContact', 'CheckinTime', 'CheckOutTime');
        $arrAccomdationInventory = array('SupplierSysId', 'NetDOccupCost', 'NetSOccupCost');
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate', 'CurrencyType');
        $arrCancPolicy = array('RoomIndex as CANCELPOLICYroomIndex', 'ChargeType as CANCELPOLICYChargeType', 'Charge as CANCELPOLICYCharge', 'Fromdate as CANCELPOLICYFromdate', 'Todate as CANCELPOLICYTodate');
        $arrAccomRoomInfo = array('RoomNumber as ACCOMROOMRoomNumber', 'OtherDetails as ACCOMROOMOtherDetails', 'Title as ACCOMROOMTitle', 'HotelNorms as ACCOMROOMHotelNorms', 'Amenities as ACCOMROOMAmenities');
        $arrCustomerMembers = array('Title as MEMBERTitle', 'Title as MEMBERTitle', 'FirstName as MEMBERFirstName', 'LastName as MEMBERLastName');
        $arrCustomerMembersPax = array('TPPaxSysId');

        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb31' => "TB_Agency_Customer_TravelPlan_Accom_Invn_Mapping"), "tb2.TPIntSysId = tb31.TPIntSysId", array('RoomType', 'MealPlanType', 'Adult', 'Child', 'Infent', 'FromDate as RoomFromDate', 'ToDate as RoomToDate', 'MappingSysId'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        //        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb51' => "TB_IC_Accomdation"), "tb51.AccomSysId = tb3.AccoSysId", $accom_detailsInv);
        //        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId", $arrAccomdationInventory);
        $select->joinLeft(array('tb7' => "TB_Agency_Customer_Trx"), "tb7.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb8' => "TB_Trx"), "tb8.TrxSysId = tb7.TrxSysId", $arrTBTrx);
        $select->joinLeft(array('tb9' => "TB_IC_Accomdation_Room_CancellationPolicy"), "tb9.Accosysid = tb3.AccoSysId AND tb9.RoomIndex = tb3.RoomIndex", $arrCancPolicy);
        $select->joinLeft(array('tb10' => "TB_Master_RoomType"), "tb10.RoomType = tb31.RoomType", array('Title as RoomName'));
        $select->joinLeft(array('tb11' => 'TB_Master_Accom_MealType'), 'tb11.MealTypeId = tb31.MealPlanType', array("Title as MealPlanTypeTitle"));
        //        $select->joinLeft(array('tb11' => "TB_Agency_Customer_Members"), "tb11.CustomerSysId = tb1.CustomerSysId", $arrCustomerMembers);
        $select->joinLeft(array('tb12' => "TB_Agency_Customer_TravelPlan_Pax"), "tb1.TPSysId = tb12.TPSysId", $arrCustomerMembersPax);
        $select->joinLeft(array('tb13' => "TB_Agency_Customer_Members"), "tb12.MemberSysId = tb13.MemberSysId", array('Title as memberSalutation', 'FirstName as memberFirstName', 'LastName as memberLastName', 'Relation as memberRelation', 'paxType as memberpaxType'));
        $select->joinLeft(array('tb14' => "TB_Master_Currency"), "tb8.CurrencyType = tb14.CurrencyType", 'Symbol as CurrencySymbol');

        $select->where('tb1.TPSysId = ?', $tpID);
        $select->where('tb12.TPSysId = ?', $tpID);
        //        $select->where('tb7.TrxType = ?', $TrxType);
        $select->where('tb8.TrxType = ?', $TrxType);
        $select->where('tb8.TrxStatus = ?', 1);
        //$select->limit(1);
        /* 			$select->where("tb1.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb4.IsActive = ?", 1);
          $select->where("tb5.IsActive = ?", 1);
          $select->where("tb6.IsActive = ?", 1);
          $select->where("tb1.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDel = ?", 0);
          $select->where("tb3.IsMarkForDel = ?", 0);
          $select->where("tb4.IsMarkForDelete = ?", 0);
          $select->where("tb5.IsMarkForDel = ?", 0);
          $select->where("tb6.IsMarkForDelete = ?", 0);
         */

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetHotelBookingDetails($tpID, $TrxType = 'H')
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'APIBookingRes', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'IsfromAPI', 'TotalPax', 'Discounts', 'XrefBookingId', 'SpecialRequest');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars', 'PrimaryContact as hotelPrimaryContact');
        $accom_detailsInv = array('Title as hotelName', 'Address as hotelAddress', 'Rating as AccomRating');

        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate', 'CurrencyType');
        $arrCancPolicy = array('RoomIndex as CANCELPOLICYroomIndex', 'ChargeType as CANCELPOLICYChargeType', 'Charge as CANCELPOLICYCharge', 'Fromdate as CANCELPOLICYFromdate', 'Todate as CANCELPOLICYTodate', 'BookingTermCond');


        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        //$select->joinLeft(array('tb31' => "TB_Agency_Customer_TravelPlan_Accom_Invn_Mapping"), "tb2.TPIntSysId = tb31.TPIntSysId", array('RoomType', 'MealPlanType', 'Adult', 'Child', 'Infent', 'FromDate as RoomFromDate', 'ToDate as RoomToDate'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId AND tb3.IsFromAPI = '1'", $accom_details);
        $select->joinLeft(array('tb51' => "TB_IC_Accomdation"), "tb51.AccomSysId = tb3.AccoSysId AND tb3.IsFromAPI = '0'", $accom_detailsInv);
        //        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId", $arrAccomdationInventory);
        $select->joinLeft(array('tb7' => "TB_Agency_Customer_Trx"), "tb7.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb8' => "TB_Trx"), "tb8.TrxSysId = tb7.TrxSysId", $arrTBTrx);
        $select->joinLeft(array('tb9' => "TB_IC_Accomdation_Room_CancellationPolicy"), "tb9.Accosysid = tb3.AccoSysId AND tb9.RoomIndex = tb3.RoomIndex", $arrCancPolicy);
        //$select->joinLeft(array('tb10' => "TB_Master_RoomType"), "tb10.RoomType = tb31.RoomType", array('Title as RoomName'));
        //$select->joinLeft(array('tb11' => 'TB_Master_Accom_MealType'), 'tb11.MealTypeId = tb31.MealPlanType', array("Title as MealPlanTypeTitle"));
        //$select->joinLeft(array('tb11' => "TB_Agency_Customer_Members"), "tb11.CustomerSysId = tb1.CustomerSysId", $arrCustomerMembers);
        //$select->joinLeft(array('tb12' => "TB_Agency_Customer_TravelPlan_Pax"), "tb1.TPSysId = tb12.TPSysId", $arrCustomerMembersPax);
        //$select->joinLeft(array('tb13' => "TB_Agency_Customer_Members"), "tb12.MemberSysId = tb13.MemberSysId", array('Title as memberSalutation', 'FirstName as memberFirstName', 'LastName as memberLastName', 'Relation as memberRelation', 'paxType as memberpaxType'));
        $select->joinLeft(array('tb14' => "TB_Master_Currency"), "tb8.CurrencyType = tb14.CurrencyType", 'Symbol as CurrencySymbol');

        $select->where('tb1.TPSysId = ?', $tpID);
        //$select->where('tb12.TPSysId = ?', $tpID);
        //        $select->where('tb7.TrxType = ?', $TrxType);
        $select->where('tb8.TrxType = ?', $TrxType);
        $select->where('tb8.TrxStatus = ?', 1);

        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetHotelBookingRooms($TPIntSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Accom_Invn_Mapping", array('RoomType', 'MealPlanType', 'Adult', 'Child', 'Infent', 'FromDate as RoomFromDate', 'ToDate as RoomToDate')));
        $select->joinLeft(array('tb10' => "TB_Master_RoomType"), "tb10.RoomType = tb1.RoomType", array('Title as RoomName'));
        $select->joinLeft(array('tb11' => 'TB_Master_Accom_MealType'), 'tb11.MealTypeId = tb1.MealPlanType', array("Title as MealPlanTypeTitle"));
        $select->where('tb1.TPIntSysId = ?', $TPIntSysId);
        $select->where('tb1.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // this function used for agency-leads controlles
    public function GetAgencyLeadList($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = NULL)
    {
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            $select->limit($limit);
        }
        $arrLeadSource = array('Title as LeadSource');
        $travelplanarray = array('*', "(select count(t2.TPSysId) FROM TB_Agency_Customer_TravelPlan t2 where tb1.TPSysId = t2.MasterTPSysId) as TotalProposal");
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        //		   $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId'));
        //filter conditions
        if (!empty($getData['customerName'])) {
            $select->Where('tb3.FirstName like ' . "'%" . $getData['customerName'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customerName'] . "%'" . ' ');
        }

        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            $select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
        } else {
            $select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where("tb1.AgentSysId IN (?)", explode(',', $AgentSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);


        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7, 8, 9, 10, 11)); // 1- for flight, 2-for hotel,5-for package,6-for visa,7-for forex,8- for activity,9-for sightseeing, 11-transfer,
        $select->order("tb1.UpdateDate DESC");
        //        echo $select;die;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        //$result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function GetAgencyLeadListCount($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('COUNT(TPSysId) AS TPSysId');
        $leadAgent_owner = array('');
        $leadAgentCreator = array('');
        $customerArray = array('');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        if (!empty($getData['IsDraft'])) {
            $select->Where(" tb1.IsDraft = '1' OR tb1.IsActive = '1' ");
        } else {
            $select->Where('tb1.IsActive = ?', 1);
        }
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', $AgentSysId) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : '';
        $select->Where('tb1.MasterTPSysId = ?', 0);
        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        //$select->Where('tb1.PlanType IN (?) ',array(1,2,5));
        // $select->order("tb1.UpdateDate DESC");
        // echo $select;exit;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // this function used for dashboard limit 5 controlles

    public function GetAgencyCustomerInsurance($tpintsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Insurance"));
        $select->where('tbl.TPIntSysId = ?', $tpintsysID);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAgencyCustomerInsuranceMember($customersysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_InsuMember"));
        $select->where('tbl.CustPolicySysId = ?', $customersysID);
        $select->where('tbl.IsMarkForDelete = ?', 0);
        // echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetActiveCustPolicyID($tpintsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Insurance"));
        $select->where('tbl.TPIntSysId = ?', $tpintsysID);
        $select->where('tbl.IsSelected = ?', 1);
        //  echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanDetailsofCustomer($tpID)
    {
        $select = $this->_dbObj->select();
        //        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId');
        $travelplanarray = array('TPSysId', 'AgencySysId', 'AgentSysId');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName', 'IsB2BAgent', 'Signature');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->where('tb1.TPSysId = ?', $tpID);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // for package proposal list created by Er Amit Kumar Dubey On 29 march 2017 at 12:53 PM
    public function GetPackageProposal($leadID)
    {
        $select = $this->_dbObj->select();
        $travel_array = array('TPSysId', 'MasterTPSysId', 'VersionId', 'ValidTill', 'PkgSellValidTill', 'CurrencyType', 'Cities as hotelCityTitle', 'DestinationPlaces', 'StatusType', 'PlanBookingId', 'RoomInfoJson', 'PlanType', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'DiscountVal', 'SupplierSysId', 'AdditionalReq', 'UpdateDate', 'Readymade', 'PackSpecType', 'Price', 'NetPrice', 'MarkUp', 'AgencyMarkUp', 'GTXMarkUp', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'PriceRange', 'IsPriceShared', 'TPId', 'EmailText', 'ProposalEmailTo', 'EmailDestination', 'AgentSysId', 'hasFollowUp', 'hasIteration', 'Cities', 'IsGTXNetwork', 'LeadQuality', 'BookingConversionRate', "((select sum(adT1.Tax) FROM TB_Agency_Customer_TravelPlan_AddonServices adT1 where adT1.IsMarkForDelete = '0' AND tb1.TPSysId = adT1.TPSysId AND (adT1.PlanType = 21 OR adT1.PlanType = 19))) as TotalTcs");
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'XrefBookingId', 'CurrencyType');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travel_array);
        // $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId" , $travel_itenary);
        // $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId" , $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tb1.AgentSysId", array(new Zend_Db_Expr('tb5.FirstName as ownerName'), 'Designation'));
        //                         $select->joinLeft(array('tb6' => "TB_Agency_Customer_ToDo"), "tb6.TPSysId = tb1.TPSysId" , array('ToDoSysId','Type as todoType')); // added by Ranvir Singh on 29 Sep 2017
        $select->joinLeft(array('tb7' => "TB_Master_LeadSource"), "tb7.LeadSourceSysId = tb1.LeadSourceSysId", array('Title as LeadSource'));
        $select->where('tb1.MasterTPSysId = ?', $leadID);
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order("tb1.TPSysId DESC");
        //$select->where("tb2.IsActive = ?", 1);
        //$select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        //$select->where("tb2.IsMarkForDel = ?", 0);
        //$select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetDuplicateCustomerMarketwiserateDate($packageId = NULL, $tripdate = NULL, $MarketPlaceId = NULL)
    {
        $whereCondition = " TPIntSysId = '" . @$packageId . "' AND IsMarkForDel = '0' AND IsActive = '1' AND  '$tripdate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) ";
        $select = $this->_dbObj->select()
            ->from(array("TBTPMWR" => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        if (!empty($MarketPlaceId)) {
            $select->where('MarketPlaceId = ?', $MarketPlaceId);
        }
        $select->where($whereCondition);
        //       echo $select; 
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getCustomerPackageMPRate($id)
    {
        $select = $this->_dbObj->select()
            ->from(array("tbl" => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"))
            ->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol')
            ->where('TPRateSheetSysId =?', @$id);
        //       echo $select; 
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getCustomerPackageRate($id)
    {
        $select = $this->_dbObj->select()
            ->from(array("tbl" => "TB_Agency_Customer_TravelPlan_Rate"))
            ->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol')
            ->where('TPRateSheetSysId =?', @$id);
        //       echo $select; 
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetCustomerTravelPlanMarketPrice($tpsysID, $tripDate = NULL, $marketPlaceId = NULL)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol');
        $select->where('tbl.TPIntSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        if (!empty($tripDate)) {
            $select->where("'$tripDate' BETWEEN CAST(tbl.FromDate AS DATE) AND CAST(tbl.ToDate AS DATE)");
        }
        if (!empty($marketPlaceId)) {
            $select->where('MarketPlaceId = ?', $marketPlaceId);
        }
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanRate($tpsysID, $tripDate = NULL, $marketPlaceId = NULL)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Rate"));
        $select->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol');
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', '0');
        if (!empty($tripDate)) {
            $select->where("'$tripDate' BETWEEN CAST(tbl.StartDate AS DATE) AND CAST(tbl.ValidTill AS DATE)");
        }
        if (!empty($marketPlaceId)) {
            $select->where('MarketPlaceId = ?', $marketPlaceId);
        }
        $select->where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanCustomerDetailsPax($tpID)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'IsfromAPI', 'TotalPax', 'Discounts', 'XrefBookingId', 'SpecialRequest', 'RoomTypeStr', 'MealPlanType', 'AllowBooking', 'RateType');
        $accom_details = array('Title as hotelName', 'ShortName', 'ResultIndex', 'TokenId', 'TraceId', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars');
        // $arrAccomdationInventory = array('Title as RoomType','SupplierSysId','NetDOccupCost','NetSOccupCost');
        $arrCancPolicy = array('RoomIndex as CANCELPOLICYroomIndex', 'ChargeType as CANCELPOLICYChargeType', 'Charge as CANCELPOLICYCharge', 'Fromdate as CANCELPOLICYFromdate', 'Todate as CANCELPOLICYTodate');
        $arrAccomRoomInfo = array('RoomNumber as ACCOMROOMRoomNumber', 'OtherDetails as ACCOMROOMOtherDetails', 'Title as ACCOMROOMTitle', 'HotelNorms as ACCOMROOMHotelNorms', 'Amenities as ACCOMROOMAmenities');
        $arrCustomerMembers = array('Title as MEMBERTitle', 'Title as MEMBERTitle', 'FirstName as MEMBERFirstName', 'LastName as MEMBERLastName');
        $arrCustomerMembersPax = array('TPPaxSysId');

        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation_API"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        //$select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.XRefAccoSysId = tb5.AccomSysId" , []);
        $select->joinLeft(array('tb7' => "TB_IC_Accomdation_Room_CancellationPolicy"), "tb7.Accosysid = tb3.AccoSysId AND tb7.RoomIndex = tb3.RoomIndex", $arrCancPolicy);
        $select->joinLeft(array('tb8' => "TB_IC_Accomdation_Room"), "tb8.AccomSysId = tb3.AccoSysId AND tb8.RoomIndex = tb3.RoomIndex AND tb8.RoomIndex = tb7.RoomIndex AND tb8.AccomSysId = tb7.Accosysid AND tb8.RoomNumber = tb7.RoomNumber", $arrAccomRoomInfo);
        $select->joinLeft(array('tb9' => "TB_Agency_Customer_Members"), "tb9.CustomerSysId = tb1.CustomerSysId", $arrCustomerMembers);
        $select->joinLeft(array('tb10' => "TB_Agency_Customer_TravelPlan_Pax"), "tb9.MemberSysId = tb10.MemberSysId", $arrCustomerMembersPax);


        //        $select->joinLeft(array('tb11' => 'TB_Master_RoomType'),'tb11.RoomType = tb6.EconomyType ',array("Title as EconomyTypeTitle","RoomType as RoomTypeId"));
        //        $select->joinLeft(array('tb12' => 'TB_Master_Accom_MealType'),'tb12.MealTypeId = tb6.MealPlanType',array("Title as MealPlanTypeTitle","MealTypeId"));




        $select->where('tb1.TPSysId = ?', $tpID);
        //$select->where('tb10.TPSysId = ?', $tpID);
        /* 			$select->where("tb1.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb4.IsActive = ?", 1);
          $select->where("tb5.IsActive = ?", 1);
          $select->where("tb6.IsActive = ?", 1);
          $select->where("tb1.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDel = ?", 0);
          $select->where("tb3.IsMarkForDel = ?", 0);
          $select->where("tb4.IsMarkForDelete = ?", 0);
          $select->where("tb5.IsMarkForDel = ?", 0);
          $select->where("tb6.IsMarkForDelete = ?", 0);
         */
        $select->order("tb10.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // for laste updated proposal created by Er Amit Kumar Dubey On 17 april 2017 at 03:10 PM
    public function GetProposalLastUpdateInfo($MasterTPSysId)
    {
        $select = $this->_dbObj->select();
        $travel_array = array('TPSysId', 'MasterTPSysId', 'VersionId', 'ValidTill', 'PkgSellValidTill', 'CurrencyType', 'Cities as hotelCityTitle', 'DestinationPlaces', 'StatusType', 'PlanBookingId', 'RoomInfoJson', 'PlanType', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'DiscountVal', 'SupplierSysId', 'AdditionalReq', 'UpdateDate', 'Readymade', 'PackSpecType', 'Price', 'NetPrice', 'MarkUp', 'AgencyMarkUp', 'GTXMarkUp', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'PriceRange');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travel_array);
        $select->limit(1);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->where('tb1.MasterTPSysId = ?', $MasterTPSysId);
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->order("tb1.UpdateDate DESC");
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetFlightproposalDetails($agencySysID, $leadId)
    {
        $travel = array('TPSysId', 'MasterTPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'AgentSysId', 'CreateDate', 'Price', 'TotalCost', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_air = array('InvnItemSysId', 'TPIntSysId', 'AdultPax', 'LocalFromTime as Departuredate', 'LocalToTime as returnDate', 'FlightCabinClass', 'ChildPax', 'InfentPax', 'SourceAirportCode', 'DestAirportCode');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Air"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_air);
        $select->where('tbl.AgencySysId = ?', $agencySysID);
        //$select->where('tbl.CustomerSysId = ?', $CRMCustSysId);
        $select->Where('tbl.StatusType > ?', 3);
        $select->order("tbl.TPSysId DESC");
        $select->where('tbl.TPSysId = ?', $leadId);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //get proposal listing status created by Er Amit Kumar Dubey on 2 may 2017 at 5:59 PM
    public function GetProposalStatusModuleComp($SubSystemType, $ModuleType)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Master_SubSystem_Module_Component"));
        $select->where('tb1.SubSystemType = ?', $SubSystemType);
        $select->where('tb1.ModuleType = ?', $ModuleType);
        $select->where('tb1.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //get proposal listing status by array created by Er Amit Kumar Dubey on 03 may 2017 at 11:41 AM
    public function GetProposalStatusModuleCompArray($SubSystemType, $ModuleType, $ComponentTypeIds)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Master_SubSystem_Module_Component"));
        $select->where('tb1.SubSystemType = ?', $SubSystemType);
        $select->where('tb1.ModuleType = ?', $ModuleType);
        $select->where('tb1.ComponentType IN(?)', $ComponentTypeIds);
        $select->where('tb1.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // for package proposal list created by Er Amit Kumar Dubey On 29 march 2017 at 12:53 PM
    public function GetPackageProposalById($leadID)
    {
        $select = $this->_dbObj->select();
        $travel_array = array('TPSysId', 'MasterTPSysId', 'VersionId', 'ValidTill', 'PkgSellValidTill', 'CurrencyType', 'Cities as hotelCityTitle', 'DestinationPlaces', 'StatusType', 'PlanBookingId', 'RoomInfoJson', 'PlanType', 'AgencySysId', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'DiscountVal', 'SupplierSysId', 'AdditionalReq', 'UpdateDate', 'Readymade', 'PackSpecType', 'Price', 'NetPrice', 'MarkUp', 'AgencyMarkUp', 'GTXMarkUp', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'PriceRange', 'IsPriceShared');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'XrefBookingId', 'CurrencyType');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travel_array);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->where('tb1.TPSysId = ?', $leadID);
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order("tb1.TPSysId DESC");
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetLeadMembersByIdArray($agencySysID, $CustomerSysId, $leadIds)
    {
        $members = array('EmailId', 'Title', 'Relation', 'Contacts', 'UserName', 'FirstName', 'LastName', 'DOB', 'Gender', 'AgeInYr');
        $paxArray = array('TPSysId');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => 'TB_Agency_Customer_Members'), $members);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tb2.MemberSysId = tbl.MemberSysId", $paxArray);
        $select->where("tbl.CustomerSysId = ?", $CustomerSysId);
        $select->where("tb2.CustomerSysId = ?", $CustomerSysId);
        $select->where('tbl.AgencySysId = ?', $agencySysID);
        $select->where('tb2.TPSysId IN(?)', $leadIds);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //plan detail with chat created by Er Amit Kumar Dubey on 15 may 2017 at 11:05 AM
    public function GetProposalCustomerChat($CustomerSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'MasterTPSysId', 'PlanBookingId', 'CreateDate', 'UpdateDate', 'CustomerSysId', 'PlanType', 'StatusType', 'Readymade', 'IsPriceShared', 'DestinationPlaces', 'Cities', 'RoomInfoJson');
        $customerarray = array('FirstName', 'LastName');
        $userinboxarray = array('UpdateDate as ChatUpdateDate', 'IsAgent');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId", $userinboxarray);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->where('tb1.CustomerSysId = ?', $CustomerSysId);
        $select->where('tb2.UserSysId= ' . $CustomerSysId . ' or tb2.SenderSysId= ' . $CustomerSysId . '');
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDelete = ?", 0);
        $select->order("tb2.UpdateDate DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    //plan detail with chat created by Er Amit Kumar Dubey on 15 may 2017 at 11:05 AM
    public function GetAllProposalsCustomerChat($AgencySysId, $AgentSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'MasterTPSysId', 'PlanBookingId', 'VersionId', 'CreateDate', 'UpdateDate', 'CustomerSysId', 'PlanType', 'StatusType', 'Readymade', 'IsPriceShared', 'DestinationPlaces', 'Cities', 'RoomInfoJson');
        $customerarray = array('FirstName', 'LastName', 'Title');
        $userinboxarray = array('UpdateDate as ChatUpdateDate', 'IsAgent');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId", $userinboxarray);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        //$select->where('tb2.UserSysId= '.$CustomerSysId.' or tb2.SenderSysId= '.$CustomerSysId.'');
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDelete = ?", 0);
        $select->where("tb1.MasterTPSysId != ?", 0);
        $select->order("tb2.UpdateDate DESC");
        //$result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function GetBookedAgencyLeadList($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = NULL, $isOnlyBooked = NULL)
    {
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            $select->limit($limit);
        }
        $travelplanarray = array('MasterTPSysId', 'IsDraft', 'DraftActiveTab', 'TPSysId', 'StatusType', 'RoomInfoJson', 'StartDate', 'ValidTill', 'PlanBookingId', 'PlanType', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'CreateDate', 'MinPax', 'SourcePlaceSysId', 'SourcePlaces', 'DestinationPlacesSysId', 'CityIds', 'DestinationPlaces', 'AdditionalReq', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'PlanBookingId', 'CuisineMask', 'HotelPreference');
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "CRMCustSysId", "AgencyCRMLeadSysId");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);

        //filter conditions
        if (!empty($getData['customerName'])) {
            $select->Where('tb3.FirstName like ' . "'%" . $getData['customerName'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customerName'] . "%'" . ' ');
        }

        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            $select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
        } else {
            $select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter

        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId = ?', $AgentSysId) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : '';
        //$select->Where('tb1.MasterTPSysId = ?', 0);


        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7)); // 1- for flight, 2-for hotel,5-for package
        $isOnlyBooked ? '' : $select->Where('tb1.StatusType IN (13,17)'); // 17 for booked,13 for partial payment
        $select->order("tb1.UpdateDate DESC");
        //           echo $select;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetHotelDetailsWithTravelPlan($TPSysId, $AccomSysId = NULL, $IsSelectedOnPkg = '')
    {
        $travel = array('TPSysId', 'NetPrice', 'Readymade');
        $travel_itenary = array('TPIntSysId', 'Cities as CityName', 'Sequence');
        $travel_accom = array('VersionId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'TotalCost', 'NetCost', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'GTXMarkup', 'AgencyMarkUp', 'MarkUp', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'Taxes', 'RoomTypeStr', 'SeqId', 'IsSelectedOnPkg', 'HoldDate');
        $customer_details = array('CRMCustSysId', 'EmailId');
        $supplier_details = array('SupplierSysId', 'SupplierName', 'Salution as SupplierSalution', 'FirstName as SupplierFirstName', 'LastName as SupplierLastName', 'EmailId as SupplierEmailId');
        $accom_details = array('Title as ICHotelTitle', 'Rating as ICHotelRating', 'Stars as ICHotelStars');
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Supplier"), "tb3.SupplierSysId = tb5.SupplierSysId", $supplier_details);
        $select->joinLeft(array('tb6' => "TB_IC_Accomdation"), "tb3.AccoSysId = tb6.AccomSysId", $accom_details);
        $select->joinLeft(array('tb7' => "TB_Master_RoomType"), "tb3.RoomType = tb7.RoomType", array('Title as RoomTitle'));
        $select->joinLeft(array('tb8' => "TB_Master_Accom_MealType"), "tb3.MealPlanType = tb8.MealTypeId", array('Title as RoomMealType'));
        $select->joinLeft(array('tb9' => "TB_Master_Currency"), "tb3.CurrencyType = tb9.CurrencyType", array('Symbol as CurrencySymbol'));
        $select->where('tb1.TPSysId = ?', $TPSysId);
        if ($AccomSysId) {
            $select->where('tb6.AccomSysId = ?', $AccomSysId);
            $select->where("tb3.IsActive = ?", 1);
            $select->where("tb3.IsMarkForDel = ?", 0);
        }
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);

        $select->where("tb4.IsActive = ?", 1);
        //$select->where("tb5.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);

        $select->where("tb4.IsMarkForDelete = ?", 0);
        
        if($IsSelectedOnPkg != ''){
            $select->where("tb3.IsSelectedOnPkg = ?", $IsSelectedOnPkg);
        }
        $select->order('tb2.Sequence ASC');
        $select->order('tb2.TotalMinDays ASC ');
        //$select->where("tb5.IsMarkForDelete = ?", 0);
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getAgentDetails($agentId)
    {
        $selectPersonalInfo = $this->_dbObj->select()
            ->from(array("TBAU" => "TB_Agency_User"))
            ->joinLeft(array('TBA' => 'TB_Agency'), 'TBAU.AgencySysId=TBA.AgencySysId', array('Logo', 'DisplayName', 'PrimaryEmail', 'Title', 'Url', 'IsB2CSite', 'IsB2CUrl', 'IsPaymentGateway', 'IsSiteType', 'SecurityKey', 'IsB2bSite', 'IsB2bSiteURL', 'IsDisplayHelloGTX', 'AgencyPhoto', 'TaxLabelId'))
            ->joinLeft(array('TBAM' => 'TB_Agency_Mapping'), 'TBAM.AgencySysId=TBA.AgencySysId', array('DefaultPDF', 'IsWhatsApp'))
            ->joinLeft(array('TBAUR' => 'TB_Agency_UserRoles'), 'TBAUR.RoleSysId=TBAU.UserRole', array('TBAUR.RoleTitle'))
            ->where("TBAU.UserSysId =? ", $agentId);
        //  echo $selectPersonalInfo; exit;
        $resultPersonalInfo = $this->_dbObj->fetchRow($selectPersonalInfo);
        return $resultPersonalInfo;
    }

    public function saveDynamicQueryData($requestPerameter)
    {
        try {
            //            $this->_dbObj->beginTransaction();
            $AgencySysId = $requestPerameter["AgencySysId"];
            $AgentSysId = !empty($requestPerameter["AgentSysId"]) ? $requestPerameter["AgentSysId"] : '';
            $IsFromGTXNetwork = $requestPerameter['IsFromGTXNetwork'] ? $requestPerameter['IsFromGTXNetwork'] : 0;  // Added By Pardeep Panchal For Sharing GTXNetwork Packages...
            $GTXNetworkAgencySysId = $requestPerameter['GTXNetworkAgencySysId'] ? $requestPerameter['GTXNetworkAgencySysId'] : 0;  // Added By Pardeep Panchal For Sharing GTXNetwork Packages...
            $travelplanID = $requestPerameter["TravelPlanId"];
            $custname = $fname = $requestPerameter["FirstName"];
            $lname = @$requestPerameter["LastName"];
            $custemail = $email = $requestPerameter["Email"];
            $mobilenum = $requestPerameter["MobileNumber"];
            $createDate = $updatedate = date('Y-m-d H:i:s');
            $planbookingID = 'Q/' . date('y');
            $salution = "";

            //$pricerange = $requestPerameter['PriceRange'] ? $requestPerameter['PriceRange'] : '';   
            $CRMCustSysId = "";
            $pkgCheckInDate = @$requestPerameter['pkgCheckInDate'];
            $pkgCheckOutDate = @$requestPerameter['pkgCheckOutDate'];
            $min_price = @$requestPerameter['MinPrice'] ? $requestPerameter['MinPrice'] : '0';
            $max_price = @$requestPerameter['MaxPrice'] ? $requestPerameter['MaxPrice'] : '0';
            //$totadlt = $requestPerameter['totadlt'] ? $requestPerameter['totadlt'] : '';
            //$totchld = $requestPerameter['totchld'] ? $requestPerameter['totchld'] : '';
            $roomlp = !empty($requestPerameter['roomlp']) ? $requestPerameter['roomlp'] : '';
            $aboutpackage = !empty($requestPerameter['aboutpackage']) ? $requestPerameter['aboutpackage'] : '';
            $tripaddress = !empty($requestPerameter['tripaddress']) ? $requestPerameter['tripaddress'] : '';
            $cardcharges = !empty($requestPerameter['cardcharges']) ? $requestPerameter['cardcharges'] : 1;
            $MarkupArray = !empty($requestPerameter['MarkUp']) ? $requestPerameter['MarkUp'] : 0;
            $discountValue = !empty($requestPerameter['discountValue']) ? $requestPerameter['discountValue'] : 0;
            $IsShareWithGST = isset($requestPerameter['GSTIncluded']) ? $requestPerameter['GSTIncluded'] : 0;
            $AgencyMarkUp = !empty($requestPerameter['AgencyMarkUp1']) ? $requestPerameter['AgencyMarkUp1'] : 0;
            $Price = !empty($requestPerameter['Price']) ? $requestPerameter['Price'] : 0;
            $StaxDiscount = !empty($requestPerameter['StaxDiscount1']) ? $requestPerameter['StaxDiscount1'] : 0;
            $StaxMarkUp = !empty($requestPerameter['StaxMarkUp1']) ? $requestPerameter['StaxMarkUp1'] : 0;
            $XServiceTaxAmount = !empty($requestPerameter['XServiceTaxAmount']) ? $requestPerameter['XServiceTaxAmount'] : 0;
            $NetPrice = !empty($requestPerameter['NetPrice']) ? $requestPerameter['NetPrice'] : 0;
            $catID = !empty($requestPerameter['catID']) ? $requestPerameter['catID'] : 1;
            $tourID = !empty($requestPerameter['tourID']) ? $requestPerameter['tourID'] : 1;
            $MealTypeId = !empty($requestPerameter['mID']) ? $requestPerameter['mID'] : 0;
            $SACCode = !empty($requestPerameter['sac_code']) ? $requestPerameter['sac_code'] : 440063; // default value 440063 for Tour Oprators..
            $gsttype = !empty($requestPerameter['gsttype']) ? $requestPerameter['gsttype'] : 1;
            $queryTPSysId = !empty($requestPerameter['queryTPSysId']) ? $requestPerameter['queryTPSysId'] : '';
            $search_going_to = !empty($requestPerameter['search_going_to']) ? $requestPerameter['search_going_to'] : '';
            $IsB2BCustomer = !empty($requestPerameter['IsB2BCustomer']) ? $requestPerameter['IsB2BCustomer'] : 0;
            $IsB2BAgent = isset($requestPerameter['IsB2BAgent']) ? $requestPerameter['IsB2BAgent'] : 0;
            $aId = !empty($requestPerameter['aId']) ? $requestPerameter['aId'] : ''; //b2b agent id
            $EmailTemplateType = isset($requestPerameter['EmailTemplateType']) ? $requestPerameter['EmailTemplateType'] : 2;
            $EmailTemplateColor = isset($requestPerameter['EmailTemplateColor']) ? $requestPerameter['EmailTemplateColor'] : '';
            $AgencyCRMLeadSysId = isset($requestPerameter['leadID']) ? (int) $requestPerameter['leadID'] : 0;
            $going_from_cityid = (int) $requestPerameter['FromDestinationId'];
            $going_from_cityname = trim($requestPerameter['FromDestination']);
            $SelectPricingType = isset($requestPerameter['SelectPricing']) ? $requestPerameter['SelectPricing'] : 'OverAll';
            $PackageCostCalType = isset($requestPerameter['PackageCostCalType']) ? $requestPerameter['PackageCostCalType'] : 0;
            if ($going_from_cityid == 0) {
                $going_from_cityid = '';
            }
            $leadsourceTitle = isset($requestPerameter['leadsource']) ? (trim($requestPerameter['leadsource'])) : 'Agency';
            $intLeadSourceSysId = $this->_crmcustomerObj->getLeadSource($AgencySysId, $leadsourceTitle); // for Master LeadSouce Creation
            //echo "<pre>";print_r($intLeadSourceSysId);exit;
            $leadsource = (isset($intLeadSourceSysId[0]['LeadSourceSysId']) && !empty($intLeadSourceSysId[0]['LeadSourceSysId'])) ? $intLeadSourceSysId[0]['LeadSourceSysId'] : 0;
            if ($IsB2BCustomer == 1) {
                $MarketPlaceId = 2;
            } else {
                $MarketPlaceId = 1;
            }
            if (!empty($search_going_to)) {
                $search_going_to_dest = explode('__', $search_going_to);
                $going_to_cityname = $search_going_to_dest[1];
                $going_to_cityid = $search_going_to_dest[0];
            }
            $roominfojsonArr = json_decode($requestPerameter['roomjson'], 1);
            $totalchild = 0;
            $totaladult = 0;
            $totalInfant = 0;
            $totalpax = 0;
            for ($k = 1; $k <= count($roominfojsonArr); $k++) {
                $totaladult = $totaladult + $roominfojsonArr[$k]['Adult'];
                $totalchild = $totalchild + $roominfojsonArr[$k]['Child'];
                $totalInfant = $totalInfant + $roominfojsonArr[$k]['Infant'];
            }
            $totalpax = $totaladult + $totalchild + $totalInfant;
            $destPlaceArr = isset($requestPerameter['DestinationPlaces']) ? json_decode(base64_decode($requestPerameter['DestinationPlaces']), true) : '';
            //        print_r($destPlaceArr);
            if (isset($destPlaceArr) && !empty($destPlaceArr)) {
                foreach ($destPlaceArr as $destIds => $destValues) {
                    $destIdsArr[] = $destIds;
                    $destValuesArr[] = $destValues;
                }
                $destinationIds = implode(', ', $destIdsArr);
                $destinationValues = implode(', ', $destValuesArr);
            }

            if (!empty($pkgCheckInDate)) {
                $explode_trip_start = explode('/', $pkgCheckInDate);
                $main_trip_start_date = $explode_trip_start[2] . '-' . $explode_trip_start[1] . '-' . $explode_trip_start[0];
            } else {
                $main_trip_start_date = date('Y-m-d');
                $pkgCheckInDate = date("d/m/Y");
            }
            if (!empty($pkgCheckOutDate)) {
                $explode_trip_start = explode('/', $pkgCheckOutDate);
                $main_trip_end_date = $explode_trip_start[2] . '-' . $explode_trip_start[1] . '-' . $explode_trip_start[0];
                if (strtotime($main_trip_end_date) < strtotime(date('Y-m-d'))) {
                    $main_trip_end_date = $main_trip_start_date;
                }
            } else {
                $main_trip_end_date = date('Y-m-d');
                $pkgCheckOutDate = date("d/m/Y");
            }
            $objPackage = new Travel_Model_TblPackage();
            $inventory = $objPackage->getFromDestinationFixedInventoryByDateAndDestination($travelplanID, $main_trip_start_date, $going_from_cityid);
            try {
                $travelplandata = $this->GetTravelPlan($travelplanID);
                $PkgSellValidTill = $travelplandata[0]['PkgSellValidTill'];
            } catch (Zend_Exception $e) {
                $error_Message = $e->getMessage();
            }

            $AgentSysId = !empty($AgentSysId) ? $AgentSysId : $travelplandata[0]['AgentSysId'];

            ######******************************Start Check user in system *************************************** */

            if (empty($queryTPSysId)) {

                if (isset($email) && !empty($email)) {
                    try {
                        if ($aId != '' || $IsB2BCustomer == 1 || $IsB2BAgent == 1) {
                            if ($aId != '') {
                                $customerDetailsEmail = $this->_crmcustomerObj->ChkEmailWithResponseUpdateB2B($email, $aId);
                            } else {
                                $customerDetailsEmail = $this->_crmcustomerObj->ChkEmailWithResponseB2B($email, $AgencySysId);
                            }
                        } else {
                            $customerDetailsEmail = $this->_crmcustomerObj->ChkEmailWithResponseUpdate($email, $AgencySysId);
                        }
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
                if (isset($mobilenum) && !empty($mobilenum)) {
                    try {
                        if ($aId != '' || $IsB2BCustomer == 1 || $IsB2BAgent == 1) {
                            if ($aId != '') {
                                $customerDetailsMobile = $this->_crmcustomerObj->ChkMobileWithResponseB2B($mobilenum, $aId, '', $CRMCustSysId);
                            } else {
                                $customerDetailsMobile = $this->_crmcustomerObj->ChkMobileExistInAgencyB2B($mobilenum, $AgencySysId);
                            }
                        } else {
                            $customerDetailsMobile = $this->_crmcustomerObj->ChkMobileWithResponse($mobilenum, $AgencySysId, '', $CRMCustSysId);
                        }
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
                //echo '<pre>';print_r($customerDetailsEmail); die;
                if (!empty($customerDetailsEmail) || !empty($customerDetailsMobile)) {
                    $status = 'success';
                    $CustomerSysId = $customerDetailsEmail['CustomerSysId'] ? $customerDetailsEmail['CustomerSysId'] : $customerDetailsMobile['CustomerSysId'];
                    $CRMCustSysId = $customerDetailsEmail['CRMCustSysId'] ? $customerDetailsEmail['CRMCustSysId'] : $customerDetailsMobile['CRMCustSysId'];
                } else {
                    $status = 'failure';
                    $CRMCustSysId = '';
                }
                ########************************************End Check user in system ********************************* */
                ########************************************ If user not exist in system then insert****************** */

                if ($status == 'failure' || $CustomerSysId == '') {
                    if ($CRMCustSysId == '') {
                        $userArray = array(
                            'EmailId' => $email,
                            'Salutation' => 1,
                            'PrimaryContactNumber' => '',
                            'FullName' => $fname . ' ' . $lname,
                            'FirstName' => $fname,
                            'LastName' => $lname ? $lname : '',
                            'ActiveDate' => $updatedate,
                            'UpdatedDate' => $updatedate,
                            'CreatedDate' => $updatedate,
                            'IsApproved' => '1',
                            'IsActive' => '1',
                            'IsMarkForDelete' => '0'
                        );
                        $CRMCustSysId = $this->_crmcustomerObj->addCustomer($userArray);
                    }
                    //for create new customer
                    $userLeadArray = array(
                        'AgencySysId' => $AgencySysId,
                        'EmailId' => $email,
                        'Salutation' => $salution ? $salution : 0,
                        'PrimaryContactNumber' => $mobilenum ? $mobilenum : '',
                        'FullName' => $fname . ' ' . $lname,
                        'FirstName' => $fname ? $fname : '',
                        'LastName' => $lname ? $lname : '',
                        'LeadSourceSysId' => $leadsource,
                        'LeadStageSysId' => "",
                        'AssignUserSysId' => '',
                        'ActiveDate' => $updatedate,
                        'UpdatedDate' => $updatedate,
                        'CreatedDate' => $updatedate,
                        'IsApproved' => '1',
                        'IsActive' => '1',
                        'IsMarkForDelete' => '0'
                    );
                    //for create new customer
                    if ((int) $AgencyCRMLeadSysId > 0) {
                        $AgencyCRMLeadSysId = $AgencyCRMLeadSysId;
                    } else {
                        $AgencyCRMLeadSysId = $this->_crmagencyleadaccountObj->addCustomer($userLeadArray);
                    }
                    $agencyuserArray = array(
                        'AgencySysId' => $AgencySysId,
                        'AgencyCRMLeadSysId' => $AgencyCRMLeadSysId,
                        'CRMCustSysId' => $CRMCustSysId,
                        'EmailId' => $email,
                        'Title' => $salution ? $salution : 0,
                        'Logo' => '',
                        'IsfromSM' => '0',
                        'UserId' => '0',
                        'CitySysId' => '',
                        'StateOrZoneSysId' => 0,
                        'CountrySysId' => '',
                        'IsEmployee' => '0',
                        'Contacts' => $mobilenum ? $mobilenum : '',
                        'JoinDate' => $updatedate,
                        'UserName' => $fname . '' . $lname,
                        'FirstName' => $fname ? $fname : '',
                        'LastName' => $lname ? $lname : '',
                        'Relation' => '',
                        'PassportNo' => '',
                        'PassportExpiry' => '',
                        'DOB' => '',
                        'MarriageAnniversary' => '',
                        'CreatedByUserSysId' => '',
                        'RegisterDate' => $updatedate,
                        'UpdateDate' => $updatedate,
                        'IsApproved' => '0',
                        'IsActive' => '1',
                        'IsMarkForDelete' => '0'
                    );
                    ### Insert Record in to Agency Table as well ########
                    $CustomerSysId = $this->_agencycustomerObj->addAgencyCustomer($agencyuserArray);
                }


                //print_r($requestPerameter);die;
                $customertravelpaln = array(
                    'PlanBookingId' => $planbookingID,
                    'MasterTPSysId' => '',
                    'AgencySysId' => $AgencySysId,
                    'AgentSysId' => $AgentSysId,
                    'CreatorSysId' => !empty($AgentSysId) ? $AgentSysId : $travelplandata[0]['AgentSysId'],
                    'StatusType' => 2,
                    'CustomerSysId' => $CustomerSysId,
                    'PlanType' => 5,
                    'InventoryType' => 5,
                    'MinPax' => $travelplandata[0]['MinPax'] ? $travelplandata[0]['MinPax'] : 0,
                    'PackRangeType' => $travelplandata[0]['PackRangeType'] ? $travelplandata[0]['PackRangeType'] : 0,
                    'Title' => $travelplandata[0]['Title'] ? $travelplandata[0]['Title'] : '',
                    'EconomyMask' => !empty($catID) ? $catID : 1,
                    'BYOPackTypeMask' => $travelplandata[0]['BYOPackTypeMask'] ? $travelplandata[0]['BYOPackTypeMask'] : '',
                    'PackTypeMask' => '',
                    'InclCatMask' => $travelplandata[0]['InclCatMask'] ? $travelplandata[0]['InclCatMask'] : 0,
                    'InclMask' => '',
                    'ExclusionMask' => $travelplandata[0]['ExclusionMask'] ? $travelplandata[0]['ExclusionMask'] : '',
                    'PackSpecType' => $travelplandata[0]['PackSpecType'] ? $travelplandata[0]['PackSpecType'] : '',
                    'SupplierSysId' => isset($travelplandata[0]['SupplierSysId']) ? $travelplandata[0]['SupplierSysId'] : '0',
                    'PriceRange' => 0,
                    'SeasonMask' => $travelplandata[0]['SeasonMask'] ? $travelplandata[0]['SeasonMask'] : 0,
                    'GeoType' => $travelplandata[0]['GeoType'] ? $travelplandata[0]['GeoType'] : 0,
                    'IsFixDatePlan' => $travelplandata[0]['IsFixDatePlan'] ? $travelplandata[0]['IsFixDatePlan'] : 0,
                    'IsFixPlan' => $travelplandata[0]['IsFixPlan'] ? $travelplandata[0]['IsFixPlan'] : 0,
                    'Details' => $travelplandata[0]['Details'] ? $travelplandata[0]['Details'] : '',
                    'ImageTN' => $travelplandata[0]['ImageTN'] ? $travelplandata[0]['ImageTN'] : '',
                    'ImgForList' => $travelplandata[0]['ImgForList'] ? $travelplandata[0]['ImgForList'] : '',
                    'ImgeDetails' => $travelplandata[0]['ImgeDetails'] ? $travelplandata[0]['ImgeDetails'] : '',
                    'StartDate' => $main_trip_start_date,
                    'ValidTill' => $main_trip_end_date ? $main_trip_end_date : '',
                    'PkgSellValidTill' => $PkgSellValidTill ? $PkgSellValidTill->format('Y-m-d') : '',
                    'Price' => $travelplandata[0]['Price'] ? $travelplandata[0]['Price'] : 0,
                    'CurrencyType' => $travelplandata[0]['CurrencyType'] ? $travelplandata[0]['CurrencyType'] : 0,
                    'DiscountMsg' => $travelplandata[0]['DiscountMsg'] ? $travelplandata[0]['DiscountMsg'] : '',
                    'DiscountType' => $travelplandata[0]['DiscountType'] ? $travelplandata[0]['DiscountType'] : 0,
                    'DiscountVal' => $travelplandata[0]['DiscountVal'] ? $travelplandata[0]['DiscountVal'] : 0,
                    'AdvBookingPercent' => $travelplandata[0]['AdvBookingPercent'] ? $travelplandata[0]['AdvBookingPercent'] : 0,
                    'AdvBookingDays' => $travelplandata[0]['AdvBookingDays'] ? $travelplandata[0]['AdvBookingDays'] : 0,
                    'NetPrice' => $travelplandata[0]['NetPrice'] ? $travelplandata[0]['NetPrice'] : 0,
                    'MinPrice' => $min_price ? $min_price : 0,
                    'MaxPrice' => $max_price ? $max_price : 0,
                    'TotalMinDays' => $travelplandata[0]['TotalMinDays'] ? $travelplandata[0]['TotalMinDays'] : 0,
                    'TotalMaxDays' => $travelplandata[0]['TotalMaxDays'] ? $travelplandata[0]['TotalMaxDays'] : 0,
                    'Hotels' => $travelplandata[0]['Hotels'] ? $travelplandata[0]['Hotels'] : '',
                    'PopularPlaces' => $travelplandata[0]['PopularPlaces'] ? $travelplandata[0]['PopularPlaces'] : '',
                    'SourcePlaceSysId' => isset($travelplandata[0]['SourcePlaceSysId']) ? $travelplandata[0]['SourcePlaceSysId'] : '',
                    'SourcePlaces' => isset($travelplandata[0]['SourcePlaces']) ? $travelplandata[0]['SourcePlaces'] : '',
                    'DestinationPlacesSysId' => (isset($going_to_cityid) && !empty($going_to_cityid)) ? $going_to_cityid : (int)$destinationIds,
                    'DestinationPlaces' => (isset($going_to_cityname) && !empty($going_to_cityname)) ? $going_to_cityname : $destinationValues,
                    'CityIds' => $destinationIds ? $destinationIds : '',
                    'Cities' => $destinationValues ? $destinationValues : '',
                    'Countries' => $travelplandata[0]['Countries'] ? $travelplandata[0]['Countries'] : '',
                    'IsMarkForDel' => $travelplandata[0]['IsMarkForDel'] ? $travelplandata[0]['IsMarkForDel'] : '0',
                    'DestinationCovered' => $travelplandata[0]['DestinationCovered'] ? $travelplandata[0]['DestinationCovered'] : '0',
                    'RoomInfoJson' => $requestPerameter['roomjson'] ? $requestPerameter['roomjson'] : '',
                    'GreetingMessage' => $aboutpackage ? substr($aboutpackage, 0, 4000) : '',
                    'EmailText' => '',
                    'EmailDestination' => $destinationValues ? $destinationValues : '',
                    'ProposalEmailTo' => trim($email),
                    'CreateDate' => $createDate,
                    'UpdateDate' => $createDate,
                    'IsActive' => 1,
                    'Readymade' => 2, // for dynamic package
                    'IsAprooved' => 1,
                    'TPId' => $travelplandata[0]['TPSysId'],
                    'IsPriceShared' => 1, // to detect withprice or without price true = If price shared , false = price range shared
                    'TourType' => $tourID,
                    'GSTSharedMode' => $gsttype, // (1 for 5% on total Cost, 2 for 18% on Service Fee) to detect what type and how much tax will apply to customer
                    'SACCode' => $SACCode,
                    'LeadSourceSysId' => $leadsource,
                    'PackageCostCalType' => !empty($travelplandata[0]['PackageCostCalType']) ? $travelplandata[0]['PackageCostCalType'] : $PackageCostCalType, // to detect package is by lowest cost or by meal plan
                    'B2BAgencySysId' => trim($GTXNetworkAgencySysId),
                    'SharedMealPlanType' => $MealTypeId, // shared meal plan id 
                    'IsB2Bproposal' => trim($IsB2BCustomer) ? trim($IsB2BCustomer) : '0',
                    'IsGTXNetwork' => $IsFromGTXNetwork,
                    'EmailTemplateType' => !empty($EmailTemplateType) ? $EmailTemplateType : '1',
                    'EmailTemplateColor' => !empty($EmailTemplateColor) ? $EmailTemplateColor : '',
                    'IsShareWithGST' => $IsShareWithGST,
                    'ProposalEmailFrom' => '',
                    'LeadSysId' => (int) $AgencyCRMLeadSysId
                );
                try {
                    $where = "AgencyCRMLeadSysId = " . $AgencyCRMLeadSysId;
                    $userArray = array(
                        'IsApproved' => '1',
                        'UpdatedDate' => $createDate,
                        'LeadStageSysId' => 50
                    );
                    $this->_crmagencyleadaccountObj->UpdateGtxCrmCustomer($userArray, $where);
                    $leadID = $this->addCustomerTravelPlanQuery($customertravelpaln);
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
            } else {
                $leadID = $queryTPSysId;
                $where = "TPSysId = " . $leadID;
                $updatetravelplan = array(
                    'UpdateDate' => $createDate,
                    'Readymade' => 2,
                    'StatusType' => 2,
                    'B2BAgencySysId' => (int) $GTXNetworkAgencySysId,
                    'IsOperationalLead' => 0,
                    'ExpectedClosureDate' => $main_trip_start_date,
                    'ExpectedValue' => $NetPrice ? round($NetPrice, 2) : 0,
                );
                try {
                    $updatetravelPlan = $this->UpdateCustomerTravelPlanQuery($updatetravelplan, $where);
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
                $gettplandataforcustomer = $this->GetTravelPlanByCustomer($leadID, 'Query');
                $CustomerSysId = $gettplandataforcustomer[0]['CustomerSysId'];
            }


            $VersionIdDetails = $this->GetLatestVersionID($leadID);
            $VersionId = (!empty($VersionIdDetails)) ? $VersionIdDetails[0]['VersionId'] + 1 : 1;
            $agentDetails = $this->getAgentDetails($AgentSysId);
            $sendersEmailId = $agentDetails['EmailId'];
            $proposalEmailFrom = $requestPerameter['senderEmailID'] ? trim($requestPerameter['senderEmailID']) : trim($sendersEmailId);

            $customertravelpalnProposal12 = array(
                'VersionId' => $VersionId,
                'PlanBookingId' => $planbookingID,
                'MasterTPSysId' => $leadID,
                'AgencySysId' => $AgencySysId,
                'AgentSysId' => !empty($AgentSysId) ? $AgentSysId : $travelplandata[0]['AgentSysId'],
                'CreatorSysId' => !empty($AgentSysId) ? $AgentSysId : $travelplandata[0]['AgentSysId'],
                'StatusType' => 4,
                'CustomerSysId' => $CustomerSysId,
                'PlanType' => 5,
                'InventoryType' => 5,
                'MinPax' => $travelplandata[0]['MinPax'] ? $travelplandata[0]['MinPax'] : 0,
                'PackRangeType' => $travelplandata[0]['PackRangeType'] ? $travelplandata[0]['PackRangeType'] : 0,
                'Title' => $travelplandata[0]['Title'] ? $travelplandata[0]['Title'] : '',
                'EconomyMask' => !empty($catID) ? $catID : 1,
                'PackTypeMask' => $travelplandata[0]['PackTypeMask'] ? $travelplandata[0]['PackTypeMask'] : '',
                'InclCatMask' => $travelplandata[0]['InclCatMask'] ? $travelplandata[0]['InclCatMask'] : 0,
                'InclMask' => $travelplandata[0]['InclMask'] ? $travelplandata[0]['InclMask'] : '',
                'ExclusionMask' => $travelplandata[0]['ExclusionMask'] ? $travelplandata[0]['ExclusionMask'] : '',
                'PackSpecType' => $travelplandata[0]['PackSpecType'] ? $travelplandata[0]['PackSpecType'] : '',
                'SupplierSysId' => isset($travelplandata[0]['SupplierSysId']) ? $travelplandata[0]['SupplierSysId'] : '0',
                'PriceRange' => 0,
                'Readymade' => 2,
                'SeasonMask' => $travelplandata[0]['SeasonMask'] ? $travelplandata[0]['SeasonMask'] : 0,
                'GeoType' => $travelplandata[0]['GeoType'] ? $travelplandata[0]['GeoType'] : 0,
                'IsFixDatePlan' => $travelplandata[0]['IsFixDatePlan'] ? $travelplandata[0]['IsFixDatePlan'] : 0,
                'IsFixPlan' => $travelplandata[0]['IsFixPlan'] ? $travelplandata[0]['IsFixPlan'] : 0,
                'Details' => $travelplandata[0]['Details'] ? $travelplandata[0]['Details'] : '',
                'ImageTN' => $travelplandata[0]['ImageTN'] ? $travelplandata[0]['ImageTN'] : '',
                'ImgForList' => $travelplandata[0]['ImgForList'] ? $travelplandata[0]['ImgForList'] : '',
                'ImgeDetails' => $travelplandata[0]['ImgeDetails'] ? $travelplandata[0]['ImgeDetails'] : '',
                'StartDate' => $main_trip_start_date,
                'ValidTill' => $main_trip_end_date ? $main_trip_end_date : '',
                'PkgSellValidTill' => $PkgSellValidTill ? $PkgSellValidTill->format('Y-m-d') : '',
                'CurrencyType' => $travelplandata[0]['CurrencyType'] ? $travelplandata[0]['CurrencyType'] : 0,
                'DiscountMsg' => $travelplandata[0]['DiscountMsg'] ? $travelplandata[0]['DiscountMsg'] : '',
                'DiscountType' => $travelplandata[0]['DiscountType'] ? $travelplandata[0]['DiscountType'] : 0,
                'AdvBookingPercent' => $travelplandata[0]['AdvBookingPercent'] ? $travelplandata[0]['AdvBookingPercent'] : 0,
                'AdvBookingDays' => $travelplandata[0]['AdvBookingDays'] ? $travelplandata[0]['AdvBookingDays'] : 0,
                'Price' => $Price ? $Price : 0,
                'NetPrice' => $NetPrice ? $NetPrice : 0,
                'DiscountVal' => $travelplandata[0]['DiscountVal'] ? $travelplandata[0]['DiscountVal'] : 0,
                'CustomDiscount' => ($discountValue[0] > 0) ? $discountValue[0] : 0,
                'AgentsCustomServiceTaxAmount' => $StaxMarkUp ? $StaxMarkUp : 0,
                'ServiceTaxOnCustomDiscount' => $StaxDiscount ? $StaxDiscount : 0,
                'MarkUp' => ($MarkupArray[0] > 0) ? $MarkupArray[0] : 0,
                'AgencyMarkUp' => $AgencyMarkUp ? $AgencyMarkUp : 0,
                'XServiceTaxAmount' => $XServiceTaxAmount,
                'GTXServiceTaxAmount' => 0,
                'AgentServiceTaxAmount' => 0,
                'GTXMarkup' => 0,
                'MinPrice' => $travelplandata[0]['MinPrice'] ? $travelplandata[0]['MinPrice'] : 0,
                'IsCardChrgToCustomer' => $cardcharges,
                'TotalMinDays' => $travelplandata[0]['TotalMinDays'] ? $travelplandata[0]['TotalMinDays'] : 0,
                'TotalMaxDays' => $travelplandata[0]['TotalMaxDays'] ? $travelplandata[0]['TotalMaxDays'] : 0,
                'Hotels' => $travelplandata[0]['Hotels'] ? $travelplandata[0]['Hotels'] : '',
                'PopularPlaces' => $travelplandata[0]['PopularPlaces'] ? $travelplandata[0]['PopularPlaces'] : '',
                'SourcePlaceSysId' => isset($travelplandata[0]['SourcePlaceSysId']) ? $travelplandata[0]['SourcePlaceSysId'] : '',
                'SourcePlaces' => isset($travelplandata[0]['SourcePlaces']) ? $travelplandata[0]['SourcePlaces'] : '',
                'DestinationPlacesSysId' => (isset($going_to_cityid) && !empty($going_to_cityid)) ? $going_to_cityid : (int)$destinationIds,
                'DestinationPlaces' => (isset($going_to_cityname) && !empty($going_to_cityname)) ? $going_to_cityname : trim($destinationValues),
                'CityIds' => $destinationIds ? $destinationIds : '',
                'Cities' => $destinationValues ? $destinationValues : '',
                'Countries' => $travelplandata[0]['Countries'] ? $travelplandata[0]['Countries'] : '',
                'IsMarkForDel' => $travelplandata[0]['IsMarkForDel'] ? $travelplandata[0]['IsMarkForDel'] : '0',
                'RoomInfoJson' => $requestPerameter['roomjson'] ? $requestPerameter['roomjson'] : '',
                'CreateDate' => $createDate,
                'UpdateDate' => $createDate,
                'IsActive' => 1,
                'IsAprooved' => 1,
                'IsMarkForDel' => $travelplandata[0]['IsMarkForDel'] ? $travelplandata[0]['IsMarkForDel'] : '0',
                'TPId' => $travelplandata[0]['TPSysId'],
                'IsPriceShared' => 1, // to detect withprice or without price true = If price shared , false = price range shared
                'GreetingMessage' => $aboutpackage ? substr($aboutpackage, 0, 4000) : '',
                'EmailText' => '',
                'EmailDestination' => $tripaddress,
                'ProposalEmailTo' => trim($custemail),
                'IsShared' => 1,
                // 'TourType' => $travelplandata[0]['TourType'] ? $travelplandata[0]['TourType'] : '',
                'GroupSize' => $travelplandata[0]['GroupSize'] ? $travelplandata[0]['GroupSize'] : '',
                'IsInsuranceExist' => $travelplandata[0]['TravelInsurance'] ? $travelplandata[0]['TravelInsurance'] : '',
                'BYOPackTypeMask' => $travelplandata[0]['BYOPackTypeMask'] ? $travelplandata[0]['BYOPackTypeMask'] : '',
                'PackSpecType' => 3,
                'TourType' => $tourID,
                'IsFixDatePlan' => $travelplandata[0]['IsFixDatePlan'] ? $travelplandata[0]['IsFixDatePlan'] : '',
                'GSTSharedMode' => $gsttype, // (1 for 5% on total Cost, 2 for 18% on Service Fee) to detect what type and how much tax will apply to customer
                'SACCode' => $SACCode,
                'PackageCostCalType' => !empty($travelplandata[0]['PackageCostCalType']) ? $travelplandata[0]['PackageCostCalType'] : $PackageCostCalType, // to detect package is by lowest cost or by meal plan
                'B2BAgencySysId' => trim($GTXNetworkAgencySysId),
                'SharedMealPlanType' => $MealTypeId, // shared meal plan id 
                'LeadSourceSysId' => $leadsource,
                'IsB2Bproposal' => trim($IsB2BCustomer) ? trim($IsB2BCustomer) : '0',
                'IsGTXNetwork' => $IsFromGTXNetwork,
                'DestinationCovered' => $travelplandata[0]['DestinationCovered'] ? $travelplandata[0]['DestinationCovered'] : '0',
                'EmailTemplateType' => !empty($EmailTemplateType) ? $EmailTemplateType : '1',
                'EmailTemplateColor' => !empty($EmailTemplateColor) ? $EmailTemplateColor : '',
                'IsShareWithGST' => $IsShareWithGST,
                'ProposalEmailFrom' => $proposalEmailFrom,
                'LeadSysId' => (int) $AgencyCRMLeadSysId,
                'SelectPricingType' => $SelectPricingType
            );
            //echo "<pre>";print_r($customertravelpalnProposal12);die;
            try {
                $tpproposalID = $this->addCustomerTravelPlan($customertravelpalnProposal12);
                //after send proposal updated cusomer updatedon date
                if (!empty($tpproposalID)) {
                    $agencyuserArray = array(
                        'UpdateDate' => $createDate
                    );
                    $whereAgencyCustomer = " AgencySysId=" . $AgencySysId . " AND CustomerSysId=" . $CustomerSysId . "";
                    $agencyCustomerData = $this->_agencycustomerObj->UpdateAgencyCustomer($agencyuserArray, $whereAgencyCustomer);
                }
            } catch (Zend_Exception $e) {
                $error_Message = $e->getMessage();
            }


            ##################################################################
            $travelplanIetnaryData = $this->GetTravelPlanItenary($travelplanID);
            $travelpanitenary = array_column($travelplanIetnaryData, 'TPIntSysId');
            $tplanitenayvalues = implode(', ', $travelpanitenary);
            $ItenaryDataForHotel = array();
            for ($i = 0; $i < count($travelplanIetnaryData); $i++) {
                $TotalMinDays =  $travelplanIetnaryData[$i]['TotalMinDays'] ? $travelplanIetnaryData[$i]['TotalMinDays'] : 0;
                $TotalMaxDays =  $travelplanIetnaryData[$i]['TotalMaxDays'] ? $travelplanIetnaryData[$i]['TotalMaxDays'] : 0;
                if ($TotalMinDays > 0 && $TotalMaxDays > 0) {
                    $tpstart_date = date('Y-m-d', strtotime($main_trip_start_date . ' +' . ($TotalMinDays - 1) . ' days'));
                    $tpend_date = date('Y-m-d', strtotime($main_trip_start_date . ' +' . ($TotalMaxDays - 1) . ' days'));
                    $NoofNights =  $TotalMaxDays - $TotalMinDays;
                } else {
                    $tpstart_date = $main_trip_start_date;
                    $tpend_date = $main_trip_start_date;
                    $NoofNights = 0;
                }

                $travelitenaryarray = array(
                    'TPSysId' => $tpproposalID,
                    'Sequence' => $travelplanIetnaryData[$i]['Sequence'],
                    'AgencySysId' => $travelplanIetnaryData[$i]['AgencySysId'],
                    'Title' => $travelplanIetnaryData[$i]['Title'],
                    'Details' => $travelplanIetnaryData[$i]['Details'],
                    'InclMask' => $travelplanIetnaryData[$i]['InclMask'] ? trim($travelplanIetnaryData[$i]['InclMask']) : '',
                    'ExclusionMask' => $travelplanIetnaryData[$i]['ExclusionMask'] ? $travelplanIetnaryData[$i]['ExclusionMask'] : '',
                    'InclCatMask' => $travelplanIetnaryData[$i]['InclCatMask'] ? trim($travelplanIetnaryData[$i]['InclCatMask']) : '',
                    'PackInclMask' => $travelplanIetnaryData[$i]['PackInclMask'] ? $travelplanIetnaryData[$i]['PackInclMask'] : '',
                    'PackTypeMask' => trim($travelplanIetnaryData[$i]['PackTypeMask']),
                    'ImageTN' => $travelplanIetnaryData[$i]['ImageTN'],
                    'ImgForList' => $travelplanIetnaryData[$i]['ImgForList'],
                    'ImgeDetails' => $travelplanIetnaryData[$i]['ImgeDetails'],
                    'Rating' => $travelplanIetnaryData[$i]['Rating'] ? $travelplanIetnaryData[$i]['Rating'] : 0,
                    'TotalMinDays' => $TotalMinDays,
                    'TotalMaxDays' => $TotalMaxDays,
                    'Hotels' => $travelplanIetnaryData[$i]['Hotels'],
                    'PopularPlaces' => $travelplanIetnaryData[$i]['PopularPlaces'],
                    'CitySysId' => $travelplanIetnaryData[$i]['CitySysId'],
                    'Cities' => $travelplanIetnaryData[$i]['Cities'],
                    'Countries' => $travelplanIetnaryData[$i]['Countries'],
                    'IsMarkForDel' => 0,
                    'IsActive' => 1,
                    'StartDate' => $tpstart_date,
                    'EndDate' => $tpend_date,
                    'CreateDate' => $createDate,
                    'UpdateDate' => $createDate,
                );
                try {
                    $lasttravelitenaryID[] = $itenaryIDD = $this->_crmcustomertravelItenary->addCustomerTravelItenary($travelitenaryarray);
                    $ItenaryDataForHotel[$itenaryIDD] = array(
                        'StartDate' => $tpstart_date,
                        'EndDate' => $tpend_date,
                        'NoofNights' => $NoofNights,
                    );
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
            }


            ##################################################################
            //error_reporting(E_ALL);
            $tplanitenaryaccomdata = $this->GetTravelPlanItenaryAccom($tplanitenayvalues, $catID);
            //echo "<pre>";print_r($tplanitenaryaccomdata);
            for ($k = 0; $k < count($tplanitenaryaccomdata); $k++) {
                $existingtpintID = $tplanitenaryaccomdata[$k]['TPIntSysId'];
                $getkeyvalue = array_search($existingtpintID, $travelpanitenary);
                if ($tplanitenaryaccomdata[$k]['MasterIntSysId'] > 0) {
                    $masterintsysID = $tplanitenaryaccomdata[$k]['MasterIntSysId'];
                    $getkeyvalueintID = array_search($masterintsysID, $travelpanitenary);
                    $getmasterID = $lasttravelitenaryID[$getkeyvalueintID];
                } else {
                    $getmasterID = 0;
                }
                //		if(isset($requestPerameter['leadsource']) && strtolower($requestPerameter['leadsource']) == 'website'){
                //                    $IsSelectedOnPkg =  0;
                //                } else {
                //                    $IsSelectedOnPkg = $tplanitenaryaccomdata[$k]['IsSelectedOnPkg'] ? $tplanitenaryaccomdata[$k]['IsSelectedOnPkg'] : 0;
                //                }
                //                if (isset($requestPerameter['leadsource']) && strtolower($requestPerameter['leadsource']) == 'website' && count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']) > 0) {
                //                    foreach ($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel'] as $key => $value) {
                //                        if ($tplanitenaryaccomdata[$k]['InvnItemSysId'] == $value['itemid'] && $value['IsIncluded'] == 1) {
                //                            $IsSelectedOnPkg = 1;
                //                        }
                //                    }
                //                }
                //  $paymentModel = new Payment_Model_Payment();
                if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && is_array($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']) && count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']) > 0) {
                    $IsSelectedOnPkg = 0;
                } else {
                    $IsSelectedOnPkg = $tplanitenaryaccomdata[$k]['IsSelectedOnPkg'] ? $tplanitenaryaccomdata[$k]['IsSelectedOnPkg'] : 0;
                }
                //  $logData = "IsSelectedOnPkg==$IsSelectedOnPkg==".$requestPerameter['leadsource']."========count==$existingtpintID==".count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']);
                // $this->writeLog($logData. "\n");
                // $logData= json_encode($requestPerameter);
                //  $this->writeLog($logData. "\n");

                if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && is_array($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']) &&  count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel']) > 0) {
                    foreach ($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['hotel'] as $key => $value) {
                        if ($tplanitenaryaccomdata[$k]['AccoSysId'] == $value['AccomSysId'] && $tplanitenaryaccomdata[$k]['RoomType'] == $value['RoomType'] && $tplanitenaryaccomdata[$k]['MealPlanType'] == $value['MealPlanType'] && $value['IsIncluded'] == 1) {
                            $IsSelectedOnPkg = 1;

                            $tplanitenaryaccomdata[$k]['AccoSysId'] = $value['AccomSysId'];
                            $tplanitenaryaccomdata[$k]['RoomType'] = $value['RoomType'];
                            $tplanitenaryaccomdata[$k]['MealPlanType'] = $value['MealPlanType'];
                            //                            $tplanitenaryaccomdata[$k]['Title'] = $value['Title'];
                            //$tplanitenaryaccomdata[$k]['SupplierSysId'] = $value['SupplierSysId'];
                        }
                    }
                }
                $TPIntSysIdd = $lasttravelitenaryID[$getkeyvalue] ? $lasttravelitenaryID[$getkeyvalue] : 0;
                $StartDate = isset($ItenaryDataForHotel[$TPIntSysIdd]['StartDate']) ? $ItenaryDataForHotel[$TPIntSysIdd]['StartDate'] : ($tplanitenaryaccomdata[$k]['FromDate'] ? $tplanitenaryaccomdata[$k]['FromDate'] : '');
                $EndDate = isset($ItenaryDataForHotel[$TPIntSysIdd]['EndDate']) ? $ItenaryDataForHotel[$TPIntSysIdd]['EndDate'] : ($tplanitenaryaccomdata[$k]['ToDate'] ? $tplanitenaryaccomdata[$k]['ToDate'] : '');
                $NoofNights = isset($ItenaryDataForHotel[$TPIntSysIdd]['NoofNight']) ? (int)$ItenaryDataForHotel[$TPIntSysIdd]['NoofNight'] : ($tplanitenaryaccomdata[$k]['TotalNights'] ? $tplanitenaryaccomdata[$k]['TotalNights'] : 0);
                $travelitenaryaccomArray = array(
                    'TPIntSysId' => $TPIntSysIdd,
                    'MasterIntSysId' => $getmasterID,
                    'SeqId' => $tplanitenaryaccomdata[$k]['SeqId'] ? $tplanitenaryaccomdata[$k]['SeqId'] : 0,
                    'AgencySysId' => $tplanitenaryaccomdata[$k]['AgencySysId'] ? $tplanitenaryaccomdata[$k]['AgencySysId'] : 0,
                    'AccoSysId' => $tplanitenaryaccomdata[$k]['AccoSysId'] ? $tplanitenaryaccomdata[$k]['AccoSysId'] : 0,
                    //'InvnItemSysId' => 278,
                    'InvnItemSysId' => $tplanitenaryaccomdata[$k]['InvnItemSysId'] ? $tplanitenaryaccomdata[$k]['InvnItemSysId'] : '0',
                    'RoomType' => $tplanitenaryaccomdata[$k]['RoomType'] ? $tplanitenaryaccomdata[$k]['RoomType'] : 0,
                    'MealPlanType' => $tplanitenaryaccomdata[$k]['MealPlanType'] ? $tplanitenaryaccomdata[$k]['MealPlanType'] : 0,
                    'RoomNumber' => $tplanitenaryaccomdata[$k]['RoomNumber'] ? $tplanitenaryaccomdata[$k]['RoomNumber'] : '',
                    'RoomTypeStr' => $tplanitenaryaccomdata[$k]['RoomTypeStr'] ? $tplanitenaryaccomdata[$k]['RoomTypeStr'] : '',
                    'Title' => $tplanitenaryaccomdata[$k]['Title'] ? $tplanitenaryaccomdata[$k]['Title'] : '',
                    'SpecialRequest' => '',
                    'CheckInTime' => $tplanitenaryaccomdata[$k]['CheckInTime'] ? $tplanitenaryaccomdata[$k]['CheckInTime'] : '',
                    'CheckOutTime' => $tplanitenaryaccomdata[$k]['CheckOutTime'] ? $tplanitenaryaccomdata[$k]['CheckOutTime'] : '',
                    'XRefCityId' => $tplanitenaryaccomdata[$k]['XRefCityId'] ? $tplanitenaryaccomdata[$k]['XRefCityId'] : '',
                    'FromDate' => $StartDate,
                    'ToDate' => $EndDate,
                    'AdultPax' => 0,
                    'ChildPax' => 0,
                    'InfantPax' => 0,
                    'PetPax' => 0,
                    'TotalPax' => $tplanitenaryaccomdata[$k]['TotalPax'] ? $tplanitenaryaccomdata[$k]['TotalPax'] : 0,
                    'TotalNights' => $NoofNights,
                    'StarRating' => $tplanitenaryaccomdata[$k]['StarRating'] ? $tplanitenaryaccomdata[$k]['StarRating'] : 0,
                    'CurrencyType' => $tplanitenaryaccomdata[$k]['CurrencyType'] ? $tplanitenaryaccomdata[$k]['CurrencyType'] : 0,
                    'TotalCost' => $tplanitenaryaccomdata[$k]['TotalCostGen'] ? $tplanitenaryaccomdata[$k]['TotalCostGen'] : 0,
                    'Discounts' => $tplanitenaryaccomdata[$k]['Discounts'] ? $tplanitenaryaccomdata[$k]['Discounts'] : 0,
                    'Taxes' => $tplanitenaryaccomdata[$k]['Taxes'] ? $tplanitenaryaccomdata[$k]['Taxes'] : 0,
                    'NetCost' => $tplanitenaryaccomdata[$k]['NetCost'] ? $tplanitenaryaccomdata[$k]['NetCost'] : 0,
                    'XServiceTaxAmount' => 0,
                    'GTXServiceTaxAmount' => 0,
                    'AgentServiceTaxAmount' => 0,
                    'AgentsCustomServiceTaxAmount' => 0,
                    'MarkUp' => 0,
                    'GTXMarkup' => 0,
                    'AgencyMarkUp' => 0,
                    'IsSelectedOnPkg' => $IsSelectedOnPkg,
                    'CreateDate' => $tplanitenaryaccomdata[$k]['CreateDate'] ? $tplanitenaryaccomdata[$k]['CreateDate'] : '',
                    'UpdateDate' => $tplanitenaryaccomdata[$k]['UpdateDate'] ? $tplanitenaryaccomdata[$k]['UpdateDate'] : '',
                    'IsMarkForDel' => 0,
                    'IsActive' => 1,
                    'IsFromAPI' => 0,
                    'SupplierSysId' => $tplanitenaryaccomdata[$k]['SupplierSysId'] ? $tplanitenaryaccomdata[$k]['SupplierSysId'] : '',
                    'SourceSysId' => $tplanitenaryaccomdata[$k]['SourceSysId'] ? $tplanitenaryaccomdata[$k]['SourceSysId'] : '',
                    'TotalCostSO' => $tplanitenaryaccomdata[$k]['TotalCostSO'] ? $tplanitenaryaccomdata[$k]['TotalCostSO'] : 0,
                    'TotalCostDO' => $tplanitenaryaccomdata[$k]['TotalCostDO'] ? $tplanitenaryaccomdata[$k]['TotalCostDO'] : 0,
                    'TotalCostTO' => 0,
                    'TotalCost' => $tplanitenaryaccomdata[$k]['TotalCost'] ? $tplanitenaryaccomdata[$k]['TotalCost'] : 0,
                    'RoomMemInfoJson' => $requestPerameter['roomjson'] ? $requestPerameter['roomjson'] : '',
                    'TotalCostExtraBed' => $tplanitenaryaccomdata[$k]['TotalCostExtraBed'] ? $tplanitenaryaccomdata[$k]['TotalCostExtraBed'] : 0,
                    'TotalCostWithoutBed' => $tplanitenaryaccomdata[$k]['TotalCostWithoutBed'] ? $tplanitenaryaccomdata[$k]['TotalCostWithoutBed'] : 0,
                    'BYOPackType' => $tplanitenaryaccomdata[$k]['BYOPackType'] ? $tplanitenaryaccomdata[$k]['BYOPackType'] : '1',
                );
                try {
                    //echo "<pre>";print_r($travelitenaryaccomArray);
                    $tplanitenaryaccomdataID = $this->_crmcusttravelplanItenaryAccom->addCustomerTravelPlanAccom($travelitenaryaccomArray);
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
            }

            ##################################################################
            $tpitenrayEvents = $this->GetTravelPlanItenaryEvents($tplanitenayvalues);
            if (count($tpitenrayEvents) > 0) {
                for ($k = 0; $k < count($tpitenrayEvents); $k++) {
                    $existingtpintID = $tpitenrayEvents[$k]['TPIntSysId'];
                    $getkeyvalue = array_search($existingtpintID, $travelpanitenary);
                    $IsOptionalActivity = $tpitenrayEvents[$k]['IsOptionalActivity'] ? $tpitenrayEvents[$k]['IsOptionalActivity'] : 0;
                    if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['activity']) > 0) {
                        foreach ($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['activity'] as $key => $value) {
                            if ($tpitenrayEvents[$k]['TPActivitySysId'] == $value['itemid'] && $value['IsIncluded'] == 1) {
                                $IsOptionalActivity = 1;
                            }
                        }
                    }
                    $tpitenrayevntsArray = array(
                        'TPIntSysId' => $lasttravelitenaryID[$getkeyvalue] ? $lasttravelitenaryID[$getkeyvalue] : 0,
                        'Sequence' => $tpitenrayEvents[$k]['Sequence'] ? $tpitenrayEvents[$k]['Sequence'] : 0,
                        'AgencySysId' => $tpitenrayEvents[$k]['AgencySysId'] ? $tpitenrayEvents[$k]['AgencySysId'] : 0,
                        'TPActivitySysId' => $tpitenrayEvents[$k]['TPActivitySysId'] ? $tpitenrayEvents[$k]['TPActivitySysId'] : 0,
                        'CurrencyType' => $tpitenrayEvents[$k]['CurrencyType'] ? $tpitenrayEvents[$k]['CurrencyType'] : 0,
                        'Title' => $tpitenrayEvents[$k]['Title'] ? $tpitenrayEvents[$k]['Title'] : '',
                        'Type' => $tpitenrayEvents[$k]['Type'] ? $tpitenrayEvents[$k]['Type'] : '',
                        'CityId' => $tpitenrayEvents[$k]['CityId'] ? $tpitenrayEvents[$k]['CityId'] : 0,
                        'IsMarkForDel' => $tpitenrayEvents[$k]['IsMarkForDel'] ? $tpitenrayEvents[$k]['IsMarkForDel'] : 0,
                        'IsActive' => $tpitenrayEvents[$k]['IsActive'] ? $tpitenrayEvents[$k]['IsActive'] : 1,
                        'Cost' => $tpitenrayEvents[$k]['Cost'] ? $tpitenrayEvents[$k]['Cost'] : 0,
                        'KidsCost' => $tpitenrayEvents[$k]['KidsCost'] ? $tpitenrayEvents[$k]['KidsCost'] : 0,
                        'Markup' => $tpitenrayEvents[$k]['Markup'] ? $tpitenrayEvents[$k]['Markup'] : 0,
                        'TotalCost' => $tpitenrayEvents[$k]['TotalCost'] ? $tpitenrayEvents[$k]['TotalCost'] : 0,
                        'IsOptionalActivity' => $IsOptionalActivity,
                        'SupplierSysId' => $tpitenrayEvents[$k]['SupplierSysId'] ? $tpitenrayEvents[$k]['SupplierSysId'] : 0,
                    );
                    try {
                        $travelitenrayevents = $this->_crmcustomertravelItenaryEvents->addCustomerTravelItenaryEvents($tpitenrayevntsArray);
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
            }

            ##################################################################
            $tpitenarysightseeing = $this->GetTravelPlanSightSeeing($tplanitenayvalues);
            if (count($tpitenarysightseeing) > 0) {
                for ($k = 0; $k < count($tpitenarysightseeing); $k++) {
                    $existingtpintID = $tpitenarysightseeing[$k]['InvnItemSysId'];
                    $getkeyvalue = array_search($existingtpintID, $travelpanitenary);
                    $SeqId = $tpitenarysightseeing[$k]['SeqId'] ? $tpitenarysightseeing[$k]['SeqId'] : 0;
                    $fromDate = $toDate = date('Y-m-d', strtotime($main_trip_start_date . ' +' . ($SeqId) . ' days'));

                    $IsOptionalSightSeeing = $tpitenarysightseeing[$k]['IsOptionalSightSeeing'] ? $tpitenarysightseeing[$k]['IsOptionalSightSeeing'] : 0;
                    $Type = $tpitenarysightseeing[$k]['Type'] ? $tpitenarysightseeing[$k]['Type'] : '';
                    if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && is_array($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['sightSeeing']) && count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['sightSeeing']) > 0) {
                        foreach ($requestPerameter['ItineraryArray']['itineraries'][$existingtpintID]['sightSeeing'] as $key => $value) {
                            if ($tpitenarysightseeing[$k]['VersionId'] == $value['itemid'] && $value['IsIncluded'] == 1) {
                                $IsOptionalSightSeeing = 0;
                                $Type = 'Included';
                            }
                        }
                    }
                    $tpitenraysightseeingArray = array(
                        'InvnItemSysId' => $lasttravelitenaryID[$getkeyvalue] ? $lasttravelitenaryID[$getkeyvalue] : 0,
                        'SeqId' => $SeqId,
                        'SSSysId' => $tpitenarysightseeing[$k]['SSSysId'] ? $tpitenarysightseeing[$k]['SSSysId'] : 0,
                        'XrefInvnItemSysId' => $tpitenarysightseeing[$k]['XrefInvnItemSysId'] ? $tpitenarysightseeing[$k]['XrefInvnItemSysId'] : 0,
                        'AgencySysId' => $tpitenarysightseeing[$k]['AgencySysId'] ? $tpitenarysightseeing[$k]['AgencySysId'] : 0,
                        'SupplierSysId' => $tpitenarysightseeing[$k]['SupplierSysId'] ? $tpitenarysightseeing[$k]['SupplierSysId'] : 0,
                        'Title' => $tpitenarysightseeing[$k]['Title'] ? $tpitenarysightseeing[$k]['Title'] : 0,
                        'Type' => $Type,
                        'IsOptionalSightSeeing' => $IsOptionalSightSeeing,
                        'CityId' => $tpitenarysightseeing[$k]['CityId'] ? $tpitenarysightseeing[$k]['CityId'] : 0,
                        'Cost' => $tpitenarysightseeing[$k]['Cost'] ? $tpitenarysightseeing[$k]['Cost'] : 0,
                        'FromDate' => $fromDate,
                        'ToDate' => $toDate,
                        'BookingType' => $tpitenarysightseeing[$k]['BookingType'] ? $tpitenarysightseeing[$k]['BookingType'] : 0,
                        'Qty' => $tpitenarysightseeing[$k]['Qty'] ? $tpitenarysightseeing[$k]['Qty'] : 0,
                        'IfAnyOffer' => $tpitenarysightseeing[$k]['IfAnyOffer'] ? $tpitenarysightseeing[$k]['IfAnyOffer'] : 0,
                        'OfferMsg' => $tpitenarysightseeing[$k]['OfferMsg'] ? $tpitenarysightseeing[$k]['OfferMsg'] : 0,
                        'OfferImage' => $tpitenarysightseeing[$k]['OfferImage'] ? $tpitenarysightseeing[$k]['OfferImage'] : 0,
                        'IxFixedDateInven' => $tpitenarysightseeing[$k]['IxFixedDateInven'] ? $tpitenarysightseeing[$k]['IsMarkForDel'] : 0,
                        'CreateDate' => $createDate,
                        'UpdateDate' => $createDate,
                        'IsActive' => $tpitenarysightseeing[$k]['IsActive'] ? $tpitenarysightseeing[$k]['IsActive'] : 0,
                        'IsMarkForDelete' => $tpitenarysightseeing[$k]['IsMarkForDelete'] ? $tpitenarysightseeing[$k]['IsMarkForDelete'] : 0,
                        'Cost' => $tpitenarysightseeing[$k]['Cost'] ? $tpitenarysightseeing[$k]['Cost'] : 0,
                        'KidsCost' => $tpitenarysightseeing[$k]['KidsCost'] ? $tpitenarysightseeing[$k]['KidsCost'] : 0,
                        'Markup' => $tpitenarysightseeing[$k]['Markup'] ? $tpitenarysightseeing[$k]['Markup'] : 0,
                        'TotalCost' => $tpitenarysightseeing[$k]['TotalCost'] ? $tpitenarysightseeing[$k]['TotalCost'] : 0,
                        'PriceType' => $tpitenarysightseeing[$k]['PriceType'] ? $tpitenarysightseeing[$k]['PriceType'] : 0,
                    );
                    try {
                        $travelitenraysightssing = $this->_crmcustomertravelSightSeeing->addCustomerTravelItenarySightSeeing($tpitenraysightseeingArray);
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
            }
            ##################################################################
            $travelplanmarketPrice = $this->GetTravelMarketPrice($travelplanID, $MarketPlaceId);

            if (count($travelplanmarketPrice) > 0) {
                for ($k = 0; $k < count($travelplanmarketPrice); $k++) {
                    $fromDate = $travelplanmarketPrice[$k]['FromDate'];
                    $toDate = $travelplanmarketPrice[$k]['ToDate'];
                    $travelmarketpriceArray = array(
                        'TPIntSysId' => $tpproposalID,
                        'AgencySysId' => trim($travelplanmarketPrice[$k]['AgencySysId']) ? $travelplanmarketPrice[$k]['AgencySysId'] : 0,
                        'FromDate' => $fromDate->format('Y-m-d'),
                        'ToDate' => $toDate->format('Y-m-d'),
                        'CurrencyType' => $travelplanmarketPrice[$k]['CurrencyType'] ? $travelplanmarketPrice[$k]['CurrencyType'] : 0,
                        'MarkType' => $travelplanmarketPrice[$k]['MarkType'] ? $travelplanmarketPrice[$k]['MarkType'] : 0,
                        'MarketPlaceId' => $travelplanmarketPrice[$k]['MarketPlaceId'] ? $travelplanmarketPrice[$k]['MarketPlaceId'] : 0,
                        'MarketPlace' => $travelplanmarketPrice[$k]['MarketPlace'] ? $travelplanmarketPrice[$k]['MarketPlace'] : 0,
                        'Permission' => $travelplanmarketPrice[$k]['Permission'] ? $travelplanmarketPrice[$k]['Permission'] : 0,
                        'MarkPercent' => $travelplanmarketPrice[$k]['MarkPercent'] ? $travelplanmarketPrice[$k]['MarkPercent'] : 0,
                        'CostPPSO' => $travelplanmarketPrice[$k]['CostPPSO'] ? $travelplanmarketPrice[$k]['CostPPSO'] : 0,
                        'CostPPDO' => $travelplanmarketPrice[$k]['CostPPDO'] ? $travelplanmarketPrice[$k]['CostPPDO'] : 0,
                        //                        'CostPPTO' => $travelplanmarketPrice[$k]['CostPPTO'] ? $travelplanmarketPrice[$k]['CostPPTO'] : 0,
                        'TourType' => $travelplanmarketPrice[$k]['TourType'] ? $travelplanmarketPrice[$k]['TourType'] : 0,
                        'PackCategoryId' => $travelplanmarketPrice[$k]['PackCategoryId'] ? $travelplanmarketPrice[$k]['PackCategoryId'] : 0,
                        'CostExtraBed' => $travelplanmarketPrice[$k]['CostExtraBed'] ? $travelplanmarketPrice[$k]['CostExtraBed'] : 0,
                        'CostChildWithoutBed' => $travelplanmarketPrice[$k]['CostChildWithoutBed'] ? $travelplanmarketPrice[$k]['CostChildWithoutBed'] : 0,
                        'Tax' => $travelplanmarketPrice[$k]['Tax'] ? $travelplanmarketPrice[$k]['Tax'] : 0,
                        'ExcludedPercent' => $travelplanmarketPrice[$k]['ExcludedPercent'] ? $travelplanmarketPrice[$k]['ExcludedPercent'] : 0,
                        "PricePerPerson" => $travelplanmarketPrice[$k]['PricePerPerson'] ? $travelplanmarketPrice[$k]['PricePerPerson'] : 0,
                        "TotalCost" => $travelplanmarketPrice[$k]['TotalCost'] ? $travelplanmarketPrice[$k]['TotalCost'] : 0,
                        "CostPerPerson" => $travelplanmarketPrice[$k]['CostPerPerson'] ? $travelplanmarketPrice[$k]['CostPerPerson'] : 0,
                        'CreateDate' => $createDate,
                        'UpdateDate' => $createDate,
                        'IsActive' => $travelplanmarketPrice[$k]['IsActive'] ? $travelplanmarketPrice[$k]['IsActive'] : 0,
                        'IsMarkForDel' => 0,
                        'MealPlanType' => !empty($travelplanmarketPrice[$k]['MealPlanType']) ? $travelplanmarketPrice[$k]['MealPlanType'] : 0, //  meal plan
                    );

                    try {
                        $travelitenramarketwsierate = $this->_crmcustomertravelMarketPlaces->addCustomerTravelMarketRate($travelmarketpriceArray);
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
            }
            //            echo $error_Message;
            //            echo "<pre>";print_r($travelmarketpriceArray);die;
            $tpitenaryplaces = $this->GetTravelPlanItenaryPaces($tplanitenayvalues);

            if (count($tpitenaryplaces) > 0) {
                for ($k = 0; $k < count($tpitenaryplaces); $k++) {
                    $existingtpintID = $tpitenaryplaces[$k]['TPIntSysId'];
                    $getkeyvalue = array_search($existingtpintID, $travelpanitenary);
                    $tpitenrayplacesArray = array(
                        'TPSysId' => $tpproposalID,
                        'TPIntSysId' => $lasttravelitenaryID[$getkeyvalue] ? $lasttravelitenaryID[$getkeyvalue] : 0,
                        'Sequence' => $tpitenaryplaces[$k]['Sequence'] ? $tpitenaryplaces[$k]['Sequence'] : 0,
                        'PlaceSysId' => $tpitenaryplaces[$k]['PlaceSysId'] ? $tpitenaryplaces[$k]['PlaceSysId'] : 0,
                        'AgencySysId' => $tpitenaryplaces[$k]['AgencySysId'] ? $tpitenaryplaces[$k]['AgencySysId'] : 0,
                        'IsMarkForDel' => $tpitenaryplaces[$k]['IsMarkForDel'] ? $tpitenaryplaces[$k]['IsMarkForDel'] : 0,
                        'IsActive' => $tpitenaryplaces[$k]['IsActive'] ? $tpitenaryplaces[$k]['IsActive'] : 0,
                        'CreateDate' => $tpitenaryplaces[$k]['CreateDate'] ? $tpitenaryplaces[$k]['CreateDate'] : $createDate,
                        'UpdateDate' => $tpitenaryplaces[$k]['UpdateDate'] ? $tpitenaryplaces[$k]['UpdateDate'] : $createDate,
                    );
                    try {
                        $travelitenrayplaces = $this->_crmcustomertravelItenaryPlaces->addCustomerTravelItenaryPlaces($tpitenrayplacesArray);
                    } catch (Zend_Exception $e) {
                        $error_Message = $e->getMessage();
                    }
                }
            }

            $objPackage = new Travel_Model_TblPackage();
            $cancelPolicyData = $objPackage->getPackageCancelPolictyList($travelplanID);
            if (count($cancelPolicyData) > 0) {
                $cancelPolicyArray = array();
                foreach ($cancelPolicyData as $cancelPolicy) {
                    unset($cancelPolicy['TPRulesSysId']);
                    $cancelPolicyArray = $cancelPolicy;
                    $cancelPolicyArray['TPSysId'] = $tpproposalID;
                    $cancelPolicyArray['CreateDate'] = $createDate;
                    $cancelPolicyArray['UpdateDate'] = $createDate;
                    $travelplancancelpolicyids[] = $objPackage->insertData('TB_Agency_Customer_TravelPlan_Rules', $cancelPolicyArray);
                }
            }
            ##################################################################
            //            $travelplanPriceArr = $this->GetTravelRate($travelplanID);
            //            if (count($travelplanPriceArr) > 0) {
            //                foreach ($travelplanPriceArr as $travelplanPrice) {
            //                    unset($travelplanPrice['TPRateSheetSysId']);
            //                    $travelpriceArray = $travelplanPrice;
            //                    $travelpriceArray['TPSysId'] = $tpproposalID;
            //                    $travelpriceArray['CreateDate'] = $createDate;
            //                    $travelpriceArray['UpdateDate'] = $createDate;
            //                    $this->_crmcustomertravelPlanRate->addCustomerTravelPlanRate($travelpriceArray); // add price
            //                }
            //            }
            ##################################################################
            try {
                $travelplanterms = $this->GetCustomerTravelPlanTerms($travelplanID);
                if (count($travelplanterms) > 0) {
                    for ($k = 0; $k < count($travelplanterms); $k++) {
                        $IsInclusions = isset($travelplanterms[$k]['IsInclusions']) ? (int) $travelplanterms[$k]['IsInclusions'] : 0;
                        $IsExclusions = isset($travelplanterms[$k]['IsExclusions']) ? (int) $travelplanterms[$k]['IsExclusions'] : 0;
                        $IsCancellationPolicy = isset($travelplanterms[$k]['IsCancellationPolicy']) ? (int) $travelplanterms[$k]['IsCancellationPolicy'] : 0;
                        $IsTravelBasics = isset($travelplanterms[$k]['IsTravelBasics']) ? (int) $travelplanterms[$k]['IsTravelBasics'] : 0;
                        $IsTermsAndConditions = isset($travelplanterms[$k]['IsTermsAndConditions']) ? (int) $travelplanterms[$k]['IsTermsAndConditions'] : 0;
                        $IsBookingTerms = isset($travelplanterms[$k]['IsBookingTerms']) ? (int) $travelplanterms[$k]['IsBookingTerms'] : 0;
                        $IsWhyUseUs = isset($travelplanterms[$k]['IsWhyUseUs']) ? (int) $travelplanterms[$k]['IsWhyUseUs'] : 0;
                        $IsREFUNDPOLICY = isset($travelplanterms[$k]['IsREFUNDPOLICY']) ? (int) $travelplanterms[$k]['IsREFUNDPOLICY'] : 0;

                        $travelplantermsArray = array(
                            'TPIntSysId' => $tpproposalID,
                            'AgencySysId' => $travelplanterms[$k]['AgencySysId'] ? $travelplanterms[$k]['AgencySysId'] : 0,
                            'Inclusions' => ($travelplanterms[$k]['Inclusions'] != '' && $IsInclusions == 1) ? $travelplanterms[$k]['Inclusions'] : 0,
                            'Exclusions' => ($travelplanterms[$k]['Exclusions'] != '' && $IsExclusions == 1) ? $travelplanterms[$k]['Exclusions'] : 0,
                            'CancellationPolicy' => ($travelplanterms[$k]['CancellationPolicy'] != '' && $IsCancellationPolicy == 1) ? $travelplanterms[$k]['CancellationPolicy'] : 0,
                            'TravelBasics' => ($travelplanterms[$k]['TravelBasics'] != '' && $IsTravelBasics == 1) ? $travelplanterms[$k]['TravelBasics'] : '',
                            'TermsAndConditions' => ($travelplanterms[$k]['TermsAndConditions'] != '' && $IsTermsAndConditions == 1) ? $travelplanterms[$k]['TermsAndConditions'] : '',
                            'BookingTerms' => ($travelplanterms[$k]['BookingTerms'] != '' && $IsBookingTerms == 1) ? $travelplanterms[$k]['BookingTerms'] : '',
                            'WhyUseUs' => ($travelplanterms[$k]['WhyUseUs'] != '' && $IsWhyUseUs == 1) ? $travelplanterms[$k]['WhyUseUs'] : '',
                            'REFUNDPOLICY' => ($travelplanterms[$k]['REFUNDPOLICY'] != '' && $IsREFUNDPOLICY == 1) ? $travelplanterms[$k]['REFUNDPOLICY'] : '',
                            'CreateDate' => $createDate,
                            'UpdateDate' => $createDate,
                            'IsMarkForDel' => $travelplanterms[$k]['IsMarkForDel'] ? $travelplanterms[$k]['IsMarkForDel'] : 0,
                            'IsActive' => $travelplanterms[$k]['IsActive'] ? $travelplanterms[$k]['IsActive'] : 0,
                        );
                        try {
                            $travelitenramarketwsierate = $this->_crmcustomertravelTerm->addCustomerTerm($travelplantermsArray);
                        } catch (Zend_Exception $e) {
                            $error_Message = $e->getMessage();
                        }
                    }
                }
            } catch (Zend_Exception $e) {
                $error_Message = $e->getMessage();
            }


            $travelplanTransFixed = $this->GetTravelPlanItenaryTransFixed($travelplanID);
            for ($j = 0; $j < count($travelplanTransFixed); $j++) {

                $existingtpintIDTF = $travelplanTransFixed[$j]['TPIntSysId'];
                $getkeyvalue = array_search($existingtpintIDTF, $travelpanitenary);
                $IsIncluded = $travelplanTransFixed[$j]['IsIncluded'] ? $travelplanTransFixed[$j]['IsIncluded'] : 0;
                $Type = $travelplanTransFixed[$j]['Type'] ? $travelplanTransFixed[$j]['Type'] : 'Optional';
                if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && is_array($requestPerameter['ItineraryArray']['itineraries'][$existingtpintIDTF]['transfers']) && count($requestPerameter['ItineraryArray']['itineraries'][$existingtpintIDTF]['transfers']) > 0) {
                    foreach ($requestPerameter['ItineraryArray']['itineraries'][$existingtpintIDTF]['transfers'] as $key => $dataTrans) {
                        if (($travelplanTransFixed[$j]['FixTransSysId'] == $dataTrans['itemid']) && ($dataTrans['IsIncluded'] == 1)) {
                            $IsIncluded = 1;
                            $Type = 'Included';
                            $travelplanTransFixed[$key]['VehSysId'] = $dataTrans['VehSysId'];
                            $travelplanTransFixed[$key]['VehicleTypeSysId'] = $dataTrans['VehicleTypeSysId'];
                            $travelplanTransFixed[$key]['RouteSysId'] = $dataTrans['RouteSysId'];
                            $travelplanTransFixed[$key]['RouteVechSysId'] = $dataTrans['RouteVechSysId'];
                            $travelplanTransFixed[$key]['FromPlace'] = $dataTrans['FromPlace'];
                            $travelplanTransFixed[$key]['ToPlace'] = $dataTrans['ToPlace'];
                            $travelplanTransFixed[$key]['Capacity'] = $dataTrans['Capacity'];
                            $travelplanTransFixed[$key]['VehName'] = $dataTrans['VehName'];
                            $travelplanTransFixed[$key]['SupplierSysId'] = $dataTrans['SupplierSysId'];
                            //                            $travelplanTransFixed[$j]['TransTypeCat'] = $dataTrans['TransTypeCat'];
                        } else if ($dataTrans['IsIncluded'] == false) {
                            $IsIncluded = 0;
                            $Type = 'Optional';
                        }
                    }
                }
                $Sequence = $travelplanTransFixed[$j]['Sequence'] ? $travelplanTransFixed[$j]['Sequence'] : 1;
                $NoofDays = $travelplanTransFixed[$j]['NoofDays'] ? (int) $travelplanTransFixed[$j]['NoofDays'] - 1 : 0;
                $FromDateT = date('Y-m-d', strtotime($main_trip_start_date . ' +' . ($Sequence - 1) . ' days'));
                $ToDateT = date('Y-m-d', strtotime($FromDateT . ' +' . $NoofDays . ' days'));
                $dataTrans = array(
                    'AgencySysId' => $AgencySysId,
                    'TPSysId' => $tpproposalID,
                    'TPIntSysId' => $lasttravelitenaryID[$getkeyvalue] ? $lasttravelitenaryID[$getkeyvalue] : 0,
                    'Type' => $Type,
                    'IsIncluded' => $IsIncluded,
                    'VehSysId' => $travelplanTransFixed[$j]['VehSysId'] ? $travelplanTransFixed[$j]['VehSysId'] : 0,
                    'VehicleTypeSysId' => $travelplanTransFixed[$j]['VehicleTypeSysId'] ? $travelplanTransFixed[$j]['VehicleTypeSysId'] : 0,
                    'RouteSysId' => $travelplanTransFixed[$j]['RouteSysId'] ? $travelplanTransFixed[$j]['RouteSysId'] : 0,
                    'RouteVechSysId' => $travelplanTransFixed[$j]['RouteVechSysId'] ? $travelplanTransFixed[$j]['RouteVechSysId'] : 0,
                    'TransId' => 1,
                    'TransType' => $travelplanTransFixed[$j]['TransType'] ? $travelplanTransFixed[$j]['TransType'] : 'Cab',
                    'TransTypeCat' => $travelplanTransFixed[$j]['TransTypeCat'] ? $travelplanTransFixed[$j]['TransTypeCat'] : 'Cab',
                    'FromPlace' => $travelplanTransFixed[$j]['FromPlace'] ? $travelplanTransFixed[$j]['FromPlace'] : '',
                    'ToPlace' => $travelplanTransFixed[$j]['ToPlace'] ? $travelplanTransFixed[$j]['ToPlace'] : '',
                    'SourceCityId' => $travelplanTransFixed[$j]['SourceCityId'] ? $travelplanTransFixed[$j]['SourceCityId'] : 0,
                    'DestCityId' => $travelplanTransFixed[$j]['DestCityId'] ? $travelplanTransFixed[$j]['DestCityId'] : 0,
                    'CostPerson' => $travelplanTransFixed[$j]['CostPerson'] ? $travelplanTransFixed[$j]['CostPerson'] : 0,
                    'TotalPrice' => $travelplanTransFixed[$j]['TotalPrice'] ? $travelplanTransFixed[$j]['TotalPrice'] : 0,
                    'Capacity' => $travelplanTransFixed[$j]['Capacity'] ? $travelplanTransFixed[$j]['Capacity'] : 0,
                    'IsGroup' => $travelplanTransFixed[$j]['IsGroup'] ? $travelplanTransFixed[$j]['IsGroup'] : 0,
                    'CreateDate' => $createDate,
                    'UpdateDate' => $createDate,
                    'IsMarkForDel' => '0',
                    'IsActive' => '1',
                    'Sequence' => $travelplanTransFixed[$j]['Sequence'] ? $travelplanTransFixed[$j]['Sequence'] : 0,
                    'TransportCategory' => $travelplanTransFixed[$j]['TransTypeCat'] ? $travelplanTransFixed[$j]['TransTypeCat'] : '',
                    'Type_Text' => $travelplanTransFixed[$j]['VehName'] ? $travelplanTransFixed[$j]['VehName'] : 'Cab',
                    'SupplierSysId' => $travelplanTransFixed[$j]['SupplierSysId'] ? $travelplanTransFixed[$j]['SupplierSysId'] : 0,
                    'FromDate' => $FromDateT,
                    'ToDate' => $ToDateT,
                );
                //                                echo "<pre>fff";print_r($dataTrans);die;
                try {
                    $updateId = $this->_crmcustomertravelFixed->addCustomerFixedItinerary($dataTrans);
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
            }

            $travelplanOtherServices = $this->GetTravelPlanOtherServices($travelplanID);
            //print_r($requestPerameter['ItineraryArray']['others']['services']);
            for ($j = 0; $j < count($travelplanOtherServices); $j++) {
                $IsOptionalServices = $travelplanOtherServices[$j]['IsOptionalServices'] ? $travelplanOtherServices[$j]['IsOptionalServices'] : 0;
                if (isset($leadsourceTitle) && $leadsourceTitle == 'Website' && count($requestPerameter['ItineraryArray']['others']['services']) > 0) {
                    foreach ($requestPerameter['ItineraryArray']['others']['services'] as $key => $value) {

                        if ($travelplanOtherServices[$j]['OtherSrvSysId'] == $value['itemid'] && $value['IsIncluded'] == 1) {
                            $IsOptionalServices = 1;
                        }
                    }
                }

                $dataOtherServices = array(
                    'TPIntSysId' => $tpproposalID,
                    'OtherSrvSysId' => $travelplanOtherServices[$j]['OtherSrvSysId'] ? $travelplanOtherServices[$j]['OtherSrvSysId'] : 0,
                    'SupplierSysId' => $travelplanOtherServices[$j]['SupplierSysId'] ? $travelplanOtherServices[$j]['SupplierSysId'] : 0,
                    'ServiceTitle' => $travelplanOtherServices[$j]['ServiceTitle'] ? $travelplanOtherServices[$j]['ServiceTitle'] : '',
                    'ServiceType' => $travelplanOtherServices[$j]['ServiceType'] ? $travelplanOtherServices[$j]['ServiceType'] : '',
                    'Comment' => $travelplanOtherServices[$j]['Comment'] ? $travelplanOtherServices[$j]['Comment'] : '',
                    'CurrencyType' => $travelplanOtherServices[$j]['CurrencyType'] ? $travelplanOtherServices[$j]['CurrencyType'] : 0,
                    'RateType' => $travelplanOtherServices[$j]['RateType'] ? $travelplanOtherServices[$j]['RateType'] : 0,
                    'PaxCount' => $travelplanOtherServices[$j]['PaxCount'] ? $travelplanOtherServices[$j]['PaxCount'] : 0,
                    'Cost' => $travelplanOtherServices[$j]['Cost'] ? $travelplanOtherServices[$j]['Cost'] : 0,
                    'IsOptionalServices' => $IsOptionalServices,
                    'IsCostInclInTP' => $travelplanOtherServices[$j]['IsCostInclInTP'] ? $travelplanOtherServices[$j]['IsCostInclInTP'] : 0,
                    'IsActive' => 1,
                    'IsMarkForDelete' => 0,
                    'IsApproved' => 1,
                    'CreateDate' => $createDate,
                    'UpdateDate' => $createDate
                );
                //print_r($dataOtherServices);
                try {
                    $updateId = $this->_crmcustomerTravelOtherServicesObj->addCustomerTravelOtherServices($dataOtherServices);
                } catch (Zend_Exception $e) {
                    $error_Message = $e->getMessage();
                }
            }


            $shareWithFlight = 0;
            $totalFlightCost = $totalFlightMarkup = $totalFlightTax = 0;
            if (!empty($inventory)) {
                $shareWithFlight = 1;

                $inventoryAirline = $objPackage->getFromDestinationFixedInventoryAirlineDateAndDestination($travelplanID, $inventory[0]['id']);
                $inventoryAirlineArr = array();
                foreach ($inventoryAirline as $key => $value) {
                    $inventoryAirlineArr[$value['FlightType']][] = $value;
                }
                foreach ($inventoryAirlineArr as $inkey => $invalue) {
                    if ($inventory[0]['MarkupType'] == 2) {
                        $B2BAdultMarkup = ((float) $inventory[0]['AdultCost'] * (float) $inventory[0]['B2BAdultMarkup'] / 100);
                        $B2BInfantMarkup = ((float) $inventory[0]['InfantCost'] * (float) $inventory[0]['B2BInfantMarkup'] / 100);
                        $AdultCost = $inventory[0]['AdultCost'] + $B2BAdultMarkup;
                        $InfantCost = $inventory[0]['InfantCost'] + $B2BInfantMarkup;
                    } else {
                        $B2BAdultMarkup = (float) $inventory[0]['B2BAdultMarkup'];
                        $B2BInfantMarkup = (float) $inventory[0]['B2BInfantMarkup'];
                        $AdultCost = $inventory[0]['AdultCost'] + $B2BAdultMarkup;
                        $InfantCost = $inventory[0]['InfantCost'] + $B2BInfantMarkup;
                    }
                    $totalPax = $totaladult + $totalchild + $totalInfant;
                    $totalAdultCost = $AdultCost * ($totaladult + $totalchild);
                    $totalInfantCost = $InfantCost * ($totalInfant);
                    $totalCost = $totalAdultCost + $totalInfantCost;
                    $totalCostPerperson = (float) $totalCost / $totalPax;


                    $totalMarkup = $B2BAdultMarkup * ($totaladult + $totalchild) + $B2BInfantMarkup * ($totalInfant);
                    //                                if(isset($inventoryAirlineArr[2])){
                    //                                    $totalMarkup = $totalMarkup/2;    
                    //                                    $totalCost = $totalCost/2;    
                    //                                }

                    $totalMarkupPerperson = (float) $totalMarkup / $totalPax;


                    $flightJson = array(
                        "inventory" => $invalue[0]['InvnAirlineSysId'],
                        "supplierName" => '',
                        "hidden_selected_supplier_sys_id" => '',
                        "FlightNo" => $invalue[0]['AirlineCode'],
                        "AirlineName" => $invalue[0]['AirlineName'],
                        "hidden_selected_airline_sys_id" => 0,
                        "departureCity" => $invalue[0]['DepartureAirportName'],
                        "depaartureDate" => ($inkey == 1) ? $postData['pkgCheckInDate'] : $postData['pkgCheckOutDate'],
                        "depaartureTime" => (isset($invalue[0]['DepartureTime']) && !empty($invalue[0]['DepartureTime'])) ? $invalue[0]['DepartureTime']->format('H:i') : '',
                        "arrivalCity" => $inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalAirportName'],
                        "arrivalDate" => ($inkey == 1) ? $postData['pkgCheckOutDate'] : $postData['pkgCheckInDate'],
                        "arrivalTime" => (isset($inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime']) && !empty($inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime'])) ? $inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime']->format('H:i') : '',
                        "stops" => count($invalue) - 1,
                        "duration" => $invalue[0]['EstimateHours'],
                        "refundableFlight" => 0,
                        "adultCabin" => "15",
                        "adultCheckIn" => "7",
                        "childCabin" => "15",
                        "childCheckIn" => "7",
                        "InfentCabin" => "",
                        "InfentCheckIn" => "",
                        "paxType" => array("2"),
                        "currencyType" => [$inventory[0]['CurrencySysId']],
                        "perpersoneprice" => [(int) $totalCostPerperson],
                        "perpersonemarkup" => [(int) $totalMarkupPerperson],
                        "taxpersentage" => ["1"],
                        "taxamount" => ["0"],
                        "totalAmount" => [$totalCost],
                        "QueryId" => $leadID,
                        "totalFightCost" => (float) $totalCost - $totalMarkup,
                        "totalFightMarkup" => (float) $totalMarkup,
                        "totalTax" => "0",
                        "totalFightCostWithMarkup" => (float) $totalCost,
                        "textbased" => "textbased",
                        "supplier_type" => "0",
                        "supplier_type_id" => "0",
                        "flighttext" => "",
                        "adult_pax" => $totaladult,
                        "adult_cost_pp" => 0,
                        "adult_markup" => 0,
                        "adult_gst" => 0,
                        "adult_total" => 0,
                        "totalcost_wom" => "0",
                        "total_markup" => "0",
                        "total_gst" => 0,
                        "totalflightcost" => (float) $totalCost - $totalMarkup,
                        "GstTaxFlight" => "1"
                    );

                    $travelitenaryaccomairArray = array(
                        'TPIntSysId' => $lasttravelitenaryID[1] ? $lasttravelitenaryID[1] : 0,
                        'SeqId' => 0,
                        'AgencySysId' => $agencyId ? $agencyId : 0,
                        'InvnItemSysId' => 0,
                        'IsFromAPI' => 0,
                        'SourceSysId' => 0,
                        'SupplierSysId' => '0',
                        'TripType' => (int) $inkey,
                        'CurrencyType' => $inventory[0]['CurrencySysId'],
                        'Cost' => (float) $flightCost,
                        'TotalCost' => (float) $flightPriceWithGST,
                        'FlightNumber' => $invalue[0]['AirlineCode'],
                        'AirlineSysId' => 1,
                        'ICSourceSysId' => 0,
                        'IsFromAgency' => 0,
                        'LocalFromTime' => (isset($invalue[0]['DepartureTime']) && trim($invalue[0]['DepartureTime'])) ? $invalue[0]['DepartureTime']->format('H:i') : '',
                        'LocalToTime' => (isset($inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime']) && trim($inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime'])) ? $inventoryAirlineArr[$inkey][count($invalue) - 1]['ArrivalTime']->format('H:i') : '',
                        'FromUTCTime' => '',
                        'ToUTCTime' => '',
                        'FlightCabinClass' => '',
                        'AdultPax' => $totaladult,
                        'ChildPax' => $totalchild,
                        'InfentPax' => $totalInfant,
                        'TotalPax' => $totalPax,
                        'IsSelectedOnPkg' => 0,
                        'IsDirect' => 0,
                        'DayLightSavingDiff' => 0,
                        'FlyingMinutes' => 0,
                        'SourcePlaceSysId' => 0,
                        'DestPlaceSysId' => 0,
                        'SourceAirportCode' => '',
                        'DestAirportCode' => '',
                        'AirportHaultMinutes' => 0,
                        'StopCount' => 0,
                        'Stops' => count($invalue) - 1,
                        'Rating' => 0,
                        'FllightFeatureMask' => 0,
                        'UpdatedByISSysId' => 0,
                        'CreatedByISSysId' => 0,
                        'ImageTN' => 0,
                        'ImgForList' => 0,
                        'ImgeDetails' => 0,
                        'UpdateDate' => $createDate,
                        'CreateDate' => $createDate,
                        'ApproveBy' => 0,
                        'ApprovalDate' => $createDate,
                        'IsApproved' => 1,
                        'IsActive' => 1,
                        'IsMarkForDel' => 0,
                        'encodedata' => json_encode($flightJson),
                        'XRefBookingId' => 0,
                        'XRefPNR' => 0,
                        'XRefCancellationlId' => 0,
                        'APIBookingRes' => 0,
                        'APICancellationRes' => 0,
                        'Discount' => 0,
                        'XServiceTaxAmount' => 0,
                        'GTXServiceTaxAmount' => 0,
                        'AgentServiceTaxAmount' => 0,
                        'AgentsCustomServiceTaxAmount' => 0,
                        'MarkUp' => (float) $flightMarkup,
                        'AgencyMarkUp' => 0,
                        'GTXMarkup' => 0,
                        'GTXCommission' => 0,
                        'AgencyCommission' => 0,
                        'Taxes' => 0,
                        'TDS' => 0,
                        'DiscountMsg' => 0,
                        'IsFixedTransport' => 0,
                        'AirlineRefPNR' => 0
                    );

                    $objPackage->insertData('TB_Agency_Customer_TravelPlan_Air', $travelitenaryaccomairArray);
                }
            }
            if ($tpproposalID > 0) {
                $extramarkup = isset($MarkupArray[0]) ? (int) $MarkupArray[0] : 0;
                $addonPackageData = [
                    'AgencySysId' => (int) $AgencySysId,
                    'TPSysId' => (int) $tpproposalID,
                    'CustomerSysId' => (int) $CustomerSysId,
                    'SupplierSysId' => 0,
                    'PlanType' => 5,
                    'InvnSysId' => 0,
                    'ServiceTitle' => 'Package',
                    'CurrencyType' => $travelplandata[0]['CurrencyType'] ? $travelplandata[0]['CurrencyType'] : 0,
                    'GSTTYPE' => $gsttype,
                    'Tax' => (float) ($XServiceTaxAmount),
                    'Cost' => (float) $Price,
                    'Markup' => (float) ($AgencyMarkUp + $extramarkup),
                    'TotalCost' => (float) $NetPrice,
                    'IsActive' => 1,
                ];
                //                echo "<pre>";print_r($addonPackageData);die;
                $saveAddonServicesData = $objPackage->saveAddonServicesData($addonPackageData);
            }
            //                        $roomjsonEncodedData = base64_encode($requestPerameter['roomjson']);
            //                        $travelpanitenaryEncodedData = base64_encode(json_encode($lasttravelitenaryID));
            //                        $this->_dbObj->commit();

            try {

                $response = Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($requestPerameter['roomjson'], $tpproposalID, $catID, $tourID, $MealTypeId, $main_trip_start_date, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);

                return array('TPSysId' => $tpproposalID, 'CurrencyType' => $travelplanmarketPrice[0]['CurrencyType']);
            } catch (Zend_Exception $e) {
                echo $error_Message = $e->getMessage();
                die;
            }
        } catch (Exception $e) {
            //echo $error_Message;
            //            $this->_dbObj->rollBack();
            throw new Exception($e->getMessage());
        }
    }

    public function GetOtherServices($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_OtherServices"));
        $select->where('TPIntSysId = ?', $tpsysID);
        $select->where('IsMarkForDelete = ?', 0);
        //        echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetAllTransportOption($tpsysID)
    {

        $select = "SELECT TPSysId,TransType,TransType,
        Type FROM TB_Agency_Customer_Trans_Fixed WHERE (TPSysId = '" . $tpsysID . "') AND 
        (IsMarkForDel = 0) AND (IsIncluded = 1) group by TPSysId,TransType,Type";

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetDayNumberByTpID($tpinstsysID)
    {
        $select = $this->_dbObj->select();
        $travel = array('Sequence');
        $select->from(array("TB_Agency_Customer_TravelPlan_Itenary"), $travel);
        $select->where('TPIntSysId = ?', $tpinstsysID);
        $select->where('IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function UpdateOptionalSSBYO($sightseeingID, $tpintsysID, $tpsysID, $roominfojson, $txt, $itenArr, $catID, $tourID, $MealTypeId = 0, $tripstartdate = 0, $MarketPlaceId = 1)
    {
        $updatewhere = array('InvnItemSysId IN(?) ' => $tpintsysID, 'SSSysId = ? ' => $sightseeingID);
        //       echo $tpsysID; print_r($updatewhere);print_r($tpintsysID);
        if ($txt == "Included") {
            $updateData = array('Type' => 'Optional');
        }
        if ($txt == "Optional") {
            $updateData = array('Type' => 'Included');
        }

        $updatequery = $this->_dbObj->update('TB_Agency_Customer_TravelPlan_SightSeeing', $updateData, $updatewhere);
        if ($updatequery) {
            //echo "SightSeeing Updated";
            $roominfo = base64_decode($roominfojson);
            echo Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfo, $tpsysID, $catID, $tourID, $MealTypeId, $tripstartdate, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);
        }
    }

    public function UpdateOptionalBYOActivity($actID, $tpintsysID, $tpsysID, $roominfojson, $txt, $itenArr, $catID, $tourID, $MealTypeId = 0, $tripstartdate = 0, $MarketPlaceId = 1)
    {
        $updatewhere = array('TPIntSysId IN(?) ' => $tpintsysID, 'TPActivitySysId = ? ' => $actID);
        if ($txt == "Included") {
            $updateData = array('Type' => 'Optional');
        }
        if ($txt == "Optional") {
            $updateData = array('Type' => 'Included');
        }

        $updatequery = $this->_dbObj->update('TB_Agency_Customer_TravelPlan_Itenary_Events', $updateData, $updatewhere);
        if ($updatequery) {
            //echo "Activity Updated";
            $roominfo = base64_decode($roominfojson);
            echo Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfo, $tpsysID, $catID, $tourID, $MealTypeId, $tripstartdate, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);
        }
    }

    public function UpdateHotelSelectionBYO($tpintsysID, $tpsysID, $roominfojson, $catID, $itenArr, $tourID, $InvnItemSysId, $MealTypeId = 0, $tripstartdate = 0, $MarketPlaceId = 1)
    {

        $updatewhere = array('TPIntSysId IN(?) ' => $tpintsysID, 'BYOPackType = ? ' => $catID, 'IsSelectedOnPkg = ?' => 1);
        if (!empty($MealTypeId)) {
            $updatewhere['MealPlanType = ?'] = $MealTypeId;
        }
        //        echo '<pre>';print_r($updatewhere);
        //        echo $tpsysID.'==='.$accomsysID; print_r($updatewhere);print_r($itenArr);
        $updateData = array('IsSelectedOnPkg' => '0');
        $this->_dbObj->update('TB_Agency_Customer_TravelPlan_Accom', $updateData, $updatewhere);

        ######## Check If Master is exist for the package or not ############
        $ischildexist = $this->IsChildExistPkg($tpintsysID, $catID, $MealTypeId);
        ######## UPDATE CHILD ID #################
        if (!empty($ischildexist)) {
            ######### First Make All the IsSelected Value 0 to all the Child ################
            $updatemasterID = array('MasterIntSysId IN(?) ' => $tpintsysID, 'BYOPackType = ? ' => $catID, 'IsSelectedOnPkg = ?' => 1);
            if (!empty($MealTypeId)) {
                $updatemasterID['MealPlanType = ?'] = $MealTypeId;
            }
            //           echo '<pre>child';print_r($updatemasterID);
            $updatemasterdata = array('IsSelectedOnPkg' => '0');
            $this->_dbObj->update('TB_Agency_Customer_TravelPlan_Accom', $updatemasterdata, $updatemasterID);
            ######### First Make All the IsSelected Value 0 to all the Child End ################
            ######### Make the Iselected = '1' based on MasterIntSysId and selected AccomSysId(HotelID) #########

            $whereclause = array('MasterIntSysId IN(?) ' => $tpintsysID, 'BYOPackType = ? ' => $catID, 'InvnItemSysId IN(?)' => $InvnItemSysId);
            if (!empty($MealTypeId)) {
                $whereclause['MealPlanType = ?'] = $MealTypeId;
            }
            //           echo '<pre>';print_r($whereclause);
            $updateaccomdata = array('IsSelectedOnPkg' => '1');
            $this->_dbObj->update('TB_Agency_Customer_TravelPlan_Accom', $updateaccomdata, $whereclause);

            ######### Make the Iselected = '1' based on MasterIntSysId and selected AccomSysId(HotelID) End #########
        }


        $updatemasterID = array('BYOPackType = ? ' => $catID, 'TPIntSysId IN(?) ' => $tpintsysID, 'InvnItemSysId = ? ' => $InvnItemSysId);
        if (!empty($MealTypeId)) {
            $updatemasterID['MealPlanType = ?'] = $MealTypeId;
        }
        $updatemasterdata = array('IsSelectedOnPkg' => '1');
        $this->_dbObj->update('TB_Agency_Customer_TravelPlan_Accom', $updatemasterdata, $updatemasterID);
        //       echo '<pre>';print_r($updatemasterID);
        $roominfo = base64_decode($roominfojson);
        echo Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfo, $tpsysID, $catID, $tourID, $MealTypeId, $tripstartdate, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);
    }

    public function UpdateTransportType($tpsysID, $roominfojson, $checkedvals, $catID, $transtype, $tpintsysID, $itenArr, $tourID, $MealTypeId = 0, $tripstartdate = 0, $MarketPlaceId = 1, $fixtranssysId = 0, $txt = 0)
    {
        //only for car
        if (empty($fixtranssysId)) {
            $updatewhere = array('TPSysId = ? ' => $tpsysID, 'TransType = ? ' => $transtype);
        } else {
            $updatewhere = array('FixTransSysId = ? ' => $fixtranssysId, 'TransType = ? ' => $transtype);
        }
        if ($txt == 1) {
            $updateData = array('IsIncluded' => 0);
        }
        if ($txt == 0) {
            $updateData = array('IsIncluded' => 1);
        }
        $updatequery = $this->_dbObj->update('TB_Agency_Customer_Trans_Fixed', $updateData, $updatewhere);

        //            for ($j = 0; $j < count($checkedvals); $j++) {
        //                $fixtransArrIDs = explode('__', @$checkedvals[$j]);
        //                $updatedData1 = array('IsIncluded' => '1', 'VehicleQty' => $fixtransArrIDs[2]);
        //                $whereclause = array('TPSysId = ? ' => $tpsysID, 'RouteVechSysId = ? ' => $fixtransArrIDs[0], 'VehSysId = ? ' => $fixtransArrIDs[1]);
        //                $this->_dbObj->update('TB_Agency_Customer_Trans_Fixed', $updatedData1, $whereclause);
        //            }
        //        $fixtransArrIDs = explode('__',$fixtransID);
        //        $whereclause = array('TPSysId = ? ' => $tpsysID,'RouteVechSysId = ? ' => $fixtransArrIDs[0],'VehSysId = ? ' => $fixtransArrIDs[1]);
        //        $whereData = array('IsIncluded' => '1');
        ////        print_r($updatewhere);print_r($whereclause);
        //        $this->_dbObj->update('TB_Agency_Customer_Trans_Fixed', $whereData, $whereclause);

        $roominfo = base64_decode($roominfojson);
        echo Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackageSeasonCost')->GetDynamicPackagePrice($roominfo, $tpsysID, $catID, $tourID, $MealTypeId, $tripstartdate, 'Customer', 'UpdateTable', 'ChangeRequest', $MarketPlaceId);
    }

    public function GetTravelPlanBYOItenaryID($tpsysID)
    {
        $select = $this->_dbObj->select();
        $tpintsysID = array('TPIntSysId', 'Cities');
        $select->from(array("TB_Agency_Customer_TravelPlan_Itenary"), $tpintsysID);
        $select->where('TPSysId = ?', $tpsysID);
        $select->where('IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchAll($select);

        return $result;
    }

    public function GetOnlyCustPackageActivityListBYO($packageId)
    {
        $sqlPackageActivity = "SELECT TBACE.*,TBICA.DurationStr as duration, TBICA.*					 
                        FROM TB_Agency_Customer_TravelPlan_Itenary_Events as TBACE 
						LEFT JOIN TB_IC_Activity as TBICA ON TBACE.TPActivitySysId=TBICA.ActivitySysId
						WHERE TBACE.IsActive = '1' AND TBACE.Type = 'Included'  AND TBACE.IsMarkForDel = '0' AND TBACE.TPIntSysId IN (SELECT TPIntSysId FROM TB_Agency_Customer_TravelPlan_Itenary WHERE TPSysId = '" . @$packageId . "')";
        //AND TB_TravelPlan_Itenary_Events.IsActive = '1' AND TB_TravelPlan_Itenary_Events.IsMarkForDel = '0'
        $resultPackageActivity = $this->_dbObj->query($sqlPackageActivity)->fetchAll();
        return $resultPackageActivity;
    }

    public function GetHotelPriceByCat($itnID, $catID, $MealTypeId = NULL)
    {
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_Accom"));
        $select->where('TPIntSysId = ?', $itnID);
        $select->where('BYOPackType = ?', $catID);
        if (!empty($MealTypeId)) {
            $select->where('MealPlanType = ?', $MealTypeId);
        }
        $select->where('IsMarkForDel = ?', 0);
        $select->where('IsSelectedOnPkg = ?', 1);
        //         echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetHotelPriceBYO($itnID, $roominfoarr, $catID, $MealTypeId = NULL)
    {
        $hotelInfo = $this->GetHotelPriceByCat($itnID, $catID, $MealTypeId);
        //       $roominfoarr = json_decode(base64_decode($roominfojson), 1);
        //       $roominfoarr = $roominfojson;

        $totalhotelprice = 0;
        if (!empty($hotelInfo)) {
            $totalhotelprice = Zend_Controller_Action_HelperBroker::getStaticHelper('DynamicPackage')->getTotlaCostOfHotelByTravelers($hotelInfo, $roominfoarr);
        }
        return $totalhotelprice;
    }

    public function getIncludedPackageSightseenList($packageId, $Type = NULL)
    {
        $cond = !empty($Type) ? "TBASCS.Type IN ('Included','Optional','Free','') " : "TBASCS.Type = 'Included'";
        $sqlPackageActivity = "SELECT TBGC.Title as CITYNAME,TBASCS.*,TBICS.DurationStr as duration, TBICS.*,TMC.Symbol,TBACTI.Sequence
                        FROM TB_Agency_Customer_TravelPlan_SightSeeing TBASCS 
                        LEFT JOIN TB_Agency_Customer_TravelPlan_Itenary TBACTI ON TBACTI.TPIntSysId=TBASCS.InvnItemSysId
						LEFT JOIN TB_IC_SightSeeing TBICS ON TBASCS.SSSysId=TBICS.SSSysId
                                                LEFT JOIN TB_Master_Geo_City TBGC ON TBICS.CitySysId=TBGC.CityId
                                                LEFT JOIN TB_Master_Currency TMC ON TMC.CurrencyType=TBASCS.CurrencyType
						WHERE TBASCS.IsActive = '1' AND TBASCS.IsMarkForDelete = '0' 
                                                AND $cond AND  TBASCS.InvnItemSysId IN 
                                                (SELECT TPIntSysId FROM TB_Agency_Customer_TravelPlan_Itenary WHERE TPSysId = '" . @$packageId . "') ORDER BY TBASCS.VersionId";
        //echo $sqlPackageActivity;
        //AND TB_TravelPlan_SightSeeing.IsActive = '1' AND TB_TravelPlan_SightSeeing.IsMarkForDelete = '0'
        $resultPackageActivity = $this->_dbObj->query($sqlPackageActivity)->fetchAll();
        return $resultPackageActivity;
    }

    public function GetAllTransportTypeBYO($tpsysID)
    {
        $select = $this->_dbObj->select();
        $selectedfields = array("*");
        $select->from(array("TB_Agency_Customer_Trans_Fixed"), $selectedfields);
        $select->where('TPSysId = ?', $tpsysID);
        $select->where('CostPerson > ?', 0);
        $select->where('TotalPrice > ?', 0);
        $select->where('IsIncluded = ?', 1);
        $select->where('IsGroup = ?', 0);
        $select->where('IsMarkForDel = ?', 0);
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetGroupCostWithoutCarBYO($tpsysID)
    {
        $select = $this->_dbObj->select();
        $selectedfields = array("*");
        $select->from(array("TB_Agency_Customer_Trans_Fixed"), $selectedfields);
        $select->where('TPSysId = ?', $tpsysID);
        $select->where('CostPerson > ?', 0);
        $select->where('TotalPrice > ?', 0);
        $select->where('IsIncluded = ?', 1);
        $select->where('TransType != ?', 'car');
        $select->where('IsMarkForDel = ?', 0);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetGroupTransport($tpsysID)
    {
        $select = $this->_dbObj->select();
        $selectedfields = array('TotalPrice', 'Capacity');
        $select->from(array("TB_Agency_Customer_Trans_Fixed"), $selectedfields);
        $select->where('TPSysId = ?', $tpsysID);
        $select->where('TransType = ?', 'car');
        $select->where('IsGroup = ?', '1');
        $select->where('IsMarkForDel = ?', 0);
        // echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function Getgroupsize($tpsysID)
    {
        $selectedcolumn = array("GroupSize");
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan"), $selectedcolumn);
        $select->where('TPSysId = ?', $tpsysID);
        $select->where('IsActive = ?', 1);
        $select->where('IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetIncludedOtherServices($tpsysID)
    {
        $selectedcolumn = array("*");
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_OtherServices"), $selectedcolumn);
        $select->where('TPIntSysId = ?', $tpsysID);
        $select->where('IsCostInclInTP = ?', 1);
        $select->where('IsMarkForDelete = ?', 0);
        //       echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetMarketWiseRateById($tpsysID, $catID, $tourID = NULL, $MealTypeId = NULL)
    {
        $selectedcolumn = array("*");
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_MarketWise_Rate"), $selectedcolumn);
        $select->where('TPIntSysId = ?', $tpsysID);
        if (!empty($tourID)) {
            $select->where('TourType = ?', $tourID);
        }
        if (!empty($MealTypeId)) {
            $select->where('MealPlanType = ?', $MealTypeId);
        }
        $select->where('PackCategoryId = ?', $catID);
        $select->where('IsMarkForDel = ?', 0);
        //       echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetMarketWiseRateBYOReadyMade($tpID, $catID, $tourID = NULL, $MealTypeId = NULL, $MarketPlaceId = NULL)
    {

        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->joinLeft(array('tb3' => "TB_Master_Currency"), "TB_Agency_Customer_TravelPlan_MarketWise_Rate.CurrencyType = tb3.CurrencyType", 'Symbol');
        $select->where('TPIntSysId = ?', $tpID);
        $select->where('PackCategoryId = ?', $catID);
        if (!empty($tourID)) {
            $select->where('TourType = ?', $tourID);
        }
        if (!empty($MealTypeId)) {
            $select->where('MealPlanType = ?', $MealTypeId);
        }
        if (!empty($MarketPlaceId)) {
            $select->where('MarketPlaceId = ?', $MarketPlaceId);
        } else {
            $select->where('MarketPlaceId = ?', 1);
        }
        $select->where('IsMarkForDel = ?', 0);
        //echo $select; exit;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetHotelFromAPIBYO($tpintID, $accomsysID, $versionID, $catID)
    {
        $select = $this->_dbObj->select();
        $travel_airline = array('Address', 'Stars');
        $select->from(array('TB1' => "TB_Agency_Customer_TravelPlan_Accom"));
        $select->joinLeft(array('TB2' => "TB_IC_Accomdation_API"), "TB2.AccomSysId = TB1.AccoSysId", $travel_airline);
        $select->where('TB1.TPIntSysId = ?', $tpintID);
        $select->where('TB1.VersionId != ?', $versionID);
        $select->where('TB1.BYOPackType = ?', $catID);
        $select->where('TB1.IsMarkForDel = ?', 0);
        $select->where('TB1.IsFromAPI = ?', 1);
        // echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSelectedHotelBYO($tpintID, $catID)
    {
        $select = $this->_dbObj->select();
        $selectedfields = array('IsFromAPI');
        $select->from(array("TB_Agency_Customer_TravelPlan_Accom"), $selectedfields);
        $select->where('TPIntSysId = ?', $tpintID);
        //        $select->where('BYOPackType = ?', $catID);
        $select->where('IsMarkForDel = ?', 0);
        $select->where('IsSelectedOnPkg = ?', 1);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTotalChild($tpintsysID, $catID, $MealTypeId = NULL)
    {
        //$selectedfields = array('MasterIntSysId');
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_Accom"));
        $select->where('MasterIntSysId = ?', $tpintsysID);
        $select->where('BYOPackType = ?', $catID);
        $select->where('IsSelectedOnPkg = ?', 1);
        if (!empty($MealTypeId)) {
            $select->where('MealPlanType = ?', $MealTypeId);
        }
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllService($tpsysID,$ServiceType = 0)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_OtherServices"));
        $select->joinLeft(array('tb2' => "TB_IC_Supplier"), "tb1.SupplierSysId = tb2.SupplierSysId", array('SupplierName'));
        $select->where('tb1.TPIntSysId = ?', $tpsysID);
        $select->where('tb1.IsMarkForDelete = ?', 0);
        if($ServiceType > 0){
            $select->where('tb1.ServiceType = ?', $ServiceType);
        }
        $select->order('tb1.VersionId ASC');
        //         echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSelectedOtherService($tpintsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb2' => "TB_Agency_Customer_TravelPlan_OtherServices"));
        $select->where('tb2.TPIntSysId = ?', $tpintsysID);
        $select->where('tb2.IsCostInclInTP = ?', 1);
        $select->where('tb2.IsMarkForDelete = ?', 0);
        echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetVehicleDetailsByDay($tpsysID, $transtpye = 'bus')
    {
        $select = $this->_dbObj->select();
        $sequence = array('Sequence', 'Cities');
        $select->from(array('tb2' => "TB_Agency_Customer_Trans_Fixed"));
        $select->join(array('tb3' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb3.TPIntSysId = tb2.TPIntSysId", $sequence);
        $select->where('tb2.TPSysId = ?', $tpsysID);
        $select->where('tb2.TransType = ?', $transtpye);
        $select->where('tb2.IsMarkForDel = ?', 0);
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSelectedVehiclePrice($tpsysID, $transtpye = 'bus')
    {
        $select = $this->_dbObj->select();
        $selectedcity = array('CostPerson', 'TotalPrice');
        $select->from(array('tb2' => "TB_Agency_Customer_Trans_Fixed"), $selectedcity);
        $select->where('tb2.TPSysId = ?', $tpsysID);
        $select->where('tb2.TransType = ?', $transtpye);
        $select->where('tb2.IsIncluded = ?', 1);
        $select->where('tb2.IsMarkForDel = ?', 0);
        //echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetAllCarDetails($tpsysID, $tourID = 1)
    {
        $isGroup = ($tourID == 1) ? 0 : 1;
        $select = $this->_dbObj->select();
        $selectedcity = array('Title');
        $select->from(array('tb2' => "TB_Agency_Customer_Trans_Fixed"));
        $select->join(array('tb3' => "TB_Agency_Transport_Route"), "tb3.RouteSysId = tb2.RouteSysId");
        $select->join(array('tb4' => "TB_Master_Geo_City"), "tb4.CityId = tb3.StartCitySysId", $selectedcity);
        $select->join(array('tb5' => "TB_Master_Vehicle"), "tb5.VehSysId = tb2.VehicleTypeSysId", array('VehName'));
        $select->where('tb2.TPSysId = ?', $tpsysID);
        $select->where('tb2.TransType = ?', 'car');
        $select->where('tb2.IsMarkForDel = ?', 0);
        $select->where('tb2.IsGroup = ?', $isGroup);
        $select->order('tb2.TotalPrice ASC');
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSelectedCarVehiclePrice($tpsysID, $tourID = 1)
    {
        $isGroup = ($tourID == 1) ? 0 : 1;
        $IsIncluded = ($tourID == 1) ? 1 : 0;
        $select = $this->_dbObj->select();
        $selectedcity = array('CostPerson', 'TotalPrice', 'Capacity');
        $select->from(array('tb2' => "TB_Agency_Customer_Trans_Fixed"), $selectedcity);
        $select->where('tb2.TPSysId = ?', $tpsysID);
        $select->where('tb2.TransType = ?', 'car');
        $select->where('tb2.IsIncluded = ?', $IsIncluded);
        $select->where('tb2.IsMarkForDel = ?', 0);
        $select->where('tb2.IsGroup = ?', $isGroup);
        //echo $select;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    // this function used for agency-leads controlles filter
    public function GetAgencyLeadListFilter($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = 500)
    {
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            $select->limit($limit);
        }
        $arrLeadSource = array('Title as LeadSource');
        $arrMediumSource = array('tb8.CampaignName as LeadMedium');
        $arCampaignSource = array('tb9.CampaignName as LeadCampaign');
        //$travelplanarray = array('Title', 'MasterTPSysId', 'IsDraft', 'DraftActiveTab', 'TPSysId', 'StatusType', 'RoomInfoJson', 'StartDate', 'ValidTill', 'PlanBookingId', 'PlanType', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'CreateDate', 'MinPax', 'SourcePlaceSysId', 'SourcePlaces', 'DestinationPlacesSysId', 'DestinationPlaces', 'AdditionalReq', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'PlanBookingId', 'CuisineMask', 'hasFollowUp', 'hasIteration', 'VersionId', 'IsB2BProposal', 'IsMarkForDel');
        $travelplanarray = array('LeadQuality','TPSysId', 'StatusType', 'RoomInfoJson', 'StartDate', 'CreateDate', 'UpdateDate', 'RTRIM(LTRIM(DestinationPlaces)) AS Cities', 'PlanType', 'RTRIM(LTRIM(SourcePlaces)) AS SourcePlaces');
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $b2bagencyColumn = array('AgencyName as CompanyName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb8' => "TB_Agency_Medium_Master"), "tb8.MediumSysId = tb1.MediumSysId", $arrMediumSource);
        $select->joinLeft(array('tb9' => "TB_Agency_Campaign_Master"), "tb9.CampSysId = tb1.CampaignSysId", $arCampaignSource);

        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb6.UserSysId = tb3.CreatedByUserSysId", $b2bagencyColumn);
        if (!empty($getData['customername'])) {
            $select->Where("tb3.FirstName like '%" . $getData['customername'] . "%' OR tb3.LastName like '%" . $getData['customername'] . "%' OR (RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) = '" . $getData['customername'] . "'");
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customeremail'])) {
            $select->Where('tb3.EmailId like ' . "'%" . $getData['customeremail'] . "%'" . ' ');
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['lead_stage'])) {
            $lead_stage = $getData['lead_stage'];
            $select->Where('tb1.StatusType IN (' . $lead_stage . ')');
        } else {
            $lead_stage = "";
            if (isset($getData['filter_name']) && $getData['filter_name'] != 'overall') {
                if ($getData['filter_name'] == 'inprogress') {
                    $lead_stage = "1, 2, 58, 36, 20,3,86,26,83,84,62,69,125";
                } else if ($getData['filter_name'] == 'confirmed') {
                    $lead_stage = "29, 21, 22, 23, 24, 38, 37, 34, 35, 122,143";
                } else if ($getData['filter_name'] == 'rejected') {
                    $lead_stage = "25, 28, 30, 31, 32, 33";
                } else if ($getData['filter_name'] == 'callback') {
                    $lead_stage = "69";
                }
                if ($lead_stage != "") {
                    $select->Where('tb1.StatusType IN (' . $lead_stage . ')');
                }
            } else {
                //$select->Where('tb1.StatusType IN (1,2)');
            }
        }
        (@$getData['lead_type'] == NULL) ? '' : $select->Where("tb3.IsB2BAgent = ?", $getData['lead_type']);
        if (!empty($getData['UserSysId'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['UserSysId']);
        }
        if (isset($getData['plan_type']) && !empty($getData['plan_type'])) {
            $select->Where('tb1.PlanType = ?', $getData['plan_type']);
        }
        if (!empty($getData['agencyUserFilter'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['agencyUserFilter']);
        }

        if (!empty($getData['dateFrom']) && !empty($getData['dateTo'] && $getData['dateTo'] != '__-__-____' && $getData['dateFrom'] != '__-__-____')) {
            $dateFromEx = explode('-', $getData['dateFrom']);
            $dateToEx = explode('-', $getData['dateTo']);
            $dateFrom = $dateFromEx[2] . '-' . $dateFromEx[1] . '-' . $dateFromEx[0];
            $dateTo = $dateToEx[2] . '-' . $dateToEx[1] . '-' . $dateToEx[0];
            $dateTos = date('Y-m-d', strtotime($dateTo . ' +1 days'));
            $select->Where('CONVERT(date,tb1.CreateDate) >= ?', $dateFrom);
            $select->Where('CONVERT(date,tb1.CreateDate) <= ?', $dateTo);
        }
        if (!empty($getData['TravelFromDate']) && !empty($getData['TravelToDate'] && $getData['TravelToDate'] != '__-__-____' && $getData['TravelFromDate'] != '__-__-____')) {
            $TravelFromDateEx = explode('-', $getData['TravelFromDate']);
            $TravelToDateEx = explode('-', $getData['TravelToDate']);
            $TravelFromDate = $TravelFromDateEx[2] . '-' . $TravelFromDateEx[1] . '-' . $TravelFromDateEx[0];
            $TravelToDate = $TravelToDateEx[2] . '-' . $TravelToDateEx[1] . '-' . $TravelToDateEx[0];
            $TravelToDates = date('Y-m-d', strtotime($TravelToDate . ' +1 days'));
            $select->Where('CONVERT(date,tb1.StartDate) >= ?', $TravelFromDate);
            $select->Where('CONVERT(date,tb1.StartDate) <= ?', $TravelToDate);
        }
        if ($AgencySysId != 4913) {
            if (isset($getData['POST']) && empty($getData['POST'])) {
                $date = strtotime(date("Y-m-d", strtotime("-1 month")));
                $befor30days = date('Y-m-d', $date);
                $select->Where('CONVERT(date,tb1.CreateDate) >= ?', $befor30days);
                $select->Where('CONVERT(date,tb1.CreateDate) <= ?', date("Y-m-d", strtotime("+1 day")));
            }
        }
        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }
        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            $select->Where(" tb1.IsDraft = '1'"); // is active condition removed by amit for website source 
        }
        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);
        if ($AgencySysId != 2645) {
            $select->Where('tb1.IsMarkForDel = ?', 0);
        }
        $select->Where('tb2.IsMarkForDel = ?', 0);
        // $select->Where('StatusType = 1 OR StatusType = 2');
        $select->order("tb1.UpdateDate DESC");
        //echo $select; exit;
        return $select;
    }

    public function GetAgencyLeadListFilterTemp($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = 500)
    {
        //$this->ReportingToSysId = '';
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            $select->limit($limit);
        }
        $arrLeadSource = array('Title as LeadSource');
        $travelplanarray = array('Title', 'MasterTPSysId', 'IsDraft', 'DraftActiveTab', 'TPSysId', 'StatusType', 'RoomInfoJson', 'StartDate', 'ValidTill', 'PlanBookingId', 'PlanType', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'CreateDate', 'MinPax', 'SourcePlaceSysId', 'SourcePlaces', 'DestinationPlacesSysId', 'DestinationPlaces', 'AdditionalReq', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'PlanBookingId', 'CuisineMask', 'hasFollowUp', 'hasIteration', 'VersionId', 'IsB2BProposal');
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $b2bagencyColumn = array('AgencyName as CompanyName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb6.UserSysId = tb3.CreatedByUserSysId", $b2bagencyColumn);
        // $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId'));
        //filter conditions 

        if (!empty($getData['customername'])) {
            //$select->Where('tb3.FirstName like ' . "'%" . $getData['customername'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customername'] . "%'" . ' ');
            $select->Where("tb3.FirstName like '%" . $getData['customername'] . "%' OR tb3.LastName like '%" . $getData['customername'] . "%' OR (RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) = '" . $getData['customername'] . "'");
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customeremail'])) {
            $select->Where('tb3.EmailId like ' . "'%" . $getData['customeremail'] . "%'" . ' ');
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['lead_stage'])) {
            $lead_stage = $getData['lead_stage'];
            //print_r($lead_stage);die;
            $select->Where('tb1.StatusType IN (' . $lead_stage . ')');
            // $select->Where('tb1.StatusType IN(' . $lead_stage . ')');
        }
        (@$getData['lead_type'] == NULL) ? '' : $select->Where("tb3.IsB2BAgent = ?", $getData['lead_type']);
        if (!empty($getData['UserSysId'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['UserSysId']);
        }
        //print_r($getData);die;
        if (!empty($getData['dateFrom']) && !empty($getData['dateTo'] && $getData['dateTo'] != '__-__-____' && $getData['dateFrom'] != '__-__-____')) {
            $dateFromEx = explode('-', $getData['dateFrom']);
            $dateToEx = explode('-', $getData['dateTo']);
            $dateFrom = $dateFromEx[2] . '-' . $dateFromEx[1] . '-' . $dateFromEx[0];
            $dateTo = $dateToEx[2] . '-' . $dateToEx[1] . '-' . $dateToEx[0];
            $dateTos = date('Y-m-d', strtotime($dateTo . ' +1 days'));
            $select->Where('tb1.CreateDate >= ?', $dateFrom);
            $select->Where('tb1.CreateDate <= ?', $dateTos);
        }
        //print_r($getData);die;
        if (isset($getData['POST']) && empty($getData['POST'])) {
            $date = strtotime(date("Y-m-d", strtotime("-1 month")));
            $befor30days = date('Y-m-d', $date);
            $select->Where('tb1.CreateDate >= ?', $befor30days);
            $select->Where('tb1.CreateDate <= ?', date("Y-m-d", strtotime("+1 day")));
        }
        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            //$select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
            $select->Where(" tb1.IsDraft = '1'"); // is active condition removed by amit for website source 
        } else {
            //$select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter

        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        //echo $ReportingToSysId;die;
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);


        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7, 8, 9)); // 1- for flight, 2-for hotel,5-for package,6-for visa,7-for forex,8-for activity,9-for sightseeing
        $select->order("tb1.UpdateDate DESC");
        //echo $select;die;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetDynamicCustomerMarketwiserateDate($packageId = NULL, $tripdate = NULL, $catID = 1, $tourType = 1)
    {
        $whereCondition = " TPIntSysId = '" . @$packageId . "'  AND PackCategoryId = '" . @$catID . "' AND TourType = '" . $tourType . "'  AND IsMarkForDel = '0' AND IsActive = '1' AND  '$tripdate' BETWEEN CAST(TBTPMWR.FromDate AS DATE) AND CAST(TBTPMWR.ToDate AS DATE) ";
        $select = $this->_dbObj->select()
            ->from(array("TBTPMWR" => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"))
            ->where($whereCondition);
        //       echo $select; 
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function IsChildExistPkg($tpintsysID, $catID, $MealTypeId = NULL)
    {
        $selectedfields = array('TPIntSysId');
        $select = $this->_dbObj->select();
        $select->from(array("TB_Agency_Customer_TravelPlan_Accom"), $selectedfields);
        $select->where('MasterIntSysId IN(?)', $tpintsysID);
        $select->where('BYOPackType = ?', $catID);
        $select->where('IsSelectedOnPkg = ?', 1);
        if (!empty($MealTypeId)) {
            $select->where('MealPlanType = ?', $MealTypeId);
        }
        //         echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllProposalListDetails($leadID = null, $AgencySysId = 0, $AgentSysId = 0)
    {
        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        $select = $this->_dbObj->select();
        $travelplanarray = array('IsGTXNetwork', 'TPSysId', 'MasterTPSysId', 'PlanBookingId', 'VersionId', 'CreateDate', 'UpdateDate', 'CustomerSysId', 'PlanType', 'StatusType', 'Readymade', 'IsPriceShared', 'DestinationPlaces', 'Cities', 'RoomInfoJson', 'PkgSellValidTill', 'PackSpecType', 'StartDate', 'NetPrice', 'TotalCost', 'AgentSysId', 'hasFollowUp', 'hasIteration', 'LeadQuality', 'IsOnlySightseeingPkg', 'TotalCostGen');
        $customerarray = array('FirstName', 'LastName', 'Contacts', 'EmailId', 'Title as salutation', 'countrycode');
        $arrSupplier = array('FirstName as SupplierFirstName', 'LastName as SupplierLastName');
        $userinboxarray = array('UpdateDate as ChatUpdateDate', 'IsAgent');
        $arrLeadSource = array('Title as LeadSource');
        $arrMasterdata = array('CreateDate as MasterCreateDate');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        //$select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId" , $userinboxarray);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.AgentSysId", array(new Zend_Db_Expr('tb4.FirstName as ownerName'), 'Designation'));
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb6.SupplierSysId = tb1.SupplierSysId", $arrSupplier);
        $select->joinInner(array('tb7' => "TB_Agency_Customer_TravelPlan_Query"), "tb1.MasterTPSysId = tb7.TPSysId", $arrMasterdata);
        $select->joinLeft(array('tb8' => "TB_Master_Currency"), "tb1.CurrencyType = tb8.CurrencyType", 'Symbol');
        $select->joinLeft(array('tb9' => "TB_Agency_Sent_Sms_Email"), "tb1.TPSysId = tb9.TPSysId AND tb9.TypeSysId = 1 AND (tb9.Source = 1 or tb9.Source = 3) AND tb9.UserType = 1 AND tb9.CustomerSysId != ''", array('RefSysId', 'RefSysStatus'));
        //        $select->joinLeft(array('tb22' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb22.TPSysId", array());
        //        $select->joinLeft(array('tb33' => "TB_Agency_Customer_TravelPlan_Air"), "tb22.TPIntSysId = tb33.TPIntSysId", array());
        //        $select->joinLeft(array('tb66' => "TB_IC_Trans_API_Air"), "tb33.InvnItemSysId = tb66.TBQAirInvenSysId", array('IsQuickProposal'));

        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.MasterTPSysId > ?', 0);
        $select->where('tb1.CustomerSysId > ?', 0);
        $select->where('tb1.StatusType <> ?', 11); // 11 status type for proposal expired
        $select->where('tb1.IsB2BProposal = ?', 0); // 1 for b2b
        //  $select->where('tb9.TypeSysId = ?', 1); // For Email Status
        // $select->where('tb9.Source = ?', 1);


        if ($this->strCondition != "") {
            $select->where("1=1 " . $this->strCondition);
        } else {

            $select->where('tb1.StatusType > ?', 3);
            if (!$this->isAdmin) {
                $select->where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId));
            }
        }
        if ($this->strConditionExpired != "") {
            $select->where("1=1 " . $this->strConditionExpired);
        }
        $select->order($this->strOrder);

        //echo $select; exit;
        //$result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function getHotelDetailsByAccomId($intAccomSysId, $TPIntSysId)
    {
        $agencyMarkup = array('NetCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom"), $agencyMarkup);
        $select->where("tbl.AccoSysId = ?", $intAccomSysId);
        $select->where("tbl.TPIntSysId = ?", $TPIntSysId);
        $select->where("tbl.IsActive = ?", 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getAllSupplierForDynamicPackageByTpId($TPSysId)
    {
        $travelplanIetnaryData = $this->GetCustomerTravelPlanOnlyItenary($TPSysId);
        for ($i = 0; $i < count($travelplanIetnaryData); $i++) {
            $travelpanitenary[] = $travelplanIetnaryData[$i]['TPIntSysId'];
        }
        $detailArray = array();
        if (count($travelpanitenary) > 0) {
            $tplanitenayvalues = implode(",", $travelpanitenary);
            $detailArray = $this->getAllSupplierForDynamicPackage($tplanitenayvalues);
            //$detailArray[]=$this->GetCustTravelPlanOtherServicesIds($tplanitenayvalues);
            //$detailArray[]=$this->GetCustTravelPlanAccomIds($tplanitenayvalues);
            //$detailArray[]=$this->GetCustTravelPlanAirIds($tplanitenayvalues);
            //$detailArray[]=$this->GetCustTravelPlanEventIds($tplanitenayvalues);
            //$detailArray[]=$this->GetCustTravelPlanSSIds($tplanitenayvalues);
        }
        return $detailArray;
    }

    public function getAllSupplierForDynamicPackage($tplanitenayvalues)
    {
        $columnArray = array('SupplierSysId');
        $userinboxarray = array('SupplierName');
        $query1 = $this->_dbObj->select()
            ->from(array('tb1' => 'TB_Agency_Customer_TravelPlan_OtherServices'), $columnArray)
            ->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb1.SupplierSysId = tb6.SupplierSysId", $userinboxarray)
            ->where('tb1.TPIntSysId IN(' . $tplanitenayvalues . ')')
            ->Where('tb1.IsActive = ?', 1)
            ->Where('tb1.IsMarkForDelete = ?', 0);
        $query2 = $this->_dbObj->select()
            ->from(array('tb2' => 'TB_Agency_Customer_TravelPlan_Accom'), $columnArray)
            ->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb2.SupplierSysId = tb6.SupplierSysId", $userinboxarray)
            ->where('tb2.TPIntSysId IN(' . $tplanitenayvalues . ')')
            ->Where('tb2.IsActive = ?', 1)
            ->Where('tb2.IsMarkForDel = ?', 0);
        $query3 = $this->_dbObj->select()
            ->from(array('tb3' => 'TB_Agency_Customer_TravelPlan_Air'), $columnArray)
            ->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb3.SupplierSysId = tb6.SupplierSysId", $userinboxarray)
            ->where('tb3.TPIntSysId IN(' . $tplanitenayvalues . ')')
            ->Where('tb3.IsActive = ?', 1)
            ->Where('tb3.IsMarkForDel = ?', 0);
        $query4 = $this->_dbObj->select()
            ->from(array('tb4' => 'TB_Agency_Customer_TravelPlan_Itenary_Events'), $columnArray)
            ->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb4.SupplierSysId = tb6.SupplierSysId", $userinboxarray)
            ->where('tb4.TPIntSysId IN(' . $tplanitenayvalues . ')')
            ->Where('tb4.IsActive = ?', 1)
            ->Where('tb4.IsMarkForDel = ?', 0);
        $query5 = $this->_dbObj->select()
            ->from(array('tb5' => 'TB_Agency_Customer_TravelPlan_SightSeeing'), $columnArray)
            ->joinLeft(array('tb6' => "TB_IC_Supplier"), "tb5.SupplierSysId = tb6.SupplierSysId", $userinboxarray)
            ->where('tb5.InvnItemSysId IN(' . $tplanitenayvalues . ')')
            ->Where('tb5.IsActive = ?', 1)
            ->Where('tb5.IsMarkForDelete = ?', 0);

        $select = $this->_dbObj->select()->union(array($query1, $query2, $query3, $query4, $query5), Zend_Db_Select::SQL_UNION);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /* 	public function GetCustTravelPlanOtherServicesIds($tplanitenayvalues)
      {
      $columnArray=array('SupplierSysId');
      $select = $this->_dbObj->select();
      $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_OtherServices"),$columnArray);
      $select->Where('tb1.TPIntSysId IN ('.$tplanitenayvalues.')');
      $select->Where('tb1.IsMarkForDelete = ?', '0');
      $select->Where('tb1.IsActive = ?', '1');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
      public function GetCustTravelPlanAccomIds($tplanitenayvalues){
      $columnArray=array('SupplierSysId');
      $select = $this->_dbObj->select();
      $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom"),$columnArray);
      $select->Where('tbl.TPIntSysId IN ('.$tplanitenayvalues.')');
      $select->Where('tbl.IsMarkForDel = ?', '0');
      $select->Where('tbl.IsActive = ?', '1');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
      public function GetCustTravelPlanAirIds($tplanitenayvalues){
      $columnArray=array('SupplierSysId');
      $select = $this->_dbObj->select();
      $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Air"),$columnArray);
      $select->Where('tb1.TPIntSysId IN ('.$tplanitenayvalues.')');
      $select->Where('tb1.IsMarkForDel = ?', '0');
      $select->Where('tb1.IsActive = ?', '1');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
      public function GetCustTravelPlanEventIds($tplanitenayvalues){
      $columnArray=array('SupplierSysId');
      $select = $this->_dbObj->select();
      $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Itenary_Events"),$columnArray);
      $select->Where('tb1.TPIntSysId IN ('.$tplanitenayvalues.')');
      $select->Where('tb1.IsMarkForDel = ?', '0');
      $select->Where('tb1.IsActive = ?', '1');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
      public function GetCustTravelPlanSSIds($tplanitenayvalues){
      $columnArray=array('SupplierSysId');
      $select = $this->_dbObj->select();
      $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_SightSeeing"),$columnArray);
      $select->Where('tb1.InvnItemSysId IN ('.$tplanitenayvalues.')');
      $select->Where('tb1.IsMarkForDelete = ?', '0');
      $select->Where('tb1.IsActive = ?', '1');
      //echo $select;
      $result = $this->_dbObj->fetchAll($select);
      return $result;
      }
     */

    public function GetCustomerVisaProposal($MasterTPSysId, $CustomerSysId = NULL, $AgencySysId = NULL, $TPSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('MasterTPSysId', 'VersionId', 'TPSysId', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'MarkUp', 'XServiceTaxAmount', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryVisaColumn = array('VisaSysId', 'VisaDuration', 'VisaValidity');
        $travelVisaColumn = array('InvnVisaAllSysId', 'VisaName', 'VisaCategory', 'DocsRequiredText', 'DocName1', 'DocName2', 'DocName3', 'DocName4', 'DocName5', 'DocName6', 'DocFileName1', 'DocFileName2', 'DocFileName3', 'DocFileName4', 'DocFileName5', 'DocFileName6', 'BasicRequirementsText', 'EmbassyAddressText', 'PrecessingTime', 'VisaRequired');

        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Visa"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryVisaColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_Visa"), "tb3.VisaSysId = tb4.InvnVisaAllSysId", $travelVisaColumn);
        $select->where('tb1.MasterTPSysId = ?', $MasterTPSysId);
        $TPSysId ? $select->where('tb1.TPSysId = ?', $TPSysId) : '';
        $CustomerSysId ? $select->where('tb1.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tb1.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order('tb1.UpdateDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getTravelPlanDetailsByTPSysId($TPSysId, $IDType = '')
    {
        $travelPlanDetails = array('TPSysId', 'GSTSharedMode', 'AgencySysId','AgentSysId', 'PlanType', 'NetPrice', 'Price', 'AgentServiceTaxAmount', 'XServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'ServiceTaxOnCustomDiscount', 'MarkUp', 'AgencyMarkUp', 'GTXMarkUp', 'LeadSysId','IsB2Bproposal','B2BAgencySysId');
        $customerDetails = array('CustomerSysId', 'EmailId', 'FirstName', 'LastName', 'IsB2BAgent', 'Title', 'Contacts', 'countrycode');
        $select = $this->_dbObj->select();
        if ($IDType == 'Query') {
            $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"), $travelPlanDetails);
        } else {
            $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanDetails);
        }

        $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb2.CustomerSysId", $customerDetails);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerVisaleadDetail($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('VersionId', 'TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details', 'IsB2BProposal', 'EmailText');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryVisaColumn = array('VisaSysId', 'NetCost', 'VisaDuration', 'VisaValidity');
        $travelVisaColumn = array('InvnVisaAllSysId', 'IsAgentSpec', 'ICSourceSysId', 'NationalitySysId', 'CountriesCoveredSysId', 'VisaName', 'VisaRequired', 'VisaCategory', 'VisaType', 'VisaValidity', 'VisaDuration', 'VisaAdultRates', 'VisaChildRates', 'VisaInfantRates', 'VisaFamilyOfRates', 'CreateDate', 'UpdateDate', 'IsApproved', 'ApproveDate', 'ApproveBy', 'IsActive', 'IsMarkForDel', 'SupplierSysId', 'CurrencyType as visaCurrencyType', 'DocsRequiredText', 'DocName1', 'DocFileName1', 'DocName2', 'DocFileName2', 'DocName3', 'DocFileName3', 'DocName4', 'DocFileName4', 'DocName5', 'DocFileName5', 'DocName6', 'DocFileName6', 'PrecessingTime', 'BasicRequirementsText', 'EmbassyAddressText', 'Iswebsite');
        //        $travelVisaColumn = array('VisaName','PrecessingTime');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId AND tb1.AgencySysId = tb2.AgencySysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Visa"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryVisaColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_Visa"), "tb3.VisaSysId = tb4.InvnVisaAllSysId", $travelVisaColumn);
        $select->where('tb1.TPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetVisaCustomerDetailsPax($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('VisaSysId', 'NetCost', 'XrefBookingId', 'XRefVoucherNo', 'VisaDuration', 'VisaValidity');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $travelVisaColumn = array('VisaName', "PrecessingTime", "VisaRequired", "VisaCategory", "PassportExpiryDays");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Visa"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_MP_Inventory_Visa"), "tb3.VisaSysId = tb5.InvnVisaAllSysId", $travelVisaColumn);
        //$select->joinLeft(array('tb5' => "TB_Agency_Customer_Members"), "tb5.CustomerSysId = tb1.CustomerSysId" , $arrCustomerMembers);
        //$select->joinLeft(array('tb6' => "TB_Agency_Customer_TravelPlan_Pax"), "tb5.MemberSysId = tb6.MemberSysId" , $arrCustomerMembersPax);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetVisaCustomerDetailsTrx($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('VisaSysId', 'NetCost', 'XrefBookingId', 'XRefVoucherNo', 'VisaDuration', 'VisaValidity');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate');
        $travelVisaColumn = array('VisaName', "PrecessingTime");
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Visa"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_MP_Inventory_Visa"), "tb3.VisaSysId = tb5.InvnVisaAllSysId", $travelVisaColumn);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb7' => "TB_Trx"), "tb7.TrxSysId = tb6.TrxSysId", $arrTBTrx);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getArchiveProposalList($getData = [])
    {

        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'MasterTPSysId', 'PlanBookingId', 'VersionId', 'CreateDate', 'UpdateDate', 'CustomerSysId', 'PlanType', 'StatusType', 'Readymade', 'IsPriceShared', 'DestinationPlaces', 'Cities', 'RoomInfoJson', 'PkgSellValidTill', 'PackSpecType', 'StartDate', 'NetPrice', 'AgentSysId');
        $customerarray = array('FirstName', 'LastName', 'Contacts', 'EmailId');
        $userinboxarray = array('UpdateDate as ChatUpdateDate', 'IsAgent');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId", $userinboxarray);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.AgentSysId", array(new Zend_Db_Expr('tb4.FirstName as ownerName'), 'Designation'));

        //                $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.MasterTPSysId" , array('ToDoSysId','Type as todoType'));
        //$select->where("tb1.IsActive = ?", 0);
        $select->where("tb1.IsMarkForDel = ?", 1);

        $select->where('tb1.AgencySysId = ?', $getData['AgencySysId']);
        //        $select->where('tb1.MasterTPSysId > ?',0);
        //        $select->where('tb1.CustomerSysId > ?',0);
        //$select->where('tb1.StatusType = ?', 11); // 11 status type for proposal expired


        if (!empty($getData['AgentSysId'])) {
            $select->where('tb1.AgentSysId = ?', $getData['AgentSysId']);
        }

        // filter data here

        if (!empty($getData['customerName'])) {
            $select->where('tb3.FirstName LIKE ?', '%' . $getData['customerName'] . '%');
        }
        if (!empty($getData['customerEmail'])) {
            $select->where('tb3.EmailId LIKE ?', '%' . $getData['customerEmail'] . '%');
        }
        if (!empty($getData['customerMobile'])) {
            $select->where('tb3.Contacts LIKE ?', '%' . $getData['customerMobile'] . '%');
        }
        if (!empty($getData['TPSysId'])) {
            $select->where('tb1.TPSysId = (?)', $getData['TPSysId']);
        }
        if (!empty($getData['StatusType'])) {
            $select->where('tb1.StatusType = (?)', $getData['StatusType']);
        }
        $select->order('tb1.UpdateDate DESC');
        //        die($select);
        //        if( !empty($getData['customerMobile']) ) {
        //            $select->where('tb3.ContactNo1 LIKE ?', '%'.$getData['customerMobile'].'%' );
        //        }
        //		return $result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    // for sight seeing proposal public view function created by amit kumar dubey on 06 oct 2017
    public function GetCustomerSightSeeingProposal($MasterTPSysId, $CustomerSysId = NULL, $AgencySysId = NULL, $TPSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('TPSysId', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details', 'TPId');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenarySSColumn = array('XrefInvnItemSysId');
        $travelItenarySSMPColumn = array('InvnItemSysId');
        $travelSSColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_SightSeeing"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenarySSColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_SightSeeing"), "tb3.InvnItemSysId = tb4.InvnItemSysId", $travelItenarySSMPColumn);
        $select->joinLeft(array('tb5' => "TB_IC_SightSeeing"), "tb5.SSSysId = tb4.XRef", $travelSSColumn);
        $select->where('tb1.MasterTPSysId = ?', $MasterTPSysId);
        $TPSysId ? $select->where('tb1.TPSysId = ?', $TPSysId) : '';
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order('tb1.UpdateDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerSightSeeingleadDetail($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenarySSColumn = array('XrefInvnItemSysId', 'TotalCost');
        $travelItenarySSMPColumn = array('InvnItemSysId');
        $travelSSColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_SightSeeing"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenarySSColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_SightSeeing"), "tb3.InvnItemSysId = tb4.InvnItemSysId", $travelItenarySSMPColumn);
        $select->joinLeft(array('tb5' => "TB_IC_SightSeeing"), "tb5.SSSysId = tb4.XRef", $travelSSColumn);
        $select->where('tb1.TPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSightSeeingCustomerDetailsPax($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('XrefInvnItemSysId', 'TotalCost', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $travelSSColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_SightSeeing"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_SightSeeing"), "tb3.InvnItemSysId = tb5.SSSysId", $travelSSColumn);
        //$select->joinLeft(array('tb5' => "TB_Agency_Customer_Members"), "tb5.CustomerSysId = tb1.CustomerSysId" , $arrCustomerMembers);
        //$select->joinLeft(array('tb6' => "TB_Agency_Customer_TravelPlan_Pax"), "tb5.MemberSysId = tb6.MemberSysId" , $arrCustomerMembersPax);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetSightSeeingCustomerDetailsTrx($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo', 'DestinationPlaces');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('XrefInvnItemSysId', 'TotalCost', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate');
        $travelSSColumn = array('Title');
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_SightSeeing"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_SightSeeing"), "tb3.InvnItemSysId = tb5.SSSysId", $travelSSColumn);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb7' => "TB_Trx"), "tb7.TrxSysId = tb6.TrxSysId", $arrTBTrx);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // for activity proposal public view function created by amit kumar dubey on 07 oct 2017
    public function GetCustomerActivityProposal($MasterTPSysId, $CustomerSysId = NULL, $AgencySysId = NULL, $TPSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('VersionId', 'MasterTPSysId', 'TPSysId', 'TPId', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryActvityColumn = array('TPActivitySysId');
        $travelItenaryActvityMPColumn = array('InvnItemSysId');
        $travelActvityColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Itenary_Events"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryActvityColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_Activity"), "tb3.InvnItemSysId = tb4.InvnItemSysId", $travelItenaryActvityMPColumn);
        $select->joinLeft(array('tb5' => "TB_IC_Activity"), "tb5.ActivitySysId = tb4.XRef", $travelActvityColumn);
        $select->where('tb1.MasterTPSysId = ?', $MasterTPSysId);
        $TPSysId ? $select->where('tb1.TPSysId = ?', $TPSysId) : '';
        $CustomerSysId ? $select->where('tb1.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tb1.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order('tb1.UpdateDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerActivityleadDetail($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('VersionId', 'TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details', 'IsB2BProposal');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryActvityColumn = array('Title', 'TPActivitySysId', 'TotalCost');
        $travelItenaryActvityMPColumn = array('InvnItemSysId');
        $travelActvityColumn = array('DurationStr', 'DurationInMin');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Itenary_Events"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryActvityColumn);
        $select->joinLeft(array('tb4' => "TB_MP_Inventory_Activity"), "tb3.InvnItemSysId = tb4.InvnItemSysId", $travelItenaryActvityMPColumn);
        $select->joinLeft(array('tb5' => "TB_IC_Activity"), "tb5.ActivitySysId = tb4.XRef", $travelActvityColumn);
        $select->where('tb1.TPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetActivityCustomerDetailsPax($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_activity = array('TPActivitySysId', 'TotalCost', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $travelItenaryActvityMPColumn = array('InvnItemSysId');
        $travelActvityColumn = array('Title', 'DurationStr', 'DurationInMin');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Itenary_Events"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_activity);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);

        $select->joinLeft(array('tb5' => "TB_MP_Inventory_Activity"), "tb3.InvnItemSysId = tb5.InvnItemSysId", $travelItenaryActvityMPColumn);
        $select->joinLeft(array('tb6' => "TB_IC_Activity"), "tb6.ActivitySysId = tb5.XRef", $travelActvityColumn);
        //$select->joinLeft(array('tb5' => "TB_IC_Activity"), "tb3.InvnItemSysId = tb5.ActivitySysId" , $travelActvityColumn);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetActivityCustomerDetailsTrx($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo', 'DestinationPlaces');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('TPActivitySysId', 'TotalCost', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate');
        $travelActvityColumn = array('Title', 'DurationStr', 'DurationInMin');
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $travelItenaryActvityMPColumn = array('InvnItemSysId');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Itenary_Events"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_MP_Inventory_Activity"), "tb3.InvnItemSysId = tb5.InvnItemSysId", $travelItenaryActvityMPColumn);
        $select->joinLeft(array('tb6' => "TB_IC_Activity"), "tb6.ActivitySysId = tb5.XRef", $travelActvityColumn);
        $select->joinLeft(array('tb7' => "TB_Agency_Customer_Trx"), "tb7.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb8' => "TB_Trx"), "tb8.TrxSysId = tb7.TrxSysId", $arrTBTrx);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // for Insurance proposal public view function created by amit kumar dubey on 24 oct 2017
    public function GetCustomerInsuranceProposal($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('TPSysId', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryActvityColumn = array('MasterPolicySysId');
        $travelActvityColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Insurance"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryActvityColumn);
        $select->joinLeft(array('tb4' => "TB_Insurance_Company"), "tb3.MasterPolicySysId = tb4.InsuCompSysId", $travelActvityColumn);
        $select->where('tb1.MasterTPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $select->order('tb1.UpdateDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerForexleadDetail($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->where('tb1.TPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerInsuranceleadDetail($leadID, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details');
        $travelItenaryColumn = array('TPIntSysId');
        $travelItenaryActvityColumn = array('MasterPolicySysId', 'NetPaid');
        $travelActvityColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Insurance"), "tb2.TPIntSysId = tb3.TPIntSysId", $travelItenaryActvityColumn);
        $select->joinLeft(array('tb4' => "TB_Insurance_Company"), "tb3.MasterPolicySysId = tb4.InsuCompSysId", $travelActvityColumn);
        $select->where('tb1.TPSysId = ?', $leadID);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType > ?', 3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetInsuranceCustomerDetailsPax($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_activity = array('MasterPolicySysId', 'NetPaid', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $travelActvityColumn = array('Title');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Insurance"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_activity);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_Insurance_Company"), "tb3.MasterPolicySysId = tb5.InsuCompSysId", $travelActvityColumn);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetInsuranceCustomerDetailsTrx($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo', 'DestinationPlaces');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $travel_visa = array('MasterPolicySysId', 'NetPaid', 'XRefVoucherNo');
        $arrCustomerMembersPax = array('TPPaxSysId');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate');
        $travelActvityColumn = array('Title');
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Insurance"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_visa);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_Insurance_Company"), "tb3.MasterPolicySysId = tb5.InsuCompSysId", $travelActvityColumn);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb7' => "TB_Trx"), "tb7.TrxSysId = tb6.TrxSysId", $arrTBTrx);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetForexCustomerDetailsTrx($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'ProposalEmailTo', 'DestinationPlaces');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId');
        $arrTBTrx = array('Amount as TBTRXAmount', 'Markup as TBTRXMarkup', 'AgencyMarkUp as TBTRXAgencyMarkUp', 'GTXMarkUp as TBTRXGTXMarkUp', 'NetAmount as TBTRXNetAmount', 'TrxDate as TBTRXTrxDate');
        $arrAgencyCustomerTrx = array('XRefTrxNo as CTRXXRefTrxNo');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_Trx"), "tb6.TPSysId = tb1.TPSysId", $arrAgencyCustomerTrx);
        $select->joinLeft(array('tb7' => "TB_Trx"), "tb7.TrxSysId = tb6.TrxSysId", $arrTBTrx);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        //$select->order("tb6.MemberSysId DESC");
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllB2BProposalListDetails($leadID = null, $AgencySysId = 0, $AgentSysId = 0)
    {
        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'MasterTPSysId', 'PlanBookingId', 'VersionId', 'CreateDate', 'UpdateDate', 'CustomerSysId', 'PlanType', 'StatusType', 'Readymade', 'IsPriceShared', 'DestinationPlaces', 'Cities', 'RoomInfoJson', 'PkgSellValidTill', 'PackSpecType', 'StartDate', 'NetPrice', 'AgentSysId', 'hasFollowUp', 'hasIteration', 'LeadQuality', 'IsGTXNetwork');
        $agencyarray = array('DisplayName', 'Title');
        $b2bagencyColumn = array('Title as B2BTitle', 'DisplayName as B2BDisplayName');
        $arrSupplier = array('FirstName as SupplierFirstName', 'LastName as SupplierLastName');
        $customerarray = array('FirstName', 'LastName', 'EmailId', 'Contacts');
        $userinboxarray = array('UpdateDate as ChatUpdateDate', 'IsAgent');
        $arrMasterdata = array('CreateDate as MasterCreateDate');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User_Inbox"), "tb1.TPSysId = tb2.RefSysId", $userinboxarray);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb3.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb4' => "TB_Agency"), "tb1.AgencySysId = tb4.AgencySysId", $agencyarray);
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tb5.UserSysId = tb3.CreatedByUserSysId", array('FirstName as AgentFirstName', 'LastName as AgentLastName', 'Designation', 'ContactNo1', 'AgencyName'));
        $select->joinLeft(array('tb6' => "TB_Agency"), "tb6.AgencySysId = tb5.AgencySysId", $b2bagencyColumn);
        $select->joinLeft(array('tb7' => "TB_IC_Supplier"), "tb7.SupplierSysId = tb1.SupplierSysId", $arrSupplier);
        $select->joinInner(array('tb8' => "TB_Agency_Customer_TravelPlan_Query"), "tb1.MasterTPSysId = tb8.TPSysId", $arrMasterdata);
        $select->joinLeft(array('tb9' => "TB_Master_Currency"), "tb1.CurrencyType = tb9.CurrencyType", 'Symbol');
        // $select->joinLeft(array('tb10' => "TB_Agency_Sent_Sms_Email"), "tb1.TPSysId = tb10.TPSysId", array('RefSysId','RefSysStatus'));
        $select->joinLeft(array('tb10' => "TB_Agency_Sent_Sms_Email"), "tb1.TPSysId = tb10.TPSysId AND tb10.TypeSysId = 1 AND (tb10.Source = 1 or tb10.Source = 3) AND tb10.UserType = 1", array('RefSysId', 'RefSysStatus'));
        //$select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.MasterTPSysId" , array('ToDoSysId','Type as todoType'));
        //$select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId','Type as todoType','TPIntSysId'));
        $select->joinLeft(array('tb11' => "TB_Agency_User"), "tb11.UserSysId = tb1.AgentSysId", array('FirstName as SuperAgentFirstName', 'LastName as SuperAgentLastName'));
        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.MasterTPSysId > ?', 0);
        $select->where('tb1.CustomerSysId > ?', 0);
        $select->where('tb1.StatusType <> ?', 11); // 11 status type for proposal expired
        $select->where('tb1.IsB2BProposal = ?', 1);
        //   $select->where('tb10.TypeSysId = ?', 1);// 11 status type for proposal expired
        //$select->where('tb1.B2BAgencySysId <> ?', 0); // 11 status type for proposal expired


        if ($this->strCondition != "") {
            $select->where("1=1 " . $this->strCondition);
        } else {
            $select->where('tb1.StatusType > ?', 3);
            if (!$this->isAdmin) {
                $select->where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId));
            }
        }


        if ($this->strConditionExpired != "") {
            $select->where("1=1 " . $this->strConditionExpired);
        }
        $select->order($this->strOrder);
        //echo $select;
        //$result = $this->_dbObj->fetchAll($select);
        return $select;
    }

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

    public function GetDeletedCustomerTravelPlanItenary($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->Where('tbl.IsActive = ?', '1');

        $result = $this->_dbObj->fetchOne($select);
        return $result;
    }

    public function GetActivity($ActivitySysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_IC_Activity"));
        $select->where('tbl.ActivitySysId = ?', $ActivitySysId);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerItenaryAccomDetails($TPIntSysId, $vid = NULL, $intAccomSysId = NULL)
    {
        $icaccomodation = array('PrimaryContact as HotelPrimaryContact', 'SecondaryContact as HotelSecondaryContact');
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Accom"));
        $select->joinLeft(array('tb2' => "TB_IC_Accomdation"), "tb1.AccoSysId = tb2.AccomSysId", $icaccomodation);
        $select->joinLeft(array('tb3' => "TB_Master_Geo_City"), "tb1.XrefCityId = tb3.CityId", array("Title as CityName"));
        $select->joinLeft(array('tb4' => "TB_Master_Accom_MealType"), "tb1.MealPlanType = tb4.MealTypeId", array('Title as RoomMealType'));
        $select->Where('tb1.TPIntSysId = ?', $TPIntSysId);
        $vid ? $select->Where('tb1.VersionId = ?', $vid) : '';
        $select->Where('tb1.IsMarkForDel = ?', '0');
        $select->Where('tb1.IsActive = ?', '1');
        $select->Where("tb1.AccoSysId = ?", $intAccomSysId);
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getHotelDetailsByAccomIdFullfillment($intAccomSysId, $TPIntSysId)
    {
        $agencyMarkup = array('NetCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom_Fullfillment"), $agencyMarkup);
        $select->where("tbl.AccoSysId = ?", $intAccomSysId);
        $select->where("tbl.TPIntSysId = ?", $TPIntSysId);
        $select->where("tbl.IsActive = ?", 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getPriceDetailByCustId($AgencySysId, $CustomerSysId)
    {
        $agency_travel_trx = array('NetPrice', 'IsCancellationProtection', 'CancellationProtectionPrice', 'TotalCostGen', 'TPSysId');
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $agency_travel_trx);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_AddonServices"), "tb1.TPSysId = tb2.TPSysId AND tb2.PlanType = 21 AND tb2.IsActive= 1 and tb2.IsMarkForDelete = 0", array('Tax'));
        $AgencySysId ? $select->where('tb1.AgencySysId = ?', $AgencySysId) : '';
        $CustomerSysId ? $select->where('tb1.CustomerSysId = ?', $CustomerSysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->where('tb1.StatusType IN(13,17,7,102,123,104,81)');
        // echo $select; exit;
        //$select->where('tb1.StatusType NOT IN(123)');// 17 for booked 13 for partial
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getProfileDataForCustId($AgencySysId, $CustomerSysId)
    {
        $agency_travel = array('CuisineMask', 'HotelPreference', 'RoomInfoJson');
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $agency_travel);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.CustomerSysId = ?', $CustomerSysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);
        //$select->where('tb1.StatusType IN(13,17)'); // 17 for booked 13 for partial
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPublicProposalWithInventoryHotelList($leadId)
    {

        $travel = array('TPSysId', 'MasterTPSysId', 'AgencySysId', 'AgentSysId', 'Rating', 'TPSysId', 'StatusType', 'PlanBookingId', 'AgencySysId', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate');
        $travel_itenary = array('TPIntSysId as itenaryID', 'TPSysId');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'Taxes', 'SourceSysId as ICSourceSysId', 'AllowBooking', 'RateType', 'InvnItemSysId', 'SpecialRequest', 'APIBookingRes');
        $customer_details = array('CustomerSysId', 'EmailId');
        $accom_details = array('Title as hotelName', 'ShortName', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars');
        $arrAccomdationInventory = array('SupplierSysId', 'NetDOccupCost', 'NetSOccupCost');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Accom"), "tb6.InvnItemSysId = tb3.InvnItemSysId", $arrAccomdationInventory);
        //        $select->joinLeft(array('tb7' => 'TB_Master_RoomType'), 'tb7.RoomType = tb6.EconomyType ', array("Title as EconomyTypeTitle", "RoomType as RoomTypeId"));
        //        $select->joinLeft(array('tb8' => 'TB_Master_Accom_MealType'), 'tb8.MealTypeId = tb6.MealPlanType', array("Title as MealPlanTypeTitle", "MealTypeId"));
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tb3.IsActive = ?", 1);
        $select->where("tb4.IsActive = ?", 1);
        $select->where("tb5.IsActive = ?", 1);
        //$select->where("tb6.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->where("tb3.IsMarkForDel = ?", 0);
        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->where("tb5.IsMarkForDel = ?", 0);
        //$select->where("tb6.IsMarkForDelete = ?", 0);

        $select->where('tbl.MasterTPSysId = ?', $leadId);
        $select->where('tbl.StatusType > ?', 3);
        //        $select->where("tb7.RoomType != ''");
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanCustomerInvHotelDetails($tpID, $limit = 1)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('TPSysId', 'IsB2BProposal', 'IsCardChrgToCustomer', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'RoomInfoJson', 'AdditionalReq', 'StartDate', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'Title');
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName');
        $travel_itenary = array('TPIntSysId as itenaryID');
        $travel_accom = array('TPIntSysId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'ToDate as hotelToDate', 'AccoSysId', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'XServiceTaxAmount', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'NetCost', 'TotalCost', 'MarkUp as hotelMarkUp', 'GTXMarkup', 'AgencyMarkUp', 'SourceSysId as ICSourceSysId', 'RoomMemInfoJson', 'Taxes', 'IsfromAPI', 'TotalPax', 'Discounts', 'XrefBookingId', 'SpecialRequest', 'RoomTypeStr', 'MealPlanType', 'AllowBooking', 'RateType', 'InvnItemSysId');
        $accom_details = array('Title as hotelName', 'ShortName', 'CurrencyType', 'MinPublishedFare', 'Address as hotelAddress', 'Rating as AccomRating', 'Stars', 'DetailImg');
        $arrAccomdationInventory = array('MappingSysId', 'Adult', 'Child', 'FromDate as RoomFromDate', 'ToDate as RoomToDate');
        $arrCancPolicy = array('RoomIndex as CANCELPOLICYroomIndex', 'ChargeType as CANCELPOLICYChargeType', 'Charge as CANCELPOLICYCharge', 'Fromdate as CANCELPOLICYFromdate', 'Todate as CANCELPOLICYTodate');
        $arrAccomRoomInfo = array('RoomNumber as ACCOMROOMRoomNumber', 'OtherDetails as ACCOMROOMOtherDetails', 'Title as ACCOMROOMTitle', 'HotelNorms as ACCOMROOMHotelNorms', 'Amenities as ACCOMROOMAmenities');
        $arrCustomerMembers = array('Title as MEMBERTitle', 'Title as MEMBERTitle', 'FirstName as MEMBERFirstName', 'LastName as MEMBERLastName');

        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb5' => "TB_IC_Accomdation"), "tb5.AccomSysId = tb3.AccoSysId", $accom_details);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_TravelPlan_Accom_Invn_Mapping"), "tb6.InvnItemSysId = tb3.VersionId", $arrAccomdationInventory);
        $select->joinLeft(array('tb7' => 'TB_Master_RoomType'), 'tb7.RoomType = tb6.RoomType ', array("Title as EconomyTypeTitle", "RoomType as RoomTypeId"));
        $select->joinLeft(array('tb8' => 'TB_Master_Accom_MealType'), 'tb8.MealTypeId = tb6.MealPlanType', array("Title as MealPlanTypeTitle", "MealTypeId"));
        //        $select->joinLeft(array('tb7' => 'TB_Master_RoomType'), 'tb7.RoomType = tb6.EconomyType ', array("Title as EconomyTypeTitle", "RoomType as RoomTypeId"));
        //        $select->joinLeft(array('tb8' => 'TB_Master_Accom_MealType'), 'tb8.MealTypeId = tb6.MealPlanType', array("Title as MealPlanTypeTitle", "MealTypeId"));
        $select->joinLeft(array('tb9' => "TB_Agency_Customer_TravelPlan_Pax"), "tb1.TPSysId = tb9.TPSysId", array("MemberSysId"));
        $select->joinLeft(array('tb10' => "TB_Agency_Customer_Members"), "tb9.MemberSysId = tb10.MemberSysId", $arrCustomerMembers);
        $select->joinLeft(array('tb11' => "TB_IC_Supplier"), "tb3.SupplierSysId = tb11.SupplierSysId", array('SupplierName as HotelSupplierName', 'Designation as SupplierDesignation', 'SupplierSysId as HotelSupplierSysId'));
        $select->joinLeft(array('tb12' => "TB_Master_Currency"), "tb3.CurrencyType = tb12.CurrencyType", array('Symbol'));
        //$select->joinLeft(array('tb11' => "TB_IC_Accomdation_Room_CancellationPolicy"), "tb10.Accosysid = tb3.AccoSysId", $arrCancPolicy);
        $select->joinLeft(array('tb13' => "TB_Agency"), "tb4.AgencySysId = tb13.AgencySysId", array('DisplayName', 'PrimaryContactNo'));

        $select->where('tb1.TPSysId = ?', $tpID);
        if ($limit > 0) {
            $select->limit($limit);
        }

        //        echo $select;die;
        /* 			$select->where("tb1.IsActive = ?", 1);
          $select->where("tb2.IsActive = ?", 1);
          $select->where("tb3.IsActive = ?", 1);
          $select->where("tb4.IsActive = ?", 1);
          $select->where("tb5.IsActive = ?", 1);
          $select->where("tb6.IsActive = ?", 1);
          $select->where("tb1.IsMarkForDel = ?", 0);
          $select->where("tb2.IsMarkForDel = ?", 0);
          $select->where("tb3.IsMarkForDel = ?", 0);
          $select->where("tb4.IsMarkForDelete = ?", 0);
          $select->where("tb5.IsMarkForDel = ?", 0);
          $select->where("tb6.IsMarkForDelete = ?", 0);
         */
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAgencyQueryFilter($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = 500)
    {
        //$this->ReportingToSysId = '';
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            // $select->limit($limit);
        }
        $arrLeadSource = array('Title as LeadSource');
        $travelplanarray = array(
            'Title',
            'MasterTPSysId',
            'IsDraft',
            'DraftActiveTab',
            'TPSysId',
            'StatusType',
            'RoomInfoJson',
            'StartDate',
            'ValidTill',
            'PlanBookingId',
            'PlanType',
            'SupplierSysId',
            'CurrencyType',
            'AgencySysId',
            'AgentSysId',
            'CustomerSysId',
            'CreateDate',
            'UpdateDate',
            'MinPax',
            'SourcePlaceSysId',
            'SourcePlaces',
            'DestinationPlacesSysId',
            'DestinationPlaces',
            'AdditionalReq',
            'Cities',
            'Countries',
            'Price',
            'NetPrice',
            'CreatorSysId',
            'CuisineMask',
            'hasFollowUp',
            'hasIteration',
            'VersionId',
            'IsB2BProposal',
            'LeadQuality',
            'PKqueryType'
        );
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $b2bagencyColumn = array('AgencyName as CompanyName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb6.UserSysId = tb3.CreatedByUserSysId", $b2bagencyColumn);
        // $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId'));
        //filter conditions 

        if (!empty($getData['customername'])) {
            //$select->Where('tb3.FirstName like ' . "'%" . $getData['customername'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customername'] . "%'" . ' ');
            $select->Where("tb3.FirstName like '%" . $getData['customername'] . "%' OR tb3.LastName like '%" . $getData['customername'] . "%' OR (RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) = '" . $getData['customername'] . "'");
        }
        if (!empty($getData['agencyName'])) {
            $select->Where("tb6.AgencyName like '%" . $getData['agencyName'] . "%'");
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customeremail'])) {
            $select->Where('tb3.EmailId like ' . "'%" . $getData['customeremail'] . "%'" . ' ');
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customerQueryId'])) {
            $select->Where('tb1.TPSysId = ?', $getData['customerQueryId']);
        }
        if (!empty($getData['lead_stage'])) {
            $lead_stage = $getData['lead_stage'];
            //print_r($lead_stage);die;
            $select->Where('tb1.StatusType IN (?)', $lead_stage);
            // $select->Where('tb1.StatusType IN(' . $lead_stage . ')');
        }
        (@$getData['lead_type'] == NULL) ? '' : $select->Where("tb3.IsB2BAgent = ?", $getData['lead_type']);
        if (!empty($getData['UserSysId'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['UserSysId']);
        }
        //print_r($getData);die;
        if (!empty($getData['dateFrom']) && !empty($getData['dateTo'] && $getData['dateTo'] != '__-__-____' && $getData['dateFrom'] != '__-__-____')) {
            $dateFromEx = explode('-', $getData['dateFrom']);
            $dateToEx = explode('-', $getData['dateTo']);
            $dateFrom = $dateFromEx[2] . '-' . $dateFromEx[1] . '-' . $dateFromEx[0];
            $dateTo = $dateToEx[2] . '-' . $dateToEx[1] . '-' . $dateToEx[0];
            $dateTos = date('Y-m-d', strtotime($dateTo . ' +1 days'));
            $select->Where('tb1.CreateDate >= ?', $dateFrom);
            $select->Where('tb1.CreateDate <= ?', $dateTos);
        }
        //print_r($getData);die;
        if (isset($getData['POST']) && empty($getData['POST'])) {
            $date = strtotime(date("Y-m-d", strtotime("-1 month")));
            $befor30days = date('Y-m-d', $date);
            $select->Where('tb1.CreateDate >= ?', $befor30days);
            $select->Where('tb1.CreateDate <= ?', date("Y-m-d", strtotime("+1 day")));
        }
        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            //$select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
            $select->Where(" tb1.IsDraft = '1'"); // is active condition removed by amit for website source 
        } else {
            //$select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter

        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        //echo $ReportingToSysId;die;
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);


        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7, 8, 9)); // 1- for flight, 2-for hotel,5-for package,6-for visa,7-for forex,8-for activity,9-for sightseeing
        ($getData['order'] != '') ? $select->order($getData['order']) : $select->order("tb1.UpdateDate DESC");
        // echo $select;die;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        // $result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function GetAgencyQueryFilterForUnAssigned($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $limit = 500)
    {
        //$this->ReportingToSysId = '';
        $select = $this->_dbObj->select();
        if (isset($limit) && !empty($limit)) {
            // $select->limit($limit);
        }
        $arrLeadSource = array('Title as LeadSource');
        $travelplanarray = array(
            new Zend_Db_Expr("'' AS OwnerAgentFirstName"),
            'Title',
            'MasterTPSysId',
            'IsDraft',
            'DraftActiveTab',
            'TPSysId',
            'StatusType',
            'RoomInfoJson',
            'StartDate',
            'ValidTill',
            'PlanBookingId',
            'PlanType',
            'SupplierSysId',
            'CurrencyType',
            'AgencySysId',
            'AgentSysId',
            'CustomerSysId',
            'CreateDate',
            'UpdateDate',
            'MinPax',
            'SourcePlaceSysId',
            'SourcePlaces',
            'DestinationPlacesSysId',
            'DestinationPlaces',
            'AdditionalReq',
            'Cities',
            'Countries',
            'Price',
            'NetPrice',
            'CreatorSysId',
            'CuisineMask',
            'hasFollowUp',
            'hasIteration',
            'VersionId',
            'IsB2BProposal',
            'LeadQuality',
            'PKqueryType'
        );
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $b2bagencyColumn = array('AgencyName as CompanyName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelplanarray);
        //$select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb6.UserSysId = tb3.CreatedByUserSysId", $b2bagencyColumn);
        // $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId'));
        //filter conditions 

        if (!empty($getData['customername'])) {
            //$select->Where('tb3.FirstName like ' . "'%" . $getData['customername'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customername'] . "%'" . ' ');
            $select->Where("tb3.FirstName like '%" . $getData['customername'] . "%' OR tb3.LastName like '%" . $getData['customername'] . "%' OR (RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) = '" . $getData['customername'] . "'");
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customeremail'])) {
            $select->Where('tb3.EmailId like ' . "'%" . $getData['customeremail'] . "%'" . ' ');
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['lead_stage'])) {
            $lead_stage = $getData['lead_stage'];
            //print_r($lead_stage);die;
            $select->Where('tb1.StatusType IN (1)');
            // $select->Where('tb1.StatusType IN(' . $lead_stage . ')');
        }
        (@$getData['lead_type'] == NULL) ? '' : $select->Where("tb3.IsB2BAgent = ?", $getData['lead_type']);
        if (!empty($getData['UserSysId'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['UserSysId']);
        }
        //print_r($getData);die;
        if (!empty($getData['dateFrom']) && !empty($getData['dateTo'] && $getData['dateTo'] != '__-__-____' && $getData['dateFrom'] != '__-__-____')) {
            $dateFromEx = explode('-', $getData['dateFrom']);
            $dateToEx = explode('-', $getData['dateTo']);
            $dateFrom = $dateFromEx[2] . '-' . $dateFromEx[1] . '-' . $dateFromEx[0];
            $dateTo = $dateToEx[2] . '-' . $dateToEx[1] . '-' . $dateToEx[0];
            $dateTos = date('Y-m-d', strtotime($dateTo . ' +1 days'));
            $select->Where('tb1.CreateDate >= ?', $dateFrom);
            $select->Where('tb1.CreateDate <= ?', $dateTos);
        }
        //print_r($getData);die;
        if (isset($getData['POST']) && empty($getData['POST'])) {
            $date = strtotime(date("Y-m-d", strtotime("-1 month")));
            $befor30days = date('Y-m-d', $date);
            $select->Where('tb1.CreateDate >= ?', $befor30days);
            $select->Where('tb1.CreateDate <= ?', date("Y-m-d", strtotime("+1 day")));
        }
        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            //$select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
            $select->Where(" tb1.IsDraft = '1'"); // is active condition removed by amit for website source 
        } else {
            //$select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter

        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        //echo $ReportingToSysId;die;
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        // $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);

        $select->Where('tb1.AgentSysId = ?', 0);
        $select->Where('tb1.IsMarkForDel = ?', 0);
        //$select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7, 8, 9)); // 1- for flight, 2-for hotel,5-for package,6-for visa,7-for forex,8-for activity,9-for sightseeing
        ($getData['order'] != '') ? $select->order($getData['order']) : $select->order("tb1.UpdateDate DESC");
        // echo $select;die;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        // $result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function getPackItenId($packageId, $sequence = NULL)
    {
        $cond = (!empty($sequence)) ? " AND Sequence = '$sequence' " : '';

        $sqlPackIten = "SELECT TPIntSysId,Sequence,CitySysId FROM TB_Agency_Customer_TravelPlan_Itenary WHERE IsMarkForDel = '0' AND IsActive = '1' AND TPSysId = '" . @$packageId . "' $cond";
        $resultPackIten = $this->_dbObj->query($sqlPackIten)->fetchAll();
        return $resultPackIten;
    }

    public function getFlexiPackageOptionalSightseenListByItenarary($iitnID = NULL, $freeType = NULL, $readymadeFreetype = NULL, $MPTYPE = 0, $date = NULL, $VersionId = NULL)
    {
        if (!empty($readymadeFreetype)) {
            $cond = " AND TBACTS.Type IN ('Optional')";
        } else {
            $cond = (!empty($freeType)) ? " AND TBACTS.Type IN ('Optional','Included')" : '';
        }
        if (!empty($date)) {
            $dateCond = " AND '$date' BETWEEN CAST(TMIS.FromDate AS DATE) AND CAST(TMIS.ToDate AS DATE) ";
        }

        //from version id or invntemsys id any 1 must be required, otherwise it will give all results
        if (!empty($VersionId)) {
            $cond .= " AND TBACTS.VersionId IN (" . $VersionId . ") ";
        } else if (!empty($iitnID)) {
            $cond .= " AND TBACTS.InvnItemSysId = '" . $iitnID . "' ";
        }
        $tripDate = !empty($date) ? $date : date('Y-m-d');
        $sqlPackageActivity = "SELECT TBACTS.XrefInvnItemSysId ,TBACTS.IsOptionalSightSeeing,TBACTS.VersionId,TBACTS.Title, TMIS.CostCurrency ,TBACTS.Type,
            TBACTS.Markup,TBACTS.ChildMarkup,TBACTS.KidsCost,TBACTS.Cost,
 TMIS.TrxCurrency ,TMIS.TotalCostNativeAdult ,TMIS.TotalCostNativeChild ,TB_IC_SightSeeing.DurationStr as duration, symbol,alloc.NetPriceNativeAdult as CustomiseAdultCost,alloc.MarkUpNativeAdult,alloc.MarkUpNativeChild,
 alloc.NetPriceNativeChild as CustomiseChildCost ,alloc.MPType,TMIS.SupplierSysId,TB_IC_Supplier.SupplierName as SupplierType,TB_IC_SightSeeing.SSSysId,TB_Agency_Customer_TravelPlan.StatusType,TB_IC_SightSeeing.WriteUp,TB_IC_SightSeeing.Icon
 FROM TB_Agency_Customer_TravelPlan_SIghtseeing as TBACTS left JOIN TB_MP_Inventory_SightSeeing TMIS ON TMIS.InvnItemSysId = TBACTS.XrefInvnItemSysId 
 INNER JOIN TB_Agency_Customer_TravelPlan_Itenary ON TB_Agency_Customer_TravelPlan_Itenary.TPIntSysId = TBACTS.InvnItemSysId
 INNER JOIN TB_Agency_Customer_TravelPlan ON TB_Agency_Customer_TravelPlan_Itenary.TPSysId = TB_Agency_Customer_TravelPlan.TPSysId
  LEFT JOIN TB_Agency_Customer_TravelPlan_MarketWise_Rate ON TB_Agency_Customer_TravelPlan_MarketWise_Rate.TPIntSysId = TB_Agency_Customer_TravelPlan.TPSysId AND Pax = 2
 left JOIN TB_MP_Inventory_SightSeeing_Alloc alloc ON alloc.InvnItemSysId = TBACTS.XrefInvnItemSysId AND TB_Agency_Customer_TravelPlan_MarketWise_Rate.MarketPlaceId = alloc.MPType
 LEFT JOIN TB_IC_SightSeeing ON TBACTS.SSSysId=TB_IC_SightSeeing.SSSysId
 JOIN TB_IC_Supplier ON TMIS.SupplierSysId=TB_IC_Supplier.SupplierSysId 
  LEFT JOIN TB_Master_Currency ON TBACTS.CurrencyType=TB_Master_Currency.CurrencyType 
  WHERE TBACTS.IsActive = '1' AND TBACTS.IsMarkForDelete = '0' AND alloc.IsMarkForDel = '0'  $cond
  AND TB_Agency_Customer_TravelPlan_MarketWise_Rate.IsMarkForDel = 0 AND TB_Agency_Customer_TravelPlan_MarketWise_Rate.MarketPlaceId = '" . $MPTYPE . "'
   AND '$tripDate' BETWEEN CAST(TB_Agency_Customer_TravelPlan_MarketWise_Rate.FromDate AS DATE) AND CAST(TB_Agency_Customer_TravelPlan_MarketWise_Rate.ToDate AS DATE)
       $dateCond
 "; // AND Sequence = 1) ";
        //AND TBACTS.IsActive = '1' AND TBACTS.IsMarkForDelete = '0'
        $resultPackageActivity = $this->_dbObj->query($sqlPackageActivity)->fetchAll();
        return $resultPackageActivity;
    }

    public function GetAgencyQueryAssignedToAgentArray($AgencySysId, $AgentSysId)
    {

        $travel = array('TPSysId', 'StatusType', 'PackTypeMask', 'InclMask', 'StartDate', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate as leadCreateDate', 'Price', 'NetPrice', 'MinPax', 'DestinationPlacesSysId', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'RoomInfoJson', 'UpdateDate as leadUpdateDate');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), $travel);
        $select->where('tbl.AgencySysId = ?', $AgencySysId);
        $select->where('tbl.AgentSysId = ?', $AgentSysId);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.MasterTPSysId = ?', 0);
        // echo $select;die;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAgencyOperationalQuery($AgencySysId, $AgentSysId = NULL, $getData = NULL, $CustomerSysId = NULL, $PlanType = NULL)
    {
        //$this->ReportingToSysId = '';
        $select = $this->_dbObj->select();

        $arrLeadSource = array('Title as LeadSource');
        $travelplanarray = array('Title', 'MasterTPSysId', 'IsDraft', 'DraftActiveTab', 'TPSysId', 'StatusType', 'RoomInfoJson', 'StartDate', 'ValidTill', 'PlanBookingId', 'PlanType', 'SupplierSysId', 'CurrencyType', 'AgencySysId', 'AgentSysId', 'CustomerSysId', 'CreateDate', 'MinPax', 'SourcePlaceSysId', 'SourcePlaces', 'DestinationPlacesSysId', 'DestinationPlaces', 'AdditionalReq', 'ValidTill', 'Cities', 'Countries', 'Price', 'NetPrice', 'CreatorSysId', 'PlanBookingId', 'CuisineMask', 'hasFollowUp', 'hasIteration', 'VersionId', 'IsB2BProposal');
        $leadAgent_owner = array('FirstName as OwnerAgentFirstName', 'LastName as OwnerAgentLastName');
        $leadAgentCreator = array('FirstName as CreatorFirstName', 'LastName as CreatorLastName');
        $b2bagencyColumn = array('AgencyName as CompanyName');
        $customerArray = array("(RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) as FullName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb2.UserSysId = tb1.AgentSysId", $leadAgent_owner);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->joinLeft(array('tb4' => "TB_Agency_User"), "tb4.UserSysId = tb1.CreatorSysId", $leadAgentCreator);
        $select->joinLeft(array('tb5' => "TB_Master_LeadSource"), "tb5.LeadSourceSysId = tb1.LeadSourceSysId", $arrLeadSource);
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb6.UserSysId = tb3.CreatedByUserSysId", $b2bagencyColumn);
        // $select->joinLeft(array('tb5' => "TB_Agency_Customer_ToDo"), "tb5.TPSysId = tb1.TPSysId" , array('ToDoSysId'));
        //filter conditions 

        if (!empty($getData['customername'])) {
            //$select->Where('tb3.FirstName like ' . "'%" . $getData['customername'] . "%'" . ' OR tb3.LastName like ' . "'%" . $getData['customername'] . "%'" . ' ');
            $select->Where("tb3.FirstName like '%" . $getData['customername'] . "%' OR tb3.LastName like '%" . $getData['customername'] . "%' OR (RTRIM(LTRIM(tb3.FirstName)) + ' ' + RTRIM(LTRIM(tb3.LastName))) = '" . $getData['customername'] . "'");
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['customeremail'])) {
            $select->Where('tb3.EmailId like ' . "'%" . $getData['customeremail'] . "%'" . ' ');
        }
        if (!empty($getData['customermobile'])) {
            $select->Where('tb3.Contacts = ?', $getData['customermobile']);
        }
        if (!empty($getData['lead_stage'])) {
            $lead_stage = $getData['lead_stage'];
            //print_r($lead_stage);die;
            $select->Where('tb1.StatusType IN (' . $lead_stage . ')');
            // $select->Where('tb1.StatusType IN(' . $lead_stage . ')');
        }
        (@$getData['lead_type'] == NULL) ? '' : $select->Where("tb3.IsB2BAgent = ?", $getData['lead_type']);
        if (!empty($getData['UserSysId'])) {
            $select->Where('tb1.AgentSysId = ?', $getData['UserSysId']);
        }
        //print_r($getData);die;
        if (!empty($getData['dateFrom']) && !empty($getData['dateTo'] && $getData['dateTo'] != '__-__-____' && $getData['dateFrom'] != '__-__-____')) {
            $dateFromEx = explode('-', $getData['dateFrom']);
            $dateToEx = explode('-', $getData['dateTo']);
            $dateFrom = $dateFromEx[2] . '-' . $dateFromEx[1] . '-' . $dateFromEx[0];
            $dateTo = $dateToEx[2] . '-' . $dateToEx[1] . '-' . $dateToEx[0];
            $dateTos = date('Y-m-d', strtotime($dateTo . ' +1 days'));
            $select->Where('tb1.CreateDate >= ?', $dateFrom);
            $select->Where('tb1.CreateDate <= ?', $dateTos);
        }
        //print_r($getData);die;
        if (isset($getData['POST']) && empty($getData['POST'])) {
            $date = strtotime(date("Y-m-d", strtotime("-1 month")));
            $befor30days = date('Y-m-d', $date);
            $select->Where('tb1.CreateDate >= ?', $befor30days);
            $select->Where('tb1.CreateDate <= ?', date("Y-m-d", strtotime("+1 day")));
        }
        if (!empty($getData['queryId'])) {
            $tpSysIdArr = explode('/', $getData['queryId']);
            if (count($tpSysIdArr) == 3) {
                $select->Where('tb1.TPSysId = ?', $tpSysIdArr[2]);
            }
        }

        if (!empty($getData['Destination'])) {
            $cityIds = $getData['Destination'];
            $select->Where(" tb1.DestinationPlacesSysId like '$cityIds%' or tb1.DestinationPlacesSysId like '$cityIds,%' or tb1.DestinationPlacesSysId like '%,$cityIds,%' or  tb1.DestinationPlacesSysId like '%,$cityIds' or tb1.SourcePlaceSysId like '$cityIds%' or tb1.SourcePlaceSysId like '$cityIds,%' or tb1.SourcePlaceSysId like '%,$cityIds,%' or  tb1.SourcePlaceSysId like '%,$cityIds' ");
        }
        if (!empty($getData['IsDraft'])) {
            //$select->Where(" tb1.IsDraft = '1' OR  tb1.IsActive = '1' ");
            $select->Where(" tb1.IsDraft = '1'"); // is active condition removed by amit for website source 
        } else {
            //$select->Where('tb1.IsActive = ?', 1);
        }
        //end of filter

        $ReportingToSysId = $AgentSysId . (isset($this->ReportingToSysId) && !empty($this->ReportingToSysId) ? ',' . $this->ReportingToSysId : '');
        //echo $ReportingToSysId;die;
        $select->Where('tb1.AgencySysId = ?', $AgencySysId);
        $AgentSysId ? $select->Where('tb1.AgentSysId IN (?)', explode(',', $ReportingToSysId)) : '';
        $CustomerSysId ? $select->Where('tb1.CustomerSysId = ?', $CustomerSysId) : $select->Where('tb1.CustomerSysId != ?', 0);
        $select->Where('tb1.MasterTPSysId = ?', 0);


        $select->Where('tb1.IsMarkForDel = ?', 0);
        $select->Where('tb2.IsMarkForDel = ?', 0);
        $select->Where('tb1.IsOperationalLead = ?', 1);
        if ($PlanType) {
            $select->Where('tb1.PlanType = ? ', $PlanType);
        } else {
            $select->Where('tb1.PlanType IN (?) ', array(1, 2, 4, 5, 6, 7, 8, 9)); // 1- for flight, 2-for hotel,5-for package,6-for visa,7-for forex,8-for activity,9-for sightseeing
        }
        $select->order("tb1.UpdateDate DESC");
        //echo $select;die;
        //$select->Where('tb1.StatusType IN (?) ',array(1,2));
        // $result = $this->_dbObj->fetchAll($select);
        return $select;
    }

    public function GetTravelPlanDetailById($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $customerArray = array("FirstName", "LastName", "Contacts", "CRMCustSysId", "AgencyCRMLeadSysId", "EmailId", "IsB2BAgent");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb1.CustomerSysId", $customerArray);
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.CustomerSysId > ?', 0);
        $select->where('tb1.IsMarkForDel = ?', 0);
        //$select->where('tbl.StatusType > ?',3);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllQuickTransportOption($tpsysID)
    {
        $select = "SELECT tb1.*,tb2.Title as FromCityTitle,tb3.Title as ToCityTitle,tb4.SupplierName,tb5.Symbol
        FROM TB_Agency_Customer_Trans_Fixed as tb1
        
        LEFT JOIN TB_Master_Geo_City as tb2 ON tb1.SourceCityId = tb2.CityId 
        LEFT JOIN TB_Master_Geo_City as tb3 ON tb1.DestCityId = tb3.CityId 
        LEFT JOIN TB_IC_Supplier as tb4 ON tb1.SupplierSysId = tb4.SupplierSysId 
        LEFT JOIN TB_Master_Currency as tb5 ON tb1.CurrencyType = tb5.CurrencyType 
        WHERE (tb1.TPSysId = '" . $tpsysID . "') AND (tb1.IsMarkForDel = 0) AND (tb1.IsIncluded = 1) AND (tb1.Type = 'Included') AND tb1.XrefItemSysId IS NULL
        ORDER BY tb1.FromDate ASC";

        //                echo $select; die;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetMasterPlanId($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $customerArray = array("TPSysId");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"));
        $select->where('tb1.MasterTPSysId = ?', $TPSysId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.CustomerSysId > ?', 0);
        $select->where('tb1.IsMarkForDel = ?', 0);
        //$select->where('tbl.StatusType > ?',3);
        $result = $this->_dbObj->fetchAll($select);
        $MasterTpSysIds = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                array_push($MasterTpSysIds, $value['TPSysId']);
            }
        }
        return $MasterTpSysIds;
    }

    public function GetTravelPlanStatusById($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $customerArray = array("TPSysId", "StatusType", "CreateDate", "UpdateDate", "MasterTPSysId");
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $customerArray);
        $select->where('tb1.TPSysId IN (?)', $TPSysId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.CustomerSysId > ?', 0);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $select->order("tb1.CreateDate ASC");
        //$select->where('tbl.StatusType > ?',3);
        $result = $this->_dbObj->fetchAll($select);
        $MasterTpSysIds = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                $MasterTpSysIds[$key]['CreateDate'] = $value['CreateDate'];
                $MasterTpSysIds[$key]['UpdateDate'] = $value['UpdateDate'];
                $MasterTpSysIds[$key]['TPSysId'] = $value['TPSysId'];
                $MasterTpSysIds[$key]['MasterTPSysId'] = $value['MasterTPSysId'];
                $MasterTpSysIds[$key]['StatusType'] = $value['StatusType'];
            }
        }
        return $MasterTpSysIds;
    }

    public function GetLeadRemarkById($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $remarkArray = array("Remarks", "CreatedDate", "RemarkType");
        $select->from(array('tb1' => "TB_Agency_Customer_Remarks"), $remarkArray);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb1.AgentSysId = tb2.UserSysId", array('FirstName', 'LastName'));
        $select->where('tb1.TPSysId IN (?)', $TPSysId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where("tb1.IsActive = ?", 1);
        //$select->where("tb1.RemarkType = ?", 1);
        $select->order('tb1.CreatedDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        $remarksArray = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                $remarksArray[$key]['CreatedDate'] = $value['CreatedDate'];
                $remarksArray[$key]['Remarks'] = $value['Remarks'];
                $remarksArray[$key]['RemarkType'] = $value['RemarkType'];
                $remarksArray[$key]['UpdatedBy'] = trim($value['FirstName']) . ' ' . trim($value['LastName']);
            }
        }
        return $remarksArray;
    }

    public function GetLeadLastFollowupsByTPSysId($TPSysId, $AgencySysId, $type)
    {
        $select = $this->_dbObj->select('*');
        $select->from(array('tb1' => "TB_Agency_Customer_ToDo"));
        $select->where('tb1.ActionId = ?', $TPSysId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where("tb1.Type = ?", $type);
        $select->where("tb1.IsCompleted = ?", 1);
        $select->order('tb1.ToDoSysId DESC');
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetLeadFollowupsById($lId, $AgencySysId, $type)
    {
        $select = $this->_dbObj->select('*');
        $select->from(array('tb1' => "TB_Agency_Customer_ToDo"));
        $select->where('tb1.ActionId IN (?)', $lId);
        $select->where('tb1.AgencySysId = ?', $AgencySysId);
        $select->where("tb1.Type = ?", $type);
        $select->order('tb1.ToDoSysId DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getSmsCount($TPSysIds = NULL, $AgencySysId = NULL, $TypeSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $select->from("TB_Agency_Sent_Sms_Email", array('count(*) as totalSms'));
        $TPSysIds ? $select->where("TPSysId IN(?)", $TPSysIds) : '';
        $AgencySysId ? $select->where("AgencySysId =?", $AgencySysId) : '';
        $TypeSysId ? $select->where("TypeSysId =?", $TypeSysId) : '';
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getToDoCount($TPSysIds, $AgencySysId, $TypeSysId)
    {
        $select = $this->_dbObj->select();
        $select->from("TB_Agency_Customer_ToDo", array('count(*) as TotalTodo'));
        $select->where("TPSysId IN(?)", $TPSysIds);
        $select->where("AgencySysId =?", $AgencySysId);
        $select->where("IsCompleted = ?", 1);
        $select->where("Subject IN(?)", $TypeSysId);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getToDoCountBYActionId($lip, $AgencySysId, $type, $TypeSysId = null)
    {
        $select = $this->_dbObj->select();
        $select->from("TB_Agency_Customer_ToDo", array('count(*) as TotalTodo'));
        $select->where("ActionId IN(?)", $lip);
        $select->where("Type =?", $type);
        $select->where("IsCompleted = ?", 1);
        $select->where("AgencySysId =?", $AgencySysId);
        if (!empty($TypeSysId)) {
            $select->where("Subject IN(?)", $TypeSysId);
        }
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getSentEmailByPlanId($TPSysIds = NULL, $AgencySysId = NULL, $TypeSysId = NULL)
    {
        $select = $this->_dbObj->select();
        $emailArary = array('TPSysId', 'Title', 'CreateDate', 'TemplateSysId', 'CustomerSysId', 'Source');
        $select->from(array('tb1' => "TB_Agency_Sent_Sms_Email"), $emailArary);
        $TPSysIds ? $select->where("tb1.TPSysId IN(?)", $TPSysIds) : '';
        $AgencySysId ? $select->where("tb1.AgencySysId =?", $AgencySysId) : '';
        $TypeSysId ? $select->where("tb1.TypeSysId =?", $TypeSysId) : '';
        $select->order('tb1.CreateDate ASC');
        $result = $this->_dbObj->fetchAll($select);
        $emailResArray = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                $emailResArray[$key]['CreateDate'] = $value['CreateDate'];
                $emailResArray[$key]['TPSysId'] = $value['TPSysId'];
                $emailResArray[$key]['Title'] = $value['Title'];
                $emailResArray[$key]['TemplateSysId'] = $value['TemplateSysId'];
                $emailResArray[$key]['Source'] = $value['Source'];
                $emailResArray[$key]['CustomerSysId'] = $value['CustomerSysId'];
            }
        }
        return $emailResArray;
    }

    public function getToDoFollowUpByPlanId($TPSysIds = NULL, $AgencySysId = NULL, $Type = NULL, $limit = null, $IsCompleted = null)
    {
        $select = $this->_dbObj->select();
        $todoArary = array('Type', 'TPSysId', 'Subject', 'Description', 'CreateDate', 'EndDateTime', 'ToDoSysId', 'CustSysId', 'IsCompleted', 'CallStatus', 'CallType');
        $select->from(array('tb1' => "TB_Agency_Customer_ToDo"), $todoArary);
        $select->joinLeft(array('tb2' => "TB_Agency_User"), "tb1.CreatedBySysId = tb2.UserSysId", array('FirstName', 'LastName'));
        $TPSysIds ? $select->where("tb1.TPSysId IN(?)", $TPSysIds) : '';
        $AgencySysId ? $select->where("tb1.AgencySysId =?", $AgencySysId) : '';
        $Type ? $select->where("tb1.Type =?", $Type) : '';
        if ($IsCompleted != null) {
            $select->where("tb1.IsCompleted = ?", $IsCompleted);
        }
        if ($limit) {
            $select->limit($limit);
        }
        $select->order('tb1.CreateDate Desc');
        //        echo $select;die;
        $result = $this->_dbObj->fetchAll($select);
        $emailResArray = array();
        if (count($result) > 0) {
            foreach ($result as $key => $value) {
                $emailResArray[$key]['ToDoSysId'] = $value['ToDoSysId'];
                $emailResArray[$key]['CustomerSysId'] = $value['CustSysId'];
                $emailResArray[$key]['CustSysId'] = $value['CustSysId'];
                $emailResArray[$key]['CreateDate'] = $value['CreateDate'];
                $emailResArray[$key]['EndDateTime'] = $value['EndDateTime'];
                $emailResArray[$key]['TPSysId'] = $value['TPSysId'];
                $emailResArray[$key]['Subject'] = $value['Subject'];
                $emailResArray[$key]['Type'] = $value['Type'];
                $emailResArray[$key]['Description'] = $value['Description'];
                $emailResArray[$key]['UpdatedBy'] = trim($value['FirstName']) . ' ' . trim($value['LastName']);
                $emailResArray[$key]['IsCompleted'] = $value['IsCompleted'];
                $emailResArray[$key]['CallType'] = $value['CallType'];
                $emailResArray[$key]['CallStatus'] = $value['CallStatus'];
            }
        }
        return $emailResArray;
    }

    public function GetTravelPlanByVersion($tpsysID, $versionId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array('ServiceTaxOnCustomDiscount', 'AgentsCustomServiceTaxAmount', 'AgentServiceTaxAmount', 'XServiceTaxAmount', 'TPSysId', 'VersionId', 'MultiOptions', 'NetPrice', 'GSTSharedMode', 'SACCode', 'MarkUp', 'IsB2BProposal'));
        $select->where('tbl.MasterTPSysId = ?', $tpsysID);
        $select->where('tbl.VersionId IN (?)', $versionId);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->order('tbl.VersionId ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetVersionAndOptionsByTpSysId($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array('TPSysId', 'VersionId', 'MultiOptions', 'EconomyMask', 'StatusType', 'PlanType'));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanDetailsByQueryIdAndVersion($tpsysID, $versionIds)
    {
        //        echo $versionIds;
        $customerarray = array('CustomerSysId', 'EmailId', 'Contacts', 'FirstName', 'Title as Salutation', 'LastName', 'IsB2BAgent');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"));
        $select->joinLeft(array('tblM' => 'TB_Agency_Customer_TravelPlan_Mapping'), "tblM.TPSysId = tbl.TPSysId", array('RefTPSysId'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", $customerarray);
        $select->joinLeft(array('tb2' => 'TB_IC_Supplier'), "tbl.SupplierSysId = tb2.SupplierSysId", array('SupplierName'));
        $select->where('tbl.MasterTPSysId = ?', $tpsysID);
        $select->where('tbl.VersionId IN (?)', $versionIds);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->order('tbl.VersionId ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    // no joint required this method used to copy data in modify proposal
    public function GetOnlyTravelPlanDetailsByQueryIdAndVersion($tpsysID, $versionIds)
    {
        //        echo $versionIds;
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"));
        $select->where('tbl.MasterTPSysId = ?', $tpsysID);
        $select->where('tbl.VersionId IN (?)', $versionIds);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPackageFLightData($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary"), array('TPIntSysId'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Air"), "tbl.TPIntSysId = tb2.TPIntSysId");
        $select->joinleft(array('ITAA' => "TB_IC_Trans_API_Air"), "ITAA.TBQAirInvenSysId = tb2.InvnItemSysId", array('TBQAirInvenSysId', 'JourneyType', 'JourneyType as TripType', 'IsInternational', 'IsRefundable', 'ICSourceSysId', 'IsNewMigration'));
        $select->joinLeft(array('tb3' => 'TB_Master_Currency'), 'tb3.CurrencyType = tb2.CurrencyType', array('Symbol'));
        $select->joinLeft(array('tb4' => "TB_IC_Supplier"), "tb4.SupplierSysId = tb2.SupplierSysId", array('SupplierName'));
        $select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);
        $select->order('tb2.LocalFromTime ASC');
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPackageCruiseData($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Cruise"));
        $select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetPackageCruiseDetailsData($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Cruise_Cabin_Detail"));
        $select->where('tbl.CruiseSysId = ?', $TPSysId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        //echo $select;
        //$leadId?$select->where('tbl.TPSysId = ?', $leadId):'';
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getCustomerMoreThanPaxDataByMarketWiseRate($TPSysId, $fromDate, $toDate, $MarketPlaceId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_MarketWise_Rate"));
        $select->joinLeft(array('tb2' => "TB_Master_Currency"), "tbl.CurrencyType = tb2.CurrencyType", 'Symbol');
        $select->where('tbl.TPIntSysId = ?', $TPSysId);
        $select->where('convert(date,tbl.FromDate) = ?', $fromDate);
        $select->where('convert(date,tbl.ToDate) = ?', $toDate);
        $select->where('tbl.MarketPlaceId = ?', $MarketPlaceId);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', '0');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getCustomerMoreThanPaxDataByMarketRate($TPSysId, $fromDate, $toDate, $MarketPlaceId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Rate"));
        $select->joinLeft(array('tb2' => "TB_Master_Currency"), "tbl.CurrencyType = tb2.CurrencyType", 'Symbol');
        $select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where('convert(date,tbl.StartDate) = ?', $fromDate);
        $select->where('convert(date,tbl.ValidTill) = ?', $toDate);
        $select->where('tbl.MarketPlaceId = ?', $MarketPlaceId);
        $select->where('tbl.IsActive = ?', 1);
        $select->where('tbl.IsMarkForDel = ?', '0');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    /*     * **************************** Copy Data Form Master Package to Customer Table ************************************* */

    public function GetTravelPlanByTPID($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan"));
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllProposalStatusModuleCompArrayNew()
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Master_SubSystem_Module_Component"));

        $select->where('tb1.IsActive = ?', 1);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getB2bAgencySysId($customerSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer"), array("AgencySysId"));
        $select->where('tb1.CustomerSysId = ?', $customerSysId);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetAllSupplierCountNew()
    {

        $select = $this->_dbObj->select();

        $tpsysID = array('SupplierSysId', 'TPSysId');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $tpsysID);
        //            $select->where('tbl.TPSysId = ?', $leadID);
        // $select->where('tbl.MasterTPSysId = ?', $leadID);
        $select->where('tbl.StatusType > ?', 3);
        $select->where('tbl.SupplierSysId > ?', 0);
        $result = $this->_dbObj->fetchAll($select);

        return $result;
    }

    public function getAllCustomerWithLeadId()
    {

        $travel = array('TPSysId', 'CustomerSysId', 'AgencySysId', 'AgentSysId', 'VersionId', 'MasterTPSysId', 'TPId', 'CreateDate', 'DownloadCount', 'StatusType');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getPickupLocation($PickupLocationSysId)
    {
        $travel = array('pickupLocation', 'PickupTime');
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_TravelPlan_Bus_Pickup_Location"), $travel);
        $select->where('tbl.PickupLocationSysId = ?', $PickupLocationSysId);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetCustomerTravelPlanLeadSourceNameByTPID($tpsysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Query"), array('LeadSourceSysId', 'StartDate'));
        $select->joinLeft(array('tb2' => "TB_Master_LeadSource"), "tb2.LeadSourceSysId = tbl.LeadSourceSysId", 'Title');
        $select->where('tbl.TPSysId = ?', $tpsysID);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $select->where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getCustomerTranportDetail($tpsysID, $IsDisplay = 0)
    {

        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trans_Fixed"));
        $select->joinLeft(array('tb2' => "TB_Agency_Transport_Route"), "tb2.RouteSysId = tbl.RouteSysId");
        $select->joinLeft(array('tb3' => "TB_Master_Geo_City"), "tbl.SourceCityId = tb3.CityId", array('Title as FromCityTitle'));
        $select->joinLeft(array('tb4' => "TB_Master_Vehicle"), "tbl.VehicleTypeSysId = tb4.VehSysId", array('VehName'));
        $select->joinLeft(array('tb5' => 'TB_Master_Currency'), 'tb5.CurrencyType = tbl.CurrencyType', array('Symbol'));
        $select->joinLeft(array('tb6' => "TB_Master_Geo_City"), "tbl.DestCityId = tb6.CityId", array('Title as EnCityTitle'));
        $select->Where('tbl.TPSysId = ' . $tpsysID);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->where('tbl.IsIncluded = 1');
        $select->Where('tbl.IsActive = ?', '1');
        if ($IsDisplay == 1) {
            $select->where('tbl.IsDisplay = ?', 1);
        }
        $select->order('tbl.TPIntSysId ASC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelTransportDetail($TPSysId, $CustomerSysId = NULL, $AgencySysId = NULL)
    {
        $select = $this->_dbObj->select();
        $travelPlanColumn = array('GSTSharedMode', 'CurrencyType', 'PkgSellValidTill', 'IsPriceShared', 'VersionId', 'TPSysId', 'MasterTPSysId', 'MarkUp', 'AgencyMarkUp', 'GTXMarkup', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'AgentsCustomServiceTaxAmount', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', 'XServiceTaxAmount', 'IsCardChrgToCustomer', 'StatusType', 'PackTypeMask', 'AgentSysId', 'CuisineMask', 'InclMask', 'StartDate', 'ValidTill', 'PlanBookingId', 'AgencySysId', 'MinPrice', 'PlanType', 'CustomerSysId', 'CreateDate', 'Price', 'NetPrice', 'MinPax', 'DiscountVal', 'DestinationPlacesSysId', 'SourcePlaces', 'SourcePlaceSysId', 'RoomInfoJson', 'DestinationPlaces', 'MaxPrice', 'AdditionalReq', 'UpdateDate as leadUpdateDate', 'Countries', 'Cities', 'Readymade', 'IsDraft', 'TotalMinDays', 'TotalMaxDays', 'DraftActiveTab', 'IsActive', 'DaysCountFrom', 'DaysCountTo', 'MinPrice', 'MaxPrice', 'LeadQuality', 'HotelPreference', 'LeadSourceSysId', 'PackCategoryId', 'TourType', 'TotalMinDays', 'Countries', 'CurrencyRequired', 'CurrencyType', 'Details', 'IsB2BProposal', 'NoofNight', 'EmailText');
        $travelItenaryColumn = array('TPIntSysId', 'TransType', 'Capacity', 'VehicleQty');

        //        $travelVisaColumn = array('VisaName','PrecessingTime');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travelPlanColumn);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_Trans_Fixed"), "tb1.TPSysId = tb2.TPSysId", $travelItenaryColumn);

        $select->where('tb1.TPSysId = ?', $TPSysId);
        $CustomerSysId ? $select->where('tbl.CustomerSysId = ?', $CustomerSysId) : '';
        $AgencySysId ? $select->where('tbl.AgencySysId = ?', $AgencySysId) : '';
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanSightSeeingForTransport($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_SightSeeing", array('InvnItemSysId', 'SeqId', 'VersionId', 'XrefInvnItemSysId', 'SSSysId', 'Title', 'Type')));
        $select->joinLeft(array('tb2' => "TB_IC_SightSeeing"), "tbl.SSSysId = tb2.SSSysId", array('Icon', 'ThumnailImg', 'DetailImg', 'Address', 'latitude', 'longitude', 'WriteUp'));
        $select->joinLeft(array('tb3' => "TB_Master_Geo_City"), "tbl.CityId = tb3.CityId", array('Title as cityTitle'));
        $select->Where('tbl.TPIntSysId = ?', $TPSysId);
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanEMIData($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trx_Emi"));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.IsActive = ?', '1');
        //echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getSearchCityId($cityIds)
    {
        $cityId = (int) $cityIds;
        if ($cityId > 0) {
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => "TB_MASTER_VIEW_PKGSEARCH_STRING"));
            $select->Where('tbl.TypeId = ?', $cityId);
            $result = $this->_dbObj->fetchAll($select);
            if (!empty($result)) {
                $cityIdVal = isset($result[0]['Id']) ? $result[0]['Id'] : 0;
                if ($cityIdVal > 0) {
                    $cityId = $cityIdVal;
                }
            }
        }
        return $cityId;
    }

    public function getSearchStateCountryId($cityIds)
    {
        $cityId = (int) $cityIds;
        if ($cityId > 0) {
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => "TB_MASTER_VIEW_PKGSEARCH_STRING"));
            $select->Where('tbl.TypeId IN (?)', $cityId);
            $result = $this->_dbObj->fetchAll($select);
            if (!empty($result)) {
                $cityIdVal = isset($result[0]['Id']) ? $result[0]['Id'] : 0;
                if ($cityIdVal > 0) {
                    $cityId = $cityIdVal;
                }
            }
        }
        return $cityId;
    }

    public function getFlightDetailForCustomer($TPSysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"));
        $select->Where('tbl.TPIntSysId IN (SELECT TPIntSysId FROM TB_Agency_Customer_TravelPlan_Itenary where TPSysId = ' . $TPSysID . ')');
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getAdvancedBalance($TPSysID)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trx"), array('SUM(NetAmount) as TotalAmountPaid'));
        $select->Where('tbl.TPSysId = ?', $TPSysID);
        $select->Where('tbl.IsActive = ?', '1');
        $select->Where('tbl.TrxStatus = ?', '1');
        //        echo $select;die;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getTcsAmount($TPSysID, $planType, $IsActive = 1)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_AddonServices"), array('TotalCost', 'Markup', 'Cost', 'GSTTYPE', 'Tax', 'ServiceTitle'));
        $select->Where('tbl.TPSysId = ?', $TPSysID);
        $select->Where('tbl.IsActive = ?', $IsActive);
        $select->Where('tbl.PlanType = ?', $planType);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getTcsAmountWithTaxType($TPSysID, $planType)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_AddonServices"), array('Markup', 'Cost', 'GSTTYPE', 'Tax', 'ServiceTitle'));
        $select->joinLeft(array('tb2' => "TB_Master_Agency_Tax_Settings"), "tbl.GSTTYPE = tb2.TaxSysId", array("TaxType"));
        $select->Where('tbl.TPSysId = ?', $TPSysID);
        $select->Where('tbl.IsActive = ?', '1');
        $select->Where('tbl.PlanType = ?', $planType);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getMemberWithDocName($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Visa_Document"), array("TPSysId", "TPPaxSysId", "DocId", "DocName", "Status as docStatusId", "UpdatedBy", "DocImagePath", 'IsMandatory', 'FieldType', 'Label', 'Options', 'Remark as UserRemark', 'UpdateDate as UpdateDateVD'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tbl.TPPaxSysId = tb2.TPPaxSysId", array("MemberSysId", "CustomerSysId"));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_Members"), "tb2.MemberSysId = tb3.MemberSysId", array('Title as Salutaion', 'FirstName', 'LastName', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry', 'paxType'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Visa_Final_Document"), "tb2.TPPaxSysId = tb4.TPPaxSysId", array('ApplicationNo', 'UploadedVisaPath', 'Remark as message', 'Status as paxTypeStatus', 'InterviwDate', 'Remark', 'UpdateDate'));
        $select->joinLeft(array('tb5' => "TB_Agency_User"), "tbl.UpdatedBy = tb5.UserSysId", array('FirstName as UserFirstName', 'LastName as UserLastName'));
        $select->joinLeft(array('tb6' => "TB_MP_Inventory_Visa_Doc"), "tbl.DocId = tb6.DocVisaSysId", array());
        $select->joinLeft(array('tb7' => "TB_Master_VisaDocument"), "tb6.DocumentSysId = tb7.DocSysId", array("Description"));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tb2.MemberSysId != 0');




        $select2 = $this->_dbObj->select();
        $select2->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Visa_Document"), array("TPSysId", "TPPaxSysId", "DocId", "DocName", "Status as docStatusId", "UpdatedBy", "DocImagePath", 'IsMandatory', 'FieldType', 'Label', 'Options', 'Remark as UserRemark', 'UpdateDate as UpdateDateVD'));
        $select2->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tbl.TPPaxSysId = tb2.TPPaxSysId", array("MemberSysId", "CustomerSysId"));
        $select2->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb3.CustomerSysId", array('Title as Salutaion', 'FirstName', 'LastName', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry', 'paxType'));
        $select2->joinLeft(array('tb4' => "TB_Agency_Customer_TravelPlan_Visa_Final_Document"), "tb2.TPPaxSysId = tb4.TPPaxSysId", array('ApplicationNo', 'UploadedVisaPath', 'Remark as message', 'Status as paxTypeStatus', 'InterviwDate', 'Remark', 'UpdateDate'));
        $select2->joinLeft(array('tb5' => "TB_Agency_User"), "tbl.UpdatedBy = tb5.UserSysId", array('FirstName as UserFirstName', 'LastName as UserLastName'));
        $select2->joinLeft(array('tb6' => "TB_MP_Inventory_Visa_Doc"), "tbl.DocId = tb6.DocVisaSysId", array());
        $select2->joinLeft(array('tb7' => "TB_Master_VisaDocument"), "tb6.DocumentSysId = tb7.DocSysId", array("Description"));
        $select2->Where('tbl.TPSysId = ?', $TPSysId);
        $select2->Where('tb2.MemberSysId = 0');

        $select1 = $this->_dbObj->select()
            ->union(array($select, $select2), Zend_Db_Select::SQL_UNION_ALL)
            ->order('TPPaxSysId ASC');


        //         echo $select; exit;

        $result = $this->_dbObj->fetchAll($select1);
        return $result;
    }

    public function getMemberWithDocNameByCustomerSysId($CustomerSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array("TPSysId", "Title", "DestinationPlaces", "StartDate", "PackageCostCalType"));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Visa_Document"), "tbl.TPSysId = tb2.TPSysId", array("TPSysId", "TPPaxSysId", "DocId", "DocName", "DocImagePath", "Status as docStatusId", "UpdatedBy", 'IsMandatory'));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Pax"), "tb2.TPPaxSysId = tb3.TPPaxSysId", array("MemberSysId"));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_Members"), "tb3.MemberSysId = tb4.MemberSysId", array('FirstName', 'LastName', 'EmailId', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry'));
        $select->joinLeft(array('tb5' => "TB_Agency_Customer_TravelPlan_Visa_Final_Document"), "tb3.TPPaxSysId = tb5.TPPaxSysId", array('ApplicationNo', 'UploadedVisaPath', 'Remark as message', 'Status as paxTypeStatus', 'InterviwDate', 'Remark'));
        $select->joinLeft(array('tb6' => "TB_Agency_User"), "tb2.UpdatedBy = tb6.UserSysId", array('FirstName as UserFirstName', 'LastName as UserLastName'));
        $select->Where('tbl.CustomerSysId = ?', $CustomerSysId);
        $select->Where('tb3.MemberSysId != 0');




        $select2 = $this->_dbObj->select();
        $select2->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array("TPSysId", "Title", "DestinationPlaces", "StartDate", "PackageCostCalType"));
        $select2->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Visa_Document"), "tbl.TPSysId = tb2.TPSysId", array("TPSysId", "TPPaxSysId", "DocId", "DocName", "DocImagePath", "Status as docStatusId", "UpdatedBy", 'IsMandatory'));
        $select2->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Pax"), "tb2.TPPaxSysId = tb3.TPPaxSysId", array("MemberSysId"));
        $select2->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb3.CustomerSysId = tb4.CustomerSysId", array('FirstName', 'LastName', 'EmailId', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry'));
        $select2->joinLeft(array('tb5' => "TB_Agency_Customer_TravelPlan_Visa_Final_Document"), "tb3.TPPaxSysId = tb5.TPPaxSysId", array('ApplicationNo', 'UploadedVisaPath', 'Remark as message', 'Status as paxTypeStatus', 'InterviwDate', 'Remark'));
        $select2->joinLeft(array('tb6' => "TB_Agency_User"), "tb2.UpdatedBy = tb6.UserSysId", array('FirstName as UserFirstName', 'LastName as UserLastName'));
        $select2->Where('tbl.CustomerSysId = ?', $CustomerSysId);
        $select2->Where('tb3.MemberSysId = 0');

        $select1 = $this->_dbObj->select()
            ->union(array($select, $select2), Zend_Db_Select::SQL_UNION_ALL)
            ->order('MemberSysId ASC');


        // echo $select1; exit;

        $result = $this->_dbObj->fetchAll($select1);
        return $result;
    }

    public function GetCustomerTravelPlanItenaryTransportByTPSysId($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Itenary_Transport"));
        $select->Where('tbl.TPSysId = ? ', $TPSysId);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getProposalCustomerMemberDetail($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Pax"), array('*'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_Members"), "tbl.MemberSysId = tb2.MemberSysId", array('FirstName', 'LastName', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry', 'paxType'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.MemberSysId != 0');




        $select2 = $this->_dbObj->select();
        $select2->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Pax"), array('*'));
        $select2->joinLeft(array('tb2' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb2.CustomerSysId", array('FirstName', 'LastName', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry', 'paxType'));
        $select2->Where('tbl.TPSysId = ?', $TPSysId);
        $select2->Where('tbl.MemberSysId = 0');

        $select1 = $this->_dbObj->select()
            ->union(array($select, $select2), Zend_Db_Select::SQL_UNION_ALL)
            ->order('VersionId ASC');


        //echo $select1; exit;

        $result = $this->_dbObj->fetchAll($select1);
        return $result;
    }

    public function getPriceWithGST($price, $TaxType, $TaxRate)
    {
        if ($TaxType == 1) {
            return (int) ($price + (((float) $price * (float) $TaxRate) / 100));
        } else {
            return (int) $price;
        }
    }

    function calculateGSTPrice($price, $markup, $TaxType, $TaxRate)
    {

        if ($TaxType == 1 && $price > 0) {
            $gstAmount = ((float) $price * $TaxRate) / 100;
        } elseif ($TaxType == 2 && $markup > 0) {
            $gstAmount = ((float) $markup * $TaxRate) / 100;
        } else {
            $gstAmount = 0;
        }
        return (float) $gstAmount;
    }

    function calculateGSTPriceIncludeDiscountAndExtraMarkup($price, $markup, $TaxType, $TaxRate, $discount = 0, $extraMarkup = 0)
    {

        $agencyTotalMarkUp = ($markup + $extraMarkup) - $discount;
        $taxableAmount = ($price + $agencyTotalMarkUp) - $markup;

        if ($TaxType == 1 && $price > 0) {
            $gstAmount = ((float) $taxableAmount * $TaxRate) / 100;
        } elseif ($TaxType == 2 && $markup > 0) {
            $gstAmount = ((float) $agencyTotalMarkUp * $TaxRate) / 100;
        } else {
            $gstAmount = 0;
        }

        $PriceWithGst = $taxableAmount + $gstAmount;
        $resultArr = [
            'AmountWithGst' => (float) $PriceWithGst,
            'gstAmount' => (float) $gstAmount
        ];
        return $resultArr;
    }

    public function expectedClosureData($TPSysId, $getData)
    {
        $objPackage = new Travel_Model_TblPackage();
        $ExpectedClosureDate = (isset($getData['ExpectedClosureDate']) && !empty($getData['ExpectedClosureDate'])) ? implode('-', array_reverse(explode('/', $getData['ExpectedClosureDate']))) : '';
        $ExpectedValue = (isset($getData['ExpectedValue']) && !empty($getData['ExpectedValue'])) ? (float) trim($getData['ExpectedValue']) : 0;

        $IsCoupon = (isset($getData['IsCoupon']) && !empty($getData['IsCoupon'])) ? $getData['IsCoupon'] : 0;
        $CouponId = (isset($getData['CouponId']) && !empty($getData['CouponId'])) ? $getData['CouponId'] : 0;
        $CouponCode = (isset($getData['CouponCode']) && !empty($getData['CouponCode'])) ? $getData['CouponCode'] : '';
        if (!empty($ExpectedClosureDate) || !empty($ExpectedValue) || !empty($CouponId)) {
            if ((int) $TPSysId > 0) {
                $saveData = [
                    'TPSysId' => $TPSysId,
                    'ExpectedClosureDate' => $ExpectedClosureDate,
                    'ExpectedValue' => $ExpectedValue,
                    'IsCoupon' => $IsCoupon,
                    'CouponId' => $CouponId,
                    'CouponCode' => $CouponCode,
                ];
                if (isset($getData['HotelVoucherStatus'])) {
                    $saveData['HotelVoucherStatus'] = (int) $getData['HotelVoucherStatus'];
                }
                if (isset($getData['FlightVoucherStatus'])) {
                    $saveData['FlightVoucherStatus'] = (int) $getData['FlightVoucherStatus'];
                }
                if (isset($getData['SightseeingVoucherStatus'])) {
                    $saveData['SightseeingVoucherStatus'] = (int) $getData['SightseeingVoucherStatus'];
                }
                if (isset($getData['TransferVoucherStatus'])) {
                    $saveData['TransferVoucherStatus'] = (int) $getData['TransferVoucherStatus'];
                }
                if (isset($getData['OtherVoucherStatus'])) {
                    $saveData['OtherVoucherStatus'] = (int) $getData['OtherVoucherStatus'];
                }
                if (isset($getData['VisaVoucherStatus'])) {
                    $saveData['VisaVoucherStatus'] = (int) $getData['VisaVoucherStatus'];
                }
                if (isset($getData['InsuranceVoucherStatus'])) {
                    $saveData['InsuranceVoucherStatus'] = (int) $getData['InsuranceVoucherStatus'];
                }
                if (isset($getData['GuideVoucherStatus'])) {
                    $saveData['GuideVoucherStatus'] = (int) $getData['GuideVoucherStatus'];
                }
                if (isset($getData['MealVoucherStatus'])) {
                    $saveData['MealVoucherStatus'] = (int) $getData['MealVoucherStatus'];
                }
                //                echo "<pre>";print_r($saveData);die;
                $response = $this->checkExpectedClosure($TPSysId);
                if (!empty($response)) {
                    $where = array('TPSysId = ? ' => $TPSysId);
                    $objPackage->updateData('TB_Agency_Customer_TravelPlan_Mapping', $saveData, $where);
                    $insertId = $TPSysId;
                } else {
                    $insertId = $objPackage->insertData('TB_Agency_Customer_TravelPlan_Mapping', $saveData);
                }
            }
        }

        return $TPSysId;
    }

    public function checkExpectedClosure($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Mapping"), array('*'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getCustPackageRoomwisePrice($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_RoomWise_Market_Rate"), array('RoomName', 'RoomOrder', 'NoOfNight', 'Adult', 'Child', 'ExtraBed', 'ExtraWithoutBed', 'Cost', 'TotalCost', 'TPRateSheetSysId', 'TPSysId'));
        $select->joinLeft(array('tb2' => 'TB_Master_Currency'), "tb2.CurrencyType = tbl.CurrencyType", array('Symbol'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.IsMarkForDelete = ?', 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getQueryDetail($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array('Cities', 'AgencySysId AS MasterAgencySysId', 'AgentSysId'));
        $select->joinLeft(array('tb2' => 'TB_Agency_Customer_TravelPlan_Mapping'), "tb2.TPSysId = tbl.TPSysId", array('ExpectedValue'));
        $select->joinLeft(array('tb3' => 'TB_Agency_Customer'), "tbl.CustomerSysId = tb3.CustomerSysId", array('CustomerSysId'));
        $select->joinLeft(array('tb4' => 'TB_Agency'), "tb3.AgencySysId = tb4.AgencySysId", array('Title', 'AgencySysId', 'AgencyMarketPlaceSysId'));
        $select->joinLeft(array('tb5' => 'TB_Agency_User'), "tbl.AgentSysId = tb5.UserSysId", array('LTRIM(RTRIM(tb5.FirstName)) AS FirstName', 'LTRIM(RTRIM(tb5.LastName)) AS LastName'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $select->Where('tbl.IsMarkForDel = ?', 0);
        //echo $select; exit;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function checkRewardPoints($AgencySysId, $MasterAgencySysId)
    {
        $objPackage = new Travel_Model_TblPackage();
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Reward_Points"), array('RewardPointsSysId'));
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $select->Where('tbl.MasterAgencySysId = ?', $MasterAgencySysId);
        $select->Where('tbl.IsMarkForDel = ?', 0);
        $select->Where('tbl.IsActive = ?', 1);
        $result = $this->_dbObj->fetchRow($select);
        $RewardPointsSysId = isset($result['RewardPointsSysId']) ? $result['RewardPointsSysId'] : null;
        $currentDate = date('Y-m-d H:i:s');
        if (!$RewardPointsSysId) {
            $insertArray = array(
                "Title" => 'Reward_' . $AgencySysId,
                "BalancePoints" => 0,
                "IsMarkForDel" => 0,
                "IsActive" => 1,
                "CreateDate" => $currentDate,
                "UpdateDate" => $currentDate,
                "AgencySysId" => $AgencySysId,
                "CurrencyType" => 1,
                "MasterAgencySysId" => $MasterAgencySysId,
            );
            $RewardPointsSysId = $objPackage->insertData('TB_Agency_Reward_Points', $insertArray);
        }
        return $RewardPointsSysId;
    }

    public function getRecordListingRewarPage($AgencySysId, $rwdId = null)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Reward_Points"), array("tbl.*", "((select sum(adT1.CreditPoints) FROM Tb_Agency_Reward_Points_History adT1 where adT1.TrxType = 0 AND tbl.RewardPointsSysId = adT1.RewardPointsSysId)) as Totalconsumed"));
        $select->joinLeft(array('tb2' => 'TB_Agency'), "tb2.AgencySysId = tbl.AgencySysId", array('Title as AgencyName'));
        $select->Where('tbl.MasterAgencySysId = ?', $AgencySysId);
        $select->Where('tbl.IsMarkForDel = ?', 0);
        $select->Where('tbl.IsActive = ?', 1);
        if ($rwdId) {
            $select->Where('tbl.RewardPointsSysId = ?', $rwdId);
            return $this->_dbObj->fetchRow($select);
        } else {
            // echo $select; exit;
            return $select;
        }
    }

    public function getRecordListingRewarHistoryPage($rwdId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "Tb_Agency_Reward_Points_History"));
        $select->joinLeft(array('tb2' => 'TB_Agency_Customer_TravelPlan'), "tb2.TPSysId = tbl.ProposalId", array('Cities'));
        $select->Where('tbl.RewardPointsSysId = ?', $rwdId);
        $select->Where('tbl.MasterAgencySysId = ?', $AgencySysId);
        $select->Where('tbl.IsMarkForDel = ?', 0);
        $select->order("tbl.HistoryRPSysId DESC");
        return $select;
    }

    public function getRewardPoints($AgencySysId, $MasterAgencySysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('T1' => "TB_Agency"), array(''));
        $select->joinLeft(array('T2' => 'TB_Agency_Reward_Points'), "T1.AgencySysId = T2.MasterAgencySysId AND T2.AgencySysId = $AgencySysId", array('BalancePoints'));
        $select->Where('T1.SecurityKey = ?', $MasterAgencySysId);
        $select->Where('T2.AgencySysId = ?', $AgencySysId);
        $select->Where('T1.IsMarkForDelete = ?', 0);
        $select->Where('T1.IsApproved = ?', 1);
        $select->Where('T1.IsActive = ?', 1);
        $select->Where('T2.IsActive = ?', 1);
        $select->Where('T2.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return isset($result['BalancePoints']) ? $result['BalancePoints'] : 0;
    }

    public function GetProposalDataWithAddonCost($TPSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $versionarray = array('TPSysId', 'MasterTPSysId', 'VersionId', 'PlanType', 'GSTSharedMode', 'NetPrice', 'TotalCostGen', 'SourcePlaceSysId', 'EconomyMask', 'PackSpecType','packageTypeCategory', 'InternalRemarks', 'DiscountType', 'DiscountVal', 'CustomDiscount', 'ServiceTaxOnCustomDiscount', "((select sum(adT1.Tax) FROM TB_Agency_Customer_TravelPlan_AddonServices adT1 where adT1.IsMarkForDelete = '0' AND tbl.TPSysId = adT1.TPSysId AND (adT1.PlanType = 21 OR adT1.PlanType = 19))) as TotalTcs");
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $versionarray);
        $select->joinLeft(array('tb3' => "TB_Master_Currency"), "tbl.CurrencyType = tb3.CurrencyType", 'Symbol as CurrencySymbol');
        $select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where('tbl.AgencySysId = ?', $AgencySysId);
        $select->where("tbl.IsActive = ?", 1);
        $select->where("tbl.IsMarkForDel = ?", 0);
        $select->order("tbl.VersionId ASC");
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanCustomerInvHotelDetailsMaping($tpID)
    {
        $select = $this->_dbObj->select();
        $travelplanarray = array('*');
        $travel_itenary = array('');
        $travel_accom = array('AccoSysId', 'VersionId');
        $arrAccomdationInventory = array('RoomType', 'MealPlanType', 'Adult', 'Child', 'FromDate', 'ToDate');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan", $travelplanarray));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb6' => "TB_Agency_Customer_TravelPlan_Accom_Invn_Mapping"), "tb6.InvnItemSysId = tb3.VersionId", $arrAccomdationInventory);
        $select->where('tb1.TPSysId = ?', $tpID);

        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function getPaxInfoWithDocDetail($TPSysId, $TPPaxSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Pax"), array("MemberSysId", "CustomerSysId", 'TPPaxSysId'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Visa_Final_Document"), "tbl.TPPaxSysId = tb2.TPPaxSysId", array('ApplicationNo', 'UploadedVisaPath', 'Remark as message', 'Status as paxTypeStatus', 'InterviwDate', 'Remark', 'UpdateDate'));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_Members"), "tbl.MemberSysId = tb3.MemberSysId", array('Title as Salutaion', 'FirstName', 'LastName', 'PassportIssue', 'Relation', 'PassportNo', 'PassportExpiry'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tbl.CustomerSysId = tb4.CustomerSysId", array('FirstName as CustomerFirstName', 'LastName as CustomerLastName'));

        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.TPPaxSysId = ?', $TPPaxSysId);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function getSenderId($SenderEmailSysId, $AgencySysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Sender_EmailID"), array("SenderEmailID"));
        $select->Where('tbl.SenderSysId = ?', $SenderEmailSysId);
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function CopyProposalPaymentData($data)
    {
        $RefTPSysId = $data['RefTPSysId'];
        $TPSysId = $data['TPSysId'];
        $MasterTPSysId = $data['MasterTPSysId'];
        $CustomerSysId = $data['CustomerSysId'];
        $AgencySysId = $data['AgencySysId'];
        $AgentSysId = $data['AgentSysId'];
        $NetPrice = $data['NetPrice'];
        if ($RefTPSysId > 0 && $TPSysId > 0) {
            $TblAgencyCustomerTrx = new Travel_Model_TblAgencyCustomerTrx();
            $objAgency = new Travel_Model_TblAgency();
            $objPackage = new Travel_Model_TblPackage();
            $objPkgBooking = new Travel_Model_TblPackageBooking();
            $getTrxDetailByPlanId = $TblAgencyCustomerTrx->getTrxDetailByPlanId($RefTPSysId);
            $getAdvancedBalance = $this->getAdvancedBalance($TPSysId);
            $TotalAmountPaidNew = isset($getAdvancedBalance[0]['TotalAmountPaid']) ? $getAdvancedBalance[0]['TotalAmountPaid'] : 0;
            if (!empty($getTrxDetailByPlanId) && $TPSysId > 0) {
                $TotalAmountPaid = $TotalAmountPaidWOTCS = 0;
                foreach ($getTrxDetailByPlanId as $tKey => $tValue) {
                    //                    $TrxSysId[] = $tValue['TrxSysId']; 
                    $TotalAmountPaid = $TotalAmountPaid + (float) $tValue['NetAmount'];
                    $TotalAmountPaidWOTCS = $TotalAmountPaidWOTCS + (float) ($tValue['NetAmount'] - $tValue['TcsFivePercentage'] - $tValue['TcsTwentyPercentage']);
                }

                //                $TrxSysIds = implode(',',$TrxSysId);  
                //                $updateResponse = $TblAgencyCustomerTrx->updateTraxDataByTrxSysIds($TrxSysIds,$TPSysId); 
                $updateResponse = 0;
                if ($TotalAmountPaidNew == 0) {
                    $updateResponse = $this->saveTRXData($data, $TotalAmountPaid, $getTrxDetailByPlanId);
                }
                if ($updateResponse == 1) {
                    $whereProposalOld = "TPSysId = " . $RefTPSysId;
                    $updatetravelplanproposalOld = array(
                        'StatusType' => 15,
                    );
                    $this->UpdateCustomerTravelPlan($updatetravelplanproposalOld, $whereProposalOld);

                    if (round($NetPrice) <= round($TotalAmountPaidWOTCS)) {
                        $StatusType = 143;
                        $PaymentStatue = 22;
                        $BookingStatus = 21;
                    } else if (round($NetPrice) > round($TotalAmountPaidWOTCS)) {
                        $StatusType = 143;
                        $PaymentStatue = 23;
                        $BookingStatus = 21;
                    } else {
                        $StatusType = 3;
                        $PaymentStatue = null;
                        $BookingStatus = null;
                    }
                    $objPkgBooking->updateProposalStatus($StatusType, $PaymentStatue, $BookingStatus, $TPSysId, $MasterTPSysId);
                    if (round($NetPrice) < round($TotalAmountPaidWOTCS)) {
                        $topupAmount = $TotalAmountPaidWOTCS - $NetPrice;
                        $CreditDate = date("Y-m-d H:i");
                        $getCreditLimitDataByCustomerId = $objAgency->getCreditLimitDataByCustomerId($CustomerSysId);
                        $WalletSysId = isset($getCreditLimitDataByCustomerId[0]['WalletSysId']) ? (int) $getCreditLimitDataByCustomerId[0]['WalletSysId'] : 0;
                        $PaymentMode = 'Add Topup';
                        $TrxType = 1;
                        $topupRemark = 'Proposal ID-' . $TPSysId;
                        if ($WalletSysId > 0) {
                            $BalanceAmount = isset($getCreditLimitDataByCustomerId[0]['BalanceAmount']) ? ($getCreditLimitDataByCustomerId[0]['BalanceAmount']) : 0;
                            $saveHistoryData = [
                                'ReferenceNo' => '',
                                'AgencySysId' => $AgencySysId,
                                'WalletSysId' => $WalletSysId,
                                'CustomerSysId' => $CustomerSysId,
                                'PlanType' => 7,
                                'PaymentMode' => $PaymentMode,
                                'CurrencyType' => (int) $data['CurrencyType'],
                                'CreditAmount' => $topupAmount,
                                'BalanceAmount' => $BalanceAmount,
                                'CreditDays' => 0,
                                'CreditDate' => $CreditDate,
                                'UserSysId' => $AgentSysId,
                                'Remark' => $topupRemark,
                                'IsCredit' => 2,
                                'OTPCode' => '',
                                'CodeValidFrom' => $CreditDate,
                                'CodeValidTo' => $CreditDate,
                                'CreateDate' => $CreditDate,
                                'UpdateDate' => $CreditDate,
                                'IsMarkForDel' => 0,
                                'IsActive' => 0,
                                'TrxType' => $TrxType,
                                'Amount' => $topupAmount,
                                'TPSysId' => $TPSysId
                            ];
                            try {
                                $objPackage->insertData('TB_Agency_Customer_B2C_Wallet_History', $saveHistoryData);
                            } catch (Zend_Exception $e) {
                                $returnErrorMessage = $e->getMessage();
                                $response = array('status' => false, 'msg' => $returnErrorMessage, 'CreditSysId' => '');
                            }
                        } else {
                            $saveData = [
                                'AgencySysId' => $AgencySysId,
                                'CurrencyType' => (int) $data['CurrencyType'],
                                'BalanceAmount' => 0,
                                'CreditDays' => '',
                                'IsOneTime' => 1,
                                'CreditDate' => $CreditDate,
                                'CustomerSysId' => $CustomerSysId,
                                'CreateDate' => date('Y-m-d H:i'),
                                'UpdateDate' => date('Y-m-d H:i:s'),
                                'IsMarkForDel' => 0,
                                'IsActive' => 1,
                                'CreditAmount' => 0,
                            ];
                            $WalletSysId = $objPackage->insertData('TB_Agency_Customer_B2C_Wallet', $saveData);
                            $PaymentMode = 'Add Topup';
                            $TrxType = 1;
                            $topupRemark = 'Proposal ID-' . $TPSysId;
                            $saveHistoryData = [
                                'ReferenceNo' => '',
                                'AgencySysId' => $AgencySysId,
                                'WalletSysId' => $WalletSysId,
                                'CustomerSysId' => $CustomerSysId,
                                'PlanType' => 7,
                                'PaymentMode' => $PaymentMode,
                                'CurrencyType' => (int) $data['CurrencyType'],
                                'CreditAmount' => $topupAmount,
                                'BalanceAmount' => $topupAmount,
                                'CreditDays' => '',
                                'CreditDate' => $CreditDate,
                                'UserSysId' => $AgentSysId,
                                'Remark' => $topupRemark,
                                'IsCredit' => 2,
                                'OTPCode' => '',
                                'CodeValidFrom' => $CreditDate,
                                'CodeValidTo' => $CreditDate,
                                'CreateDate' => $CreditDate,
                                'UpdateDate' => $CreditDate,
                                'IsMarkForDel' => 0,
                                'IsActive' => 0,
                                'TrxType' => $TrxType,
                                'Amount' => $topupAmount,
                                'TPSysId' => $TPSysId
                            ];
                            try {
                                $objPackage->insertData('TB_Agency_Customer_B2C_Wallet_History', $saveHistoryData);
                                $response = array('status' => true, 'msg' => 'Success', 'CreditSysId' => '');
                            } catch (Zend_Exception $e) {
                                $returnErrorMessage = $e->getMessage();
                                $response = array('status' => false, 'msg' => $returnErrorMessage, 'CreditSysId' => '');
                            }
                        }
                    }


                    $wherePax = array('TPSysId = ? ' => $RefTPSysId);
                    $savePaxData = array(
                        'TPSysId' => $TPSysId
                    );
                    $objPackage->updateData('TB_Agency_Customer_TravelPlan_Pax', $savePaxData, $wherePax);
                }
                return $updateResponse;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public function saveTRXData($data, $TotalAmountPaid, $getTrxDetailByPlanId)
    {      //  error_reporting(E_ALL);
        $this->paymentMdl = new Payment_Model_Payment();
        $FinanceModel = new Finance_Model_Finance();
        $PaidAmount = $NetAmount = $amount = $TotalAmountPaid;
        $Markup = $data['MarkUp'];
        $AgencyMarkUp = $data['AgencyMarkUp'];
        $GTXMarkup = $data['GTXMarkup'];
        $TransFee = 0;
        $Commission = 0;
        $TrxTypeArray = array(1 => 'F', 2 => 'H', 5 => 'P', 6 => 'V', 9 => 'S', 10 => 'M', 11 => 'T');
        $MarketPlaceId = ($data['IsB2BProposal'] == 1) ? 2 : 1;
        $PlanType = $data['PlanType'];
        $TrxType = isset($TrxTypeArray[$PlanType]) ? $TrxTypeArray[$PlanType] : 'P';

        $TrxDate = $getTrxDetailByPlanId[0]['TrxDate'];
        $ConversionRate = isset($getTrxDetailByPlanId[0]['ConversionRate']) ? $getTrxDetailByPlanId[0]['ConversionRate'] : 0;

        $CustomerSysId = $data['CustomerSysId'];
        $AgencySysId = $data['AgencySysId'];
        $AgencyUserSysId = $data['AgentSysId'];
        $TPSysId = $tpproposalID = $data['TPSysId'];
        $CurrencyType = $data['CurrencyType'];

        $SupplierSourceStr = $AgencySysId . "/myinventory";

        $RoomInfoJson = json_decode($data['RoomInfoJson'], 1);

        $PaxCount = 0;
        foreach ($RoomInfoJson as $roomKey => $roomValue) {
            $noofPax = (int)$roomValue['Adult'] + (int)$roomValue['Child'] + (int)$roomValue['Infant'];
            $PaxCount = $PaxCount + $noofPax;
        }
        $wallet = $this->paymentMdl->getDetailsByUniqueId("TB_Agency_Wallet", "AgencySysId", $AgencySysId);

        $ServiceTax = $data['XServiceTaxAmount'];
        $GTXServiceTaxAmount = $data['GTXServiceTaxAmount'];
        $AgentServiceTaxAmount = $data['AgentServiceTaxAmount'];
        $AgentsCustomServiceTaxAmount = $data['AgentsCustomServiceTaxAmount'];

        $offlinedate = date('Y-m-d');

        foreach ($getTrxDetailByPlanId as $trxKey => $trxValue) {
            $txnid = $trxValue['XRefTrxNo'];
            $addData_Trx = array(
                'MPSysId' => $MarketPlaceId,
                'InvoiceId' => '',
                'TrxOrdDocId' => $PlanType,
                'TrxDate' => $trxValue['TrxDate']->format('Y-m-d H:i:s'),
                'TrxType' => $trxValue['TrxType'],
                'TrxPayMediaType' => $trxValue['TrxPayMediaType'],
                'CrPartyAccSysId' => $trxValue['CrPartyAccSysId'],
                'DrPartyAccSysId' => "",
                'CrPartyName' => 'GTX', //Agency Name
                'DrPartyName' => $trxValue['DrPartyName'],
                'CurrencyType' => $trxValue['CurrencyType'],
                'Amount' => $trxValue['Amount'],
                'Markup' => $trxValue['Markup'],
                "AgencyMarkUp" => $trxValue['AgencyMarkUp'],
                "GTXMarkup" => $trxValue['GTXMarkup'],
                "TrxFee" => $trxValue['TrxFee'],
                "Commission" => $trxValue['Commission'],
                'TotalDiscount' => 0,
                'PaidAmount' => $trxValue['PaidAmount'],
                'NetAmount' => $trxValue['NetAmount'],
                'TrxStatus' => $trxValue['TrxStatus'],
                'TBPoints' => 0,
                'IsActive' => $trxValue['IsActive'],
            );
            $TrxSysId = $this->paymentMdl->insertTable("TB_Trx", $addData_Trx);

            $addDataAgency_Customer_Trx = array(
                "CustomerSysId" => $CustomerSysId,
                "AgencySysId" => $AgencySysId,
                "UserSysId" => $AgencyUserSysId,
                "TrxSysId" => $TrxSysId,
                'XRefTrxNo' => $txnid,
                'TPSysId' => $TPSysId,
                'MPSysId' => $MarketPlaceId,
                'TrxDate' => $trxValue['TrxDate']->format('Y-m-d H:i:s'),
                'TrxUpdatedOn' => "",
                'PaymentModeType' => $trxValue['PaymentModeType'],
                'InvoiceId' => '',
                'TrxOrdDocId' => $PlanType,
                'TrxType' => $trxValue['TrxType'],
                'TrxPayMediaRefNo' => "",
                'CrPartyAccSysId' => $trxValue['CrPartyAccSysId'],
                "DrPartyAccSysId" => 0,
                "CrPartyName" => "GTX",
                "DrPartyName" => $trxValue['DrPartyName'],
                'TrxPayMediaType' => $trxValue['TrxPayMediaType'],
                'CurrencyType' => $trxValue['CurrencyType'],
                "SupplierSourceStr" => $SupplierSourceStr,
                "PaxCount" => $PaxCount,
                'Amount' => $trxValue['Amount'],
                'Markup' => $trxValue['Markup'],
                "AgencyMarkUp" => $trxValue['AgencyMarkUp'],
                "GTXMarkup" => $trxValue['GTXMarkup'],
                "TrxFee" => $trxValue['TrxFee'],
                "Commission" => $trxValue['Commission'],
                'TotalDiscount' => 0,
                'PaidAmount' => $trxValue['PaidAmount'],
                'NetAmount' => $trxValue['NetAmount'],
                'TBPoints' => 0,
                'TrxStatus' => $trxValue['TrxStatus'],
                'IsActive' => $trxValue['IsActive'],
                'IsTCS' => $trxValue['IsTCS'],
                'TcsFivePercentage' => $trxValue['TcsFivePercentage'],
                'TcsTwentyPercentage' => $trxValue['TcsTwentyPercentage'],
                'PancardNumber' => $trxValue['PancardNumber'],
                'ConversionRate' => $trxValue['ConversionRate'],
                'IsPanVarified' => $trxValue['IsPanVarified'],
            );
            $this->paymentMdl->insertTable("TB_Agency_Customer_Trx", $addDataAgency_Customer_Trx);
            $addData = array(
                'TrxId' => $TrxSysId,
                'AgencySysId' => $AgencySysId,
                'WalletSysId' => $wallet['WalletSysId'],
                'XRefTPSysId' => $TPSysId,
                "GUID" => $txnid,
                "TrxDate" => $offlinedate,
                'TrxType' => $trxValue['TrxType'],
                'InvoiceId' => '0',
                'TrxOrdDocId' => $PlanType,
                'PaymentModeType' => $trxValue['PaymentModeType'],
                "TrxPayMediaType" => $trxValue['TrxPayMediaType'],
                'TransFee' => $trxValue['TransFee'],
                "TrxPayMediaRefNo" => $trxValue['WalletTrxPayMediaRefNo'],
                "OffLinePaymentRefNo" => $trxValue['OffLinePaymentRefNo'],
                "OffLinePaymentBrank" => $trxValue['OffLinePaymentBrank'],
                "OffLinePaymentBranch" => $trxValue['OffLinePaymentBranch'],
                'CrPartyAccSysId' => $trxValue['CrPartyAccSysId'],
                'DrPartyAccSysId' => 0,
                "SupplierSourceStr" => $SupplierSourceStr,
                "PaxCount" => $PaxCount,
                'CrPartyName' => "GTX", //Agency Name
                'DrPartyName' => $trxValue['DrPartyName'],
                'CurrencyType' => $trxValue['CurrencyType'],
                'TotalDiscount' => 0,
                "Amount" => $trxValue['Amount'],
                'NetAmount' => $trxValue['NetAmount'],
                'PaidAmount' => $trxValue['PaidAmount'],
                "ClosingBalance" => 0,
                'TBPoints' => 0,
                "IsActive" => $trxValue['IsActive'],
                "UserSysId" => $AgencyUserSysId, //insert user id
                "CreateDate" => date('Y-m-d H:i:s'),
                "UpdateDate" => date('Y-m-d H:i:s'),
                "IsApproved" => $trxValue['IsApproved'],
                "ApprovedBy" => $AgencyUserSysId,
                "ApprovedDate" => date('Y-m-d H:i:s'),
                "IsMarkForDel" => false
            );
            $this->paymentMdl->insertTable("TB_Agency_Wallet_Trx", $addData);
            $addTDSData = array(
                'TrxSysId' => $TrxSysId,
                'GTXTDS' => "0",
                'AgencyTDS' => "0",
                'XServiceTaxAmount' => $ServiceTax,
                'GTXServiceTaxAmount' => $GTXServiceTaxAmount,
                'AgentServiceTaxAmount' => $AgentServiceTaxAmount,
                'AgentsCustomServiceTaxAmount' => $AgentsCustomServiceTaxAmount,
                'IsActive' => True
            );
            // echo "<pre>";print_r($addTDSData);exit;
            $this->paymentMdl->insertTable("TB_Trx_Tax", $addTDSData);
            if($trxValue['TrxSysId'] > 0){
                $whereTBTrx = array('TrxSysId =?' => $trxValue['TrxSysId']);
                $whereWalletTrx = array('TrxId =?' => $trxValue['TrxSysId']);
                $updateTBTrx = array("IsActive" => 0);
                $this->paymentMdl->updateTable("TB_Trx", $updateTBTrx, $whereTBTrx);
                $this->paymentMdl->updateTable("TB_Agency_Customer_Trx", $updateTBTrx, $whereTBTrx);
                $this->paymentMdl->updateTable("TB_Agency_Wallet_Trx", $updateTBTrx, $whereWalletTrx);
            }
            
            
            
        }

        $whereProposalNew = "TPSysId = " . $TPSysId;
        $updatetravelplanproposalNew = array(
            'ApproveDate' => (isset($TrxDate) && $TrxDate->format('Y') > 1970) ? $TrxDate->format('Y-m-d H:i:s') : date('Y-m-d H:i:s'),
        );
        if (!empty($ConversionRate)) {
            $updatetravelplanproposalNew['BookingConversionRate'] = $ConversionRate;
        }
        $this->UpdateCustomerTravelPlan($updatetravelplanproposalNew, $whereProposalNew);
        $FinanceModel->addCommissionData($TPSysId);
        $modelAgency = new Travel_Model_TblAgencyCustomerTrx();
        $modelAgency->updateFirstEntryInBalanceSheet($tpproposalID, $AgencySysId);
        $modelAgency->updateSecondEntryInBalanceSheet($tpproposalID, $AgencySysId, $TrxSysId, $NetAmount);
        return 1;
    }

    public function GUID()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }
        return sprintf('%04X%04X%04X%04X%04X%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
    }

    public function sendWhatsAppMessage($whatsappData, $baseUrl)
    {
        $postData = $whatsappData;
        unset($postData['SecurityKey']);
        $curl = curl_init($baseUrl . "/gtxwebservices/whatsapp/package");
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'SecurityKey: ' . $whatsappData['SecurityKey'],
        ));
        $getPackagesData = curl_exec($curl);
        curl_close($curl);
        //        if ($whatsappData['SecurityKey'] == '7A739273-D037-4386-9B23-BCD6A4B1ED8B') {
        //            echo "<pre>";print_r($getPackagesData); exit;
        //        }
        return $getPackagesData;
    }

    public function sendFlightProposalMessage($whatsappData)
    {
        $baseUrl = Catabatic_Helper::getSiteUrl();
        $postData = $whatsappData;
        unset($postData['SecurityKey']);
        $curl = curl_init($baseUrl . "/gtxwebservices/whatsapp/filght-proposal");
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'SecurityKey: ' . $whatsappData['SecurityKey'],
        ));
        $getPackagesData = curl_exec($curl);
        curl_close($curl);
        return $getPackagesData;
    }

    public function sendVisaMessage($whatsappData)
    {
        $baseUrl = Catabatic_Helper::getSiteUrl();
        $postData = $whatsappData;
        unset($postData['SecurityKey']);
        $curl = curl_init($baseUrl . "/gtxwebservices/whatsapp/visa");
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'SecurityKey: ' . $whatsappData['SecurityKey'],
        ));
        $getPackagesData = curl_exec($curl);
        curl_close($curl);
        return $getPackagesData;
    }

    public function getCustomerProposalPromotion($AgencySysId, $TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Promotions"), array('*'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $select->Where('tbl.IsMarkForDelete = ?', 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function checkAgencyRewardPoints($AgencySysId, $MasterAgencySysId, $TPSysId = null)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Reward_Points_History"), array('RewardPointsSysId'));
        $select->Where('tbl.MasterAgencySysId = ?', $MasterAgencySysId);
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $select->Where('tbl.TrxType = ?', 1);
        if ($TPSysId) {
            $select->Where('tbl.ProposalId = ?', $TPSysId);
        } else {
            $select->Where('tbl.Remark = ?', 'Welcome To Registration');
        }
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanHistoryUpdates($AgencySysId, $TPSysId, $TPPaxSysId = 0)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_History"), array('Remark', 'CreateDate', 'Status', 'IsManualAdded'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Visa_Document"), "tbl.DocId = tb2.DocId AND tbl.TPSysId = tb2.TPSysId AND tbl.TPPaxSysId = tb2.TPPaxSysId", array('DocName'));
        $select->joinLeft(array('tb3' => "TB_Agency_User"), "tbl.UserSysId = tb3.UserSysId", array('FirstName', 'LastName'));
        $select->Where('tbl.AgencySysId = ?', $AgencySysId);
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        if ($TPPaxSysId) {
            $select->Where('tbl.TPPaxSysId = ?', $TPPaxSysId);
        }
        $select->Where('tbl.DocId > ?', 0);
        $select->order('tbl.CreateDate DESC');
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetTravelPlanVisaLeadpaxDeail($TPSysId)
    {
        $select = $this->_dbObj->select();
        $travelplanArray = array('TPSysId', 'PlanType', 'IsPlanViewed', 'AgentSysId', 'AgencySysId', 'IsHotelOnlyPackage', 'OpsAgentSysId', 'TPId', 'IsB2BProposal', 'CustomerSysId', 'StartDate', 'DestinationPlaces', 'Title', 'MinPax', 'CreateDate');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travelplanArray);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tbl.TPSysId = tb2.TPSysId", array('TPPaxSysId'));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb3.CustomerSysId", array('AgencySysId as CustomerAgencySysId', 'Title as CustomerSalutation', 'FirstName as CustomerFirstName', 'LastName as CustomerLastName', 'countrycode as Customercountrycode', 'Contacts as CustomerContacts', 'EmailId as CustomerEmailId'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_Members"), "tb2.MemberSysId = tb4.MemberSysId", array('MemberSysId', 'Title as MemberSalutation', 'FirstName as MemberFirstName', 'LastName as MemberLastName', 'countrycode as Membercountrycode', 'Contacts as MemberContacts', 'EmailId as MemberEmailId'));
        $select->joinLeft(array('tb5' => "TB_Agency"), "tb3.AgencySysId = tb5.AgencySysId", array('DisplayName'));
        $select->joinLeft(array('tb6' => 'TB_Agency_User'), 'tb5.AgencySysId=tb6.AgencySysId AND tb5.PrimaryUserSysId=tb6.UserSysId', array("FirstName", "LastName", "countrycode", "ContactNo1"));
        $select->where('tbl.TPSysId = ?', $TPSysId);
        $select->where('tb2.IsLeadpax = ?', 1);
        //        echo $select;die;
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }

    public function GetTravelPlanUploadedDocuments($TPSysId, $TPPaxSysId = 0, $FieldType = '', $Status = '', $IsMandatory = '')
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Visa_Document"), array("TPSysId", "TPPaxSysId", "DocId", "DocName", "DocImagePath", "Remark", "Status", "IsMandatory"));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Pax"), "tbl.TPPaxSysId = tb2.TPPaxSysId", array("MemberSysId", "CustomerSysId"));
        $select->joinLeft(array('tb3' => "TB_Agency_Customer"), "tb2.CustomerSysId = tb3.CustomerSysId", array('Title as CustomerSalutaion', 'FirstName as CustomerFirstName', 'LastName as CustomerFirstName'));
        $select->joinLeft(array('tb4' => "TB_Agency_Customer_Members"), "tb2.MemberSysId = tb4.MemberSysId", array('Title as MemberSalutaion', 'FirstName as MemberFirstName', 'LastName as MemberLastName'));
        $select->Where('tbl.TPSysId = ?', $TPSysId);
        if (!empty($TPPaxSysId)) {
            $select->Where('tbl.TPPaxSysId = ?', $TPPaxSysId);
        }
        if (!empty($FieldType)) {
            $select->Where("tbl.FieldType like '%" . $FieldType . "%'");
        }
        if ($Status != '') {
            $select->Where('tbl.Status = ?', $Status);
        }
        if ($IsMandatory != '') {
            $select->Where('tbl.IsMandatory = ?', $IsMandatory);
        }
        $select->order('tbl.TPPaxSysId ASC');
        //        echo $select;die;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function CheckAndUpdateProposalOpsAgentSysId($TPSysId, $AgentSysId)
    {
        $status = 0;
        if ((int) $TPSysId > 0 && (int) $AgentSysId > 0) {
            $select = $this->_dbObj->select();
            $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), array('OpsAgentSysId', 'MasterTPSysId'));
            $select->where('tbl.TPSysId = ?', $TPSysId);
            //            $select->where('tbl.OpsAgentSysId > ?', 0); 
            $result = $this->_dbObj->fetchRow($select);
            $updatetravelplan = array(
                'UpdateDate' => date('Y-m-d H:i')
            );
            if (empty($result['OpsAgentSysId']) && $result['MasterTPSysId'] > 0) {
                $whereQuery = "TPSysId = " . (int) $result['MasterTPSysId'];
                $updatetravelplanQuery = array(
                    'OpsAgentSysId' => $AgentSysId,
                    'UpdateDate' => date('Y-m-d H:i'),
                );
                $this->UpdateCustomerTravelPlanQuery($updatetravelplanQuery, $whereQuery);

                $updatetravelplan['OpsAgentSysId'] = $AgentSysId;
                $status = 1;
            }
            $where = "TPSysId = " . $TPSysId;
            $this->UpdateCustomerTravelPlan($updatetravelplan, $where);
        }
        return $status;
        exit;
    }

    public function GetCustomerTravelPlanAccomByVersionIds($versionIds)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Accom"), array());
        $select->joinLeft(array('tb11' => "TB_Agency_Customer_TravelPlan_Accom"), "tbl.TPIntSysId = tb11.TPIntSysId AND tb11.IsSelectedOnPkg = 1", array('TPIntSysId','AccoSysId', 'Title', 'FromDate', 'ToDate', 'TotalNights', 'RoomTypeStr', 'SupplierSysId', 'RoomType', 'MealPlanType' ,'AdultPax' , 'ChildPax' , 'InfantPax' , 'CostQuad' , 'CostQuint' , 'CostHexa' , 'ExtraAdult' , 'ChildNoBed' , 'SingleOAdult', 'NoOfRoom'));
        $select->joinLeft(array('tb2' => "TB_Master_Geo_City"), "tbl.XRefCityId = tb2.CityId", array('Title as CityTitle'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));
        $select->joinLeft(array('tb4' => "TB_Master_RoomType"), "tb11.RoomType = tb4.RoomType", array('Title as RoomName'));
        $select->joinLeft(array('tb5' => 'TB_Master_Accom_MealType'), 'tb11.MealPlanType = tb5.MealTypeId', array("Title as MealPlanTypeTitle"));
        $select->Where('tbl.VersionId IN (?) ', $versionIds);
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsSelectedOnPkg = ?', '1');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order("tbl.FromDate ASC");
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanSightseeingByVersionIds($versionIds)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Sightseeing"), array('SSSysId', 'Title', 'FromDate', 'ToDate', 'PriceType', 'SupplierSysId', 'SeqId','PickupLocation','DropLocation','AdultPax','ChildPax','InfantPax'));
        $select->joinLeft(array('tb2' => "TB_Master_Geo_City"), "tbl.CityId = tb2.CityId", array('Title as CityTitle'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));
        $select->Where('tbl.VersionId IN (?) ', $versionIds);
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order("tbl.VersionId ASC");
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanFlightByVersionIds($versionIds)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_Air"), array('SupplierSysId', 'encodedata', 'AirlineSysId'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));
        if (is_array($versionIds)) {
            $select->Where('tbl.VersionId IN (?) ', $versionIds);
        } else {
            $select->Where('tbl.VersionId IN (' . $versionIds . ')');
        }
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order("tbl.VersionId ASC");
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanTransferByVersionIds($versionIds)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_Trans_Fixed"), array('SupplierSysId', 'FromDate', 'FromPlace', 'ToPlace', 'Type_Text', 'VehicleQty'));
        $select->joinLeft(array('tb2' => "TB_Master_Geo_City"), "tbl.SourceCityId = tb2.CityId", array('Title as FromCityTitle'));
        $select->joinLeft(array('tb21' => "TB_Master_Geo_City"), "tbl.DestCityId = tb21.CityId", array('Title as EnCityTitle'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));

        if (is_array($versionIds)) {
            $select->Where('tbl.FixTransSysId IN (?) ', $versionIds);
        } else {
            $select->Where('tbl.FixTransSysId IN (' . $versionIds . ')');
        }
        $select->Where('tbl.IsMarkForDel = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order("tbl.FixTransSysId ASC");
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }

    public function GetCustomerTravelPlanOtherServicesByVersionIds($versionIds, $ServiceType = 0)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan_OtherServices"), array('SupplierSysId', 'ServiceTitle', 'ServiceType', 'Comment'));
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tbl.ItenarySysId = tb2.TPIntSysId", array('Sequence'));
        $select->joinLeft(array('tb3' => "TB_IC_Supplier"), "tbl.SupplierSysId = tb3.SupplierSysId", array('SupplierName'));

        if (is_array($versionIds)) {
            $select->Where('tbl.VersionId IN (?) ', $versionIds);
        } else {
            $select->Where('tbl.VersionId IN (' . $versionIds . ')');
        }
        if ($ServiceType > 0) {
            $select->Where('tbl.ServiceType = ?', $ServiceType);
        }
        $select->Where('tbl.IsMarkForDelete = ?', '0');
        $select->Where('tbl.IsActive = ?', '1');
        $select->order("tbl.VersionId ASC");
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }
    public function GetCustomerTravelPlanVisaDetail($TPIntSysId)
    {
        $select = $this->_dbObj->select();
        $travelVisaColumn = array('InvnVisaAllSysId', 'IsAgentSpec', 'ICSourceSysId', 'NationalitySysId', 'CountriesCoveredSysId', 'VisaName', 'VisaRequired', 'VisaCategory', 'VisaType', 'VisaValidity', 'VisaDuration', 'VisaAdultRates', 'VisaChildRates', 'VisaInfantRates', 'VisaFamilyOfRates', 'CreateDate', 'UpdateDate', 'IsApproved', 'ApproveDate', 'ApproveBy', 'IsActive', 'IsMarkForDel', 'SupplierSysId', 'CurrencyType as visaCurrencyType', 'DocsRequiredText', 'DocName1', 'DocFileName1', 'DocName2', 'DocFileName2', 'DocName3', 'DocFileName3', 'DocName4', 'DocFileName4', 'DocName5', 'DocFileName5', 'DocName6', 'DocFileName6', 'PrecessingTime', 'BasicRequirementsText', 'EmbassyAddressText', 'Iswebsite');
        $travelItenaryVisaColumn = array('VisaSysId', 'NetCost', 'VisaDuration', 'VisaValidity');
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Visa"), $travelItenaryVisaColumn);
        $select->joinLeft(array('tb2' => "TB_MP_Inventory_Visa"), "tb1.VisaSysId = tb2.InvnVisaAllSysId", $travelVisaColumn);
        $select->where('tb1.TPIntSysId = ?', $TPIntSysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDelete = ?', 0);
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }
    public function GetCustomerTravelPlanSubAgencyDetail($TPSysId)
    {
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), array('IsB2BProposal'));
        $select->joinLeft(array('tb2' => "TB_Agency"), "tb1.B2BAgencySysId = tb2.AgencySysId", array('AgencyType', 'DisplayName'));
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsMarkForDel = ?', 0);

        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }
    
    public function getQueryDetailsForFranchisee($TPSysId){
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan_Query"), array('IsB2BProposal', 'B2BAgencySysId'));
        $select->where('tb1.TPSysId = ?', $TPSysId);
        $select->where('tb1.IsActive = ?', 1);
        $select->where('tb1.IsB2BProposal = ?', 3);
        $select->where('tb1.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }
    public function CheckCustomerWithLeadIdCommission($leadId)
    {
        $select = $this->_dbObj->select();
        
        $travel = array('CustomerSysId', 'AgencySysId', 'AgentSysId', 'VersionId', 'MasterTPSysId', 'TPId', 'CreateDate', 'DownloadCount', 'StatusType', 'LeadSourceSysId', 'EmailText', 'IsB2BProposal', 'B2BAgencySysId', 'EconomyMask', 'IsFixedDeparturePackage');
        $select->from(array('tbl' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "Tb_Agency_Commission"), "tbl.TPSysId = tb2.TPSysId", array('Commission'));
        $select->where('tbl.TPSysId = ?', $leadId);
        $select->where('tbl.IsMarkForDel = ?', 0);
        $result = $this->_dbObj->fetchRow($select);
        return $result;
    }
       public function GetHoldHotelDetails()
    {
        $travel = array('TPSysId', 'NetPrice', 'Readymade', 'PlanBookingId', 'RoomInfoJson', 'MasterTPSysId', 'VersionId as ProposalVersionId');
        $travel_itenary = array('TPIntSysId', 'Cities as CityName', 'Sequence');
        $travel_accom = array('VersionId', 'Title as hotelCityTitle', 'FromDate as hotelFromDate', 'TotalCost', 'NetCost', 'ToDate as hotelToDate', 'CreateDate as hotelCreateDate', 'UpdateDate as hotelUpdateDate', 'AdultPax as adultsinHotel', 'TotalNights as hotelTotalNights', 'ChildPax as childsinHotel', 'InfantPax as infentinHotel', 'StarRating as hotelStarRating', 'ChildsAge as hotelChildsAge', 'XrefCityId as hotelXrefCityId', 'AccoSysId as hotelAccoSysId', 'GTXMarkup', 'AgencyMarkUp', 'MarkUp', 'GTXServiceTaxAmount', 'AgentServiceTaxAmount', 'Taxes', 'RoomTypeStr', 'SeqId', 'IsSelectedOnPkg', 'HoldDate', 'HoldStatus');
        $customer_details = array('CRMCustSysId', 'CustomerSysId', 'EmailId', 'Contacts', 'Title', 'FirstName', 'LastName', 'CountryCode', 'IsB2BAgent');
        $supplier_details = array('SupplierSysId', 'SupplierName', 'Salution as SupplierSalution', 'FirstName as SupplierFirstName', 'LastName as SupplierLastName', 'EmailId as SupplierEmailId', 'ContactNo');
        $accom_details = array('Title as ICHotelTitle', 'Rating as ICHotelRating', 'Stars as ICHotelStars');
        $b2bagencyColumn = array('Title as CompanyName', 'BusinessType', 'AgencyType', 'TrxCurrency');
        $select = $this->_dbObj->select();
        $select->from(array('tb1' => "TB_Agency_Customer_TravelPlan"), $travel);
        $select->joinLeft(array('tb2' => "TB_Agency_Customer_TravelPlan_Itenary"), "tb1.TPSysId = tb2.TPSysId", $travel_itenary);
        $select->joinLeft(array('tb3' => "TB_Agency_Customer_TravelPlan_Accom"), "tb2.TPIntSysId = tb3.TPIntSysId", $travel_accom);
        $select->joinLeft(array('tb4' => "TB_Agency_Customer"), "tb1.CustomerSysId = tb4.CustomerSysId", $customer_details);
        $select->joinLeft(array('tb5' => "TB_IC_Supplier"), "tb3.SupplierSysId = tb5.SupplierSysId", $supplier_details);
        $select->joinLeft(array('tb6' => "TB_IC_Accomdation"), "tb3.AccoSysId = tb6.AccomSysId", $accom_details);
        $select->joinLeft(array('tb7' => "TB_Master_RoomType"), "tb3.RoomType = tb7.RoomType", array('Title as RoomTitle'));
        $select->joinLeft(array('tb8' => "TB_Master_Accom_MealType"), "tb3.MealPlanType = tb8.MealTypeId", array('Title as RoomMealType'));
        $select->joinLeft(array('tb9' => "TB_Master_Currency"), "tb3.CurrencyType = tb9.CurrencyType", array('Symbol as CurrencySymbol'));
        $select->joinLeft(array('tb10' => "TB_Agency"), "tb4.AgencySysId = tb10.AgencySysId", $b2bagencyColumn);
        $select->where('tb3.HoldDate != ?', '');
        $select->where('tb3.HoldStatus IN (?)', array(1, 3, 4));

        $select->where("tb1.IsActive = ?", 1);
        $select->where("tb2.IsActive = ?", 1);

        $select->where("tb4.IsActive = ?", 1);
        //$select->where("tb5.IsActive = ?", 1);
        $select->where("tb1.IsMarkForDel = ?", 0);
        $select->where("tb2.IsMarkForDel = ?", 0);

        $select->where("tb4.IsMarkForDelete = ?", 0);
        $select->order('tb2.Sequence ASC');
        $select->order('tb2.TotalMinDays ASC ');
        //$select->where("tb5.IsMarkForDelete = ?", 0);
        //        echo $select;
        $result = $this->_dbObj->fetchAll($select);
        return $result;
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit