<?php

require_once (SF_ROOT_DIR . "/classes/class.dmsd.php");
class CdkFeedApi
{
	private $methods		= array(
							'help-employee'						=> 'post',
							'help-model' 						=> 'post',
							'customer' 							=> 'post'
							);


	public function __construct()
	{
		$this->User 		= 'amermktgmailing';
		$this->Pass 		= 'vykOukucIkAA';

		$this->Mode 		= 'test';
		#$this->Mode 		= 'prod';
		$this->baseurl 		= '';
		$this->ConnDms 		= Propel::GetConnection('dms_main');
		$this->SetTestMode();
		$this->CDmsd 		= new Dmsd();
		$this->CdkSyncDays 	= 10;	// The number of days between syncing of 'helper' data (employees & models)  - tracked in dmsdb10.dms.cdk_extra_sync

	}


	/*
	 * SetTestMode()
	 * ********************************************************************* */
	public function SetTestMode()
	{
		$this->baseurl 		= 'https://uat-3pa.dmotorworks.com/pip-extract/';
		$this->Mode 		= 'test';
	}


	/*
	 * SetProdMode()
	 * ********************************************************************* */
	public function SetProdMode()
	{
		$this->baseurl 		= 'https://uat-3pa.dmotorworks.com/pip-extract/';
		$this->Mode 		= 'prod';
	}


	/*
	 * GetEmployees()
	 * ********************************************************************* */
	public function GetEmployees($CdkDealerId="", $CustomerId=0, $FeedId=0)
	{
		if ( $CdkDealerId == '' )
			return false;

		if( $CustomerId == 0)
		{
			echo "CustomerId = 0 - must be a valid customer_id.\n";
			die("Aborting\n");
		}
		echo "CustomerId = {$CustomerId}\n";


		// Is is type to sync this feed source?
		$SyncRec 			= $this->GetSyncRec($CustomerId, $FeedId, 'EMPLOYEE');

		if ( strtotime($SyncRec['try_next_date']) > time() )
			return false;



		$CdkQuery 			= "HEMPL_Bulk_Service";
		$Api				= "help-employee";

		echo "GetEmployees($CdkDealerId, $CustomerId)\n";
		$Result 	= $this->CallApi($Api, array('queryId'	=> $CdkQuery, 'dealerId' => $CdkDealerId));
		if ( !$Result )
		{
			echo "Returned false\n";
		} else {
			// echo "Result = " . print_r($Result, true) . "\n";
			if( substr($Result, 0, 1) == '<' && substr($Result, -1) == '>' )
			{
				// We got XML data.
				$xml = simplexml_load_string($Result);
				$json = json_encode($xml);
				$ResultArr = json_decode($json, true);
				echo "ResultArr = " . print_r($ResultArr, true) . "\n";
				if ( isset($ResultArr['HelpEmployee']))
				{
					$DmsConn 		= $this->CDmsd->GetDmsDbConn($CustomerId);

					foreach($ResultArr['HelpEmployee'] as $Key => $EmployeeRec)
					{
						$Query 		= "INSERT INTO `dms_employee` (`dms_id`,`employee_name`) VALUES ('" . addslashes($EmployeeRec['Id']) . "', '" . addslashes($EmployeeRec['Name']) . "') "
									. "ON DUPLICATE KEY UPDATE employee_name=VALUES(employee_name) ";
								echo "Query = {$Query}\n";
						$Rs 		= $DmsConn->executeQuery($Query);
					}
				}
			}
		}

		$this->ResetSyncRec($FeedId, 'EMPLOYEE');

	}



	/*
	 * GetEmployees()
	 * ********************************************************************* */
	public function GetModels($CdkDealerId="", $CustomerId=0, $FeedId=0)
	{
		if ( $CdkDealerId == '' )
			return false;

		if( $CustomerId == 0)
		{
			echo "CustomerId = 0 - must be a valid customer_id.\n";
			die("Aborting\n");
		}
		echo "CustomerId = {$CustomerId}\n";


		// Is is type to sync this feed source?
		$SyncRec 			= $this->GetSyncRec($CustomerId, $FeedId, 'MODEL');

		if ( strtotime($SyncRec['try_next_date']) > time() )
			return false;

		// Note
		// ------------------------------------------------------------------------------
		// From: Wilson, Ryan [mailto:Ryan.Wilson@cdk.com] 
		// Sent: Thursday, September 27, 2018 11:04 AM
		// To: Rick Davis
		// Cc: Roanna Valdellon (amms)
		// Subject: RE: API Question - models

		// Rick,

		// The model abbreviations are local to each dealer.

		// You won’t see much changing in this data – only when OEMs release new models, or when the dealer services a specific model for the first time. 

		// I typically recommend running this weekly at the most.

		// Thanks,
		// Ryan
		// ------------------------------------------------------------------------------
		// From: Rick Davis [mailto:rdavis@ammsusa.com] 
		// Sent: Thursday, September 27, 2018 10:01 AM
		// To: Wilson, Ryan <Ryan.Wilson@cdk.com>
		// Cc: Roanna Valdellon (amms) <RValdellon@ammsusa.com>
		// Subject: API Question - models

		// Hey Ryan,

		// Question: Is the list of models unique to each dealer - or is it a general list applied across all dealers?
		// When I call our helper extract PIP 'HMOD_Bulk', for the test dealer - I get 2k+ records.



		$CdkQuery 			= "HMOD_Bulk";
		$Api				= "help-model";

		echo "GetModels($CdkDealerId, $CustomerId, $FeedId)\n";
		$Result 	= $this->CallApi($Api, array('queryId'	=> $CdkQuery, 'dealerId' => $CdkDealerId));
		if ( !$Result )
		{
			echo "Returned false\n";
		} else {
			// echo "Result = " . print_r($Result, true) . "\n";
			if( substr($Result, 0, 1) == '<' && substr($Result, -1) == '>' )
			{
				// We got XML data.
				$xml = simplexml_load_string($Result);
				$json = json_encode($xml);
				$ResultArr = json_decode($json, true);
				echo "ResultArr = " . print_r($ResultArr, true) . "\n";

				// Instead of createing a new table - we'll just overload an HVAC table and use it instead.
				// amms_event_detail.
				//					 external_event_id 			=> Unique key (Make+Model) - for detecting duplicates
				//					 exernal_customer_id 		=> Make (short version of make)
				//					 external_systemunit_id 	=> Model (short version of model)
				//					 event_name 				=> FullMakeName
				//					 invoice 					=> FullModelName

				if ( isset($ResultArr['HelpModel']))
				{
					$DmsConn 		= $this->CDmsd->GetDmsDbConn($CustomerId);

					foreach($ResultArr['HelpModel'] as $Key => $ModelRec)
					{
						$UniqueKey 	= $ModelRec['Make'] . "|" . $ModelRec['Model'];
						$Query 		= "INSERT INTO `amms_event_detail` (`external_event_id`,`external_customer_id`,`external_systemunit_id`,`event_name`,`invoice`) "
									. "VALUES ('" . addslashes($UniqueKey) . "', '" . addslashes($ModelRec['Make']) . "', '" . addslashes($ModelRec['Model'])  . "', '" . addslashes($ModelRec['FullMakeName']) . "', '" . addslashes($ModelRec['FullModelName'])   . "') "
									. "ON DUPLICATE KEY UPDATE external_customer_id=VALUES(external_customer_id),  external_systemunit_id=VALUES(external_systemunit_id), event_name=VALUES(event_name), invoice=VALUES(invoice) ";
							//	echo "Query = {$Query}\n";
						$Rs 		= $DmsConn->executeQuery($Query);
					}
				}
			}
		}

		$this->ResetSyncRec($FeedId, 'MODEL');

	}



	/*
	 * GetCustomers()
	 * ********************************************************************* */
	public function GetCustomers($CdkDealerId="", $CustomerId=0, $FeedId=0, $Mode='delta', $LastSyncDate='')
	{
		if ( $CdkDealerId == '' )
			return false;

		if( $CustomerId == 0)
		{
			echo "CustomerId = 0 - must be a valid customer_id.\n";
			die("Aborting\n");
		}
		echo "CustomerId = {$CustomerId}\n";


		$ArgList 			= array( 'dealerId' => $CdkDealerId);
		switch($Mode)
		{
			case 'bulk':
				$CdkQuery 	= "CUST_Bulk";
				break;
			default:
				$CdkQuery 	= "CUST_Delta";
				$ArgList['deltaDate'] 	= strtotime("m/d/Y", strtotime($LastSyncDate));
				break;
		}
		$ArgList['queryId']	= $CdkQuery;
		

		$Api				= "customer";
		$Response 			= false;

		echo "GetCustomers($CdkDealerId, $CustomerId, $FeedId, $Mode, $LastSyncDate)\n";
		echo " ArgList = " . print_r($ArgList, true) . "\n";
		$Result 	= $this->CallApi($Api, $ArgList);
		if ( !$Result )
		{
			echo "Returned false\n";
		} else {
			echo "Result = " . print_r($Result, true) . "\n";
			if( substr($Result, 0, 1) == '<' && substr($Result, -1) == '>' )
			{
				// We got XML data.
				$xml 		= simplexml_load_string($Result);
				$json 		= json_encode($xml);
				$ResultArr	= json_decode($json, true);
				// echo "ResultArr = " . print_r($ResultArr, true) . "\n";


				if ( isset($ResultArr['Customer']))
				{
					$DmsConn 		= $this->CDmsd->GetDmsDbConn($CustomerId);
					$FieldKeys 		= array('external_customer_id', 
											'customer_name',
											'customer_voice_phone',
											'customer_text_phone',
											'customer_email',
											'customer_email',
											'customer_email2',
											'home_phone',
											'home_ext',
											'work_phone',
											'work_ext',
											'mobile_phone',
											'dms_entry_date',
											'street_address',
											'postal_code',
											'city',
											'state_province',
											'first_name',
											'last_name',
											'middle_name',
											'gender',
											'birthday',
											'salutation',
											'customer_voice_phone_normal',
											'suffix',
											'company'
											);

					$InsertQuery 	= "INSERT INTO dms_consumer (`" . join("`,`", $FieldKeys) . "`) VALUES ";
					$UpdateQueryField = array();

					foreach($FieldKeys as $FieldName)
					{
						if ( $FieldName != 'external_customer_id')	// we don't want to update the unique identifier
						{
							$UpdateQueryField[] = "{$FieldName} = VALUES({$FieldName})";
						}
					}
					$UpdateQuery 	= " ON DUPLICATE KEY UPDATE " . join(",", $UpdateQueryField);
					$QueryRow 		= array();
					$RowCount 		= 1;

					foreach($ResultArr['Customer'] as $Key => $CustRec)
					{
						$Row 		= array();

						// Put something in the blank row
						foreach($FieldKeys as $FieldName)
						{
							$Row[$FieldName] = '';
						}
						$Row['external_customer_id'] 	= $this->ParseField('CustNo', $CustRec);

						$Row['company'] 				= $this->ParseField('NameCompany', $CustRec);
						$Row['customer_name'] 			= $this->ParseField('Name1', $CustRec);
						$Row['salutation'] 				= $this->ParseField('NameTitle', $CustRec);
						$Row['first_name'] 				= $this->ParseField('FirstName', $CustRec);
						$Row['middle_name'] 			= $this->ParseField('MiddleName', $CustRec);
						$Row['last_name'] 				= $this->ParseField('LastName', $CustRec);
						$Row['suffix'] 					= $this->ParseField('NameSuffix', $CustRec);
						$Row['street_address'] 			= $this->ParseField('Address', $CustRec);
						$Addr2 							= $this->ParseField('AddressSecondLine', $CustRec);
						if ( strlen($Addr2) > 0 )
							$Row['street_address']		.= " {$Addr2}";		// Append the 2nd line to the first line
						$Row['city'] 					= $this->ParseField('City', $CustRec);
						$Row['state_province'] 			= $this->ParseField('State', $CustRec);
						$Row['postal_code'] 			= $this->ParseField('ZipOrPostalCode', $CustRec);
						$Row['customer_voice_phone'] 	= $this->ParseField('Telephone', $CustRec);
						$Row['customer_text_phone'] 	= $this->ParseField('Pager', $CustRec);
						$Row['customer_email'] 			= $this->ParseField('Email', $CustRec);
						$Row['customer_email2'] 		= $this->ParseField('Email2', $CustRec);
						$Row['home_phone'] 				= $this->ParseField('HomePhone', $CustRec);
						$Row['home_ext'] 				= $this->ParseField('HomePhoneExt', $CustRec);
						$Row['work_phone'] 				= $this->ParseField('BusinessPhone', $CustRec);
						$Row['work_ext'] 				= $this->ParseField('BusinessPhoneExt', $CustRec);
						$Row['mobile_phone'] 			= $this->ParseField('Cellular', $CustRec);
						$Row['dms_entry_date'] 			= $this->ParseField('DateAdded', $CustRec);
						$Row['gender'] 					= $this->ParseField('Gender', $CustRec);
						$BirthDate 						= $this->ParseField('Birthdate', $CustRec);
						if ( strlen($BirthDate) > 0 )
						{
							$BirthDate 					= date("Y-m-d", strtotime($BirthDate));
						}
						$Row['birthday'] 				= $BirthDate;
						$Row['customer_voice_phone_normal'] 			= $this->ParseField('Telephone', $CustRec);


						$QueryRow[]						= "('" . join("','", $Row) . "')";
						if ( $RowCount % 1000 == 0 )
						{
							$Query 						= $InsertQuery . join(",", $QueryRow) . $UpdateQuery;
							echo "Query = {$Query}\n";
				 			$Rs 						= $DmsConn->executeQuery($Query);
				 			$QueryRow 					= array();

						}
						$RowCount++;

					}
					if ( count($QueryRow) > 0 )
					{
						// Pick up the balance of the records

							$Query 						= $InsertQuery . join(",", $QueryRow) . $UpdateQuery;
							echo "Query = {$Query}\n";
				 			$Rs 						= $DmsConn->executeQuery($Query);
					}

					// $Response = true;
				}
			}
		}

		return $Response;

	}


	private function ParseField($FieldName, $Rec)
	{
		$Result 	= "";
		if ( !is_array($Rec[$FieldName]) && isset($Rec[$FieldName]) )
			$Result = addslashes($Rec[$FieldName]);

		return $Result;

	}

	/*
	 * ProcessNext()
	 * ********************************************************************* */
	public function ProcessNext()
	{
		$FeedHistoryRec 	= false;
		$Query 				= "SELECT * FROM dmsd_feed_history, dmsd_feed "
							. "WHERE dmsd_feed_history.dmsd_feed_id = dmsd_feed.dmsd_feed_id "
							. "ANd dmsd_feed.feed_source_id = 8 "
							. "AND dmsd_feed_history.processing_try_next < now() "
							. "AND complete_yn = 'N' "
							. "AND dmsd_feed_history.processing_yn = 'N' "
							. "ORDER BY priority, dmsd_feed.start_date "
							. "LIMIT 1 ";
						echo "Query = {$Query}\n";
		$Rs 				= $this->ConnDms->executeQuery($Query);
		while($Rs->next())
		{
			$FeedHistoryRec = $Rs->getRow();
		}
		if ( $FeedHistoryRec )
		{
			$CustomerId 	= $FeedHistoryRec['customer_id'];


			echo "Next Record: " . print_r($FeedHistoryRec, true) . "\n";

			// Employees
			$this->GetEmployees($FeedHistoryRec['cdk_dealer_id'], $FeedHistoryRec['customer_id'], $FeedHistoryRec['dmsd_feed_id']);

			// Models
			$this->GetModels($FeedHistoryRec['cdk_dealer_id'], $FeedHistoryRec['customer_id'], $FeedHistoryRec['dmsd_feed_id']);

			// Consumers
			$ConsumerTryNextTime 	= strtotime($FeedHistoryRec['consumer_try_next']);
			if ( $ConsumerTryNextTime < time() )
			{
				$PreDeltaTime = time() - 86400;

				if ( strtotime($FeedHistoryRec['start_date']) < $PreDeltaTime )
				{
					$Mode 	= 'bulk';
					$LastSyncDate = '';
				} else {
					$Mode 	= 'delta';
					$LastSyncDate = $FeedHistoryRec['start_date'];
				}
				$Result = $this->GetCustomers($FeedHistoryRec['cdk_dealer_id'], $FeedHistoryRec['customer_id'], $FeedHistoryRec['dmsd_feed_id'], $Mode, $LastSyncDate);
				if ( $Result )
				{
					// Because the CDK model is either 'bulk' or 'changes since', we should update multiple feed_history records so we don't try to hit them again.
					$Query 		= "UPDATE dmsd_feed_history "
								. "SET consumer_try_next = '2029-12-31 23:59:59' "
								. "WHERE dmsd_feed_id = {$FeedHistoryRec['dmsd_feed_id']} "
								. "AND consumer_try_next < now() ";
						echo "Query = {$Query}\n";
					$Rs 		= $this->ConnDms->executeQuery($Query);					
				}
			}


		}
	}






	/*
	 * BuildHistory()
	 * ********************************************************************* */
	public function BuildHistory()
	{
		// Get the dealers with CDK feeds
		$Query 				= "SELECT * FROM dmsd_feed "
							. "WHERE feed_source_id = 8 "
							. "AND active_yn = 'Y' ";
		$Rs 				= $this->ConnDms->executeQuery($Query);
		while($Rs->next())
		{
			$FeedList[] 	= $Rs->getRow();
		}

		// echo "FeedList = " . print_r($FeedList, true) . "\n";

		foreach($FeedList as $key => $Rec)
		{
			if ( $Rec['feed_type'] == 'FULL' )
			{
				// echo "BuildHistory:: Full\n";
				// Add in the historical feed records
				$CurrentYear 	= date("Y");
				$FirstYear 		= $CurrentYear - 4;
				for($i = $FirstYear; $i < $CurrentYear; $i++)
				{
					$StartDate 	= sprintf("%d-01-01 00:00:00", $i);
					$EndDate 	= sprintf("%d-12-31 23:59:59", $i);
					$this->CheckHistory($Rec['dmsd_feed_id'], $StartDate, $EndDate);
					// echo "StartDate = '{$StartDate}', EndDate='{$EndDate}'\n";
				}
				$StartDate 		= sprintf("%d-01-01 00:00:00", $CurrentYear);
				$EndDate 		= date("Y-m-d 23:59:59", time() - (3 * 86400));	// yesterday
				$this->CheckHistory($Rec['dmsd_feed_id'], $StartDate, $EndDate);
				// echo "StartDate = '{$StartDate}', EndDate='{$EndDate}'\n";
				// Set the feed type to incremental
				$Query 			= "UPDATE dmsd_feed "
								. "SET feed_type = 'INCREMENTAL' "
								. "WHERE dmsd_feed_id = {$Rec['dmsd_feed_id']} "
								. "LIMIT 1 ";
				// 	echo "Query = {$Query}\n";
				$Rs 			= $this->ConnDms->executeUpdate($Query);
			}
			// Find the last date and walk forward
			$MaxDate 			= false;
			$Query 				= "SELECT max(end_date) as max_date "
								. "FROM dmsd_feed_history "
								. "WHERE dmsd_feed_id = {$Rec['dmsd_feed_id']} ";
			$Rs 				= $this->ConnDms->executeQuery($Query);
			while($Rs->next())
			{
				$MaxDate 		= strtotime($Rs->get('max_date')) + 86400;
			}

			$EndDate 		= strtotime(date("Y-m-d 23:59:59", time() - (86400 * 1)));	// can only go up to yesterday.
			while($MaxDate < $EndDate)
			{					
				$StartDate 	= date("Y-m-d 00:00:00", $MaxDate);
				$EndDate 	= date("Y-m-d 23:59:59", $MaxDate);
				$this->CheckHistory($Rec['dmsd_feed_id'], $StartDate, $EndDate);
				$MaxDate 	+= 86400;
			}

		}

	}


	/*
	 * CheckHistory()
	 * ********************************************************************* */
	private function CheckHistory($FeedId, $StartDate, $EndDate)
	{
		// echo "CheckHistory($FeedId, $StartDate, $EndDate)\n";
		$HistRec 			= false;
		$Query 				= "SELECT * FROM dmsd_feed_history "
							. "WHERE dmsd_feed_id = {$FeedId} "
							. "AND start_date = '{$StartDate}' "
							. "AND end_date = '{$EndDate}' ";
				//	echo "Query = {$Query}\n";
		$Rs 				= $this->ConnDms->executeQuery($Query);
		while($Rs->next())
		{
			$HistRec 		= $Rs->getRow();
		}
		if ( !$HistRec )
		{
			$Query 			= "INSERT INTO dmsd_feed_history (`dmsd_feed_id`,`start_date`,`end_date`, `complete_yn`, `processing_try_next`) "
							. "VALUES ({$FeedId}, '{$StartDate}', '{$EndDate}', 'Y', '1980-01-01 00:00:00') ";
				//	echo "Query = {$Query}\n";
			$Rs 			= $this->ConnDms->executeQuery($Query);

		}
	}


	/*
	 * GetSyncRec()
	 * ********************************************************************* */
	private function GetSyncRec($CustomerId=0, $FeedId=0,$Source='EMPLOYEE')
	{


		$NextRec 			= false;

		$Query 				= "SELECT * FROM cdk_extra_sync "
							. "WHERE feed_id = {$FeedId} "
							. "AND source = '{$Source}' ";
						echo "Query = {$Query}\n";
		$Rs 				= $this->ConnDms->executeQuery($Query);
		while($Rs->next())
		{
			$NextRec 		= $Rs->getRow();
			$ExtraRecId 	= $NextRec['cdk_extra_sync_id'];
		}

		if ( !$NextRec )
		{
			// Insert a record
			$Query 			= "INSERT INTO cdk_extra_sync (`customer_id`,`feed_id`,`source`) "
							. "VALUES ({$CustomerId}, {$FeedId}, '{$Source}') ";
						echo "Query = {$Query}\n";
			$Rs 			= $this->ConnDms->executeQuery($Query);

			$Query 				= "SELECT * FROM cdk_extra_sync "
								. "WHERE feed_id = {$FeedId} "
								. "AND source = '{$Source}' ";
						echo "Query = {$Query}\n";
			$Rs 				= $this->ConnDms->executeQuery($Query);
			while($Rs->next())
			{
				$NextRec 		= $Rs->getRow();
				$ExtraRecId 	= $NextRec['cdk_extra_sync_id'];
			}
		}

		echo "GetSyncRec:: NextRec = " . print_r($NextRec, true) . "\n";
		return $NextRec;

	}


	/*
	 * ResetSyncRec()
	 * ********************************************************************* */
	private function ResetSyncRec($FeedId=0, $Source='EMPLOYEE')
	{

		$Query 				= "SELECT * FROM cdk_extra_sync "
							. "WHERE feed_id = {$FeedId} "
							. "AND source = '{$Source}' ";
						echo "Query = {$Query}\n";
		$Rs 				= $this->ConnDms->executeQuery($Query);
		while($Rs->next())
		{
			$NextRec 		= $Rs->getRow();
			$ExtraRecId 	= $NextRec['cdk_extra_sync_id'];
		}

		if ( $NextRec )
		{
			$TryNextDate 	= date("Y-m-d 00:00:00", time() + ($this->CdkSyncDays * 86400));
			// Insert a record
			$Query 			= "UPDATE cdk_extra_sync "
							. "SET last_sync_date = now(), try_next_date='{$TryNextDate}' "
							. "WHERE cdk_extra_sync_id = {$ExtraRecId}";
						echo "Query = {$Query}\n";
			$Rs 			= $this->ConnDms->executeQuery($Query);

		}

	}


	/*
	 * CheckHistory()
	 * ********************************************************************* */
	// borrowed from Midnight APi
	public function CallApi($api='', $args=array()) {
		if (!array_key_exists($api, $this->methods)) {
			return false;
		}

		$url			= $this->baseurl.$api."/extract";
		$method			= $this->methods[$api];
		// $params			= array(
		// 	'payload'		=> json_encode($args)
		// );
		$params 		= $args;

		// echo "class.AmmsCoreDDSApi.php CallApi() <br />url = {$url}<br />method = {$method}<br />";

		$query_string		= !empty($params) ? http_build_query($params,'','&') : "";
		$content_type		= 'application/x-www-form-urlencoded';

		// Do the auth leg
		$ch					= curl_init();

		$UserPass 			= base64_encode($this->User . ":" . $this->Pass);
		echo "base64_encode({$this->User}':'{$this->Pass})\n";
		echo "UserPass = {$UserPass}\n";


		// Now for the actual API request

		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
		curl_setopt($ch, CURLOPT_TIMEOUT, 6000);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		if ($method == "post" || $method == "put") {
			$length				= count($params);
			$query_string		= !empty($params) ? http_build_query($params,'','&') : "";
			$Header 			= array();
			$Header[] 			= 'Content-Type: '.$content_type;
			$Header[] 			= 'Authorization: Basic ' . $UserPass;
			curl_setopt($ch, CURLOPT_HTTPHEADER, $Header);

			curl_setopt($ch, CURLOPT_HEADER, FALSE);
			curl_setopt($ch, CURLOPT_POST, $length);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
			curl_setopt($ch, CURLOPT_URL, $url);
			echo "POST FIELDS: {$query_string}\n";
			echo "URL: $url\n";

		} else {
			if (!empty($params)) {
				$url				= $url . "?".http_build_query($params,'','&');
			} else {
				$url				= $url;
			}

			curl_setopt($ch, CURLOPT_URL, $url);
		}

		if ($method == "put" || $method == "delete") {
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
		}
		echo " final url={$url}\n";

		curl_setopt($ch,CURLOPT_ENCODING , "gzip");
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
		$response = curl_exec($ch);

		// echo "response = " .print_r($response, true) . "\n";

		if ($response === false) {
			$msg		= "Error Number ".curl_errno($ch)." Error Text".curl_error($ch);
			echo "msg = {$msg}\n";
			$response	= json_encode(array("status"=>"error","message"=>"Curl Error -".$msg,"data"=>false));

			curl_close($ch);
			return $response;
		} else {
			curl_close($ch);
			return $response;
		}

	}

}