
<?php
function httpsPost($Url, $strRequest)
{
	// Initialisation
	$ch=curl_init();
	// Set parameters
	curl_setopt($ch, CURLOPT_URL, $Url);
	// Return a variable instead of posting it directly
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// Active the POST method
	curl_setopt($ch, CURLOPT_POST, 1) ;
	// Request
	curl_setopt($ch, CURLOPT_POSTFIELDS, $strRequest);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	// execute the connexion
	$result = curl_exec($ch);
	// Close it
	curl_close($ch);
	return $result;
}

function getIngramPrice($sku)
{
		include("pcg.php");
		$string = '<?xml version="1.0" encoding="ISO-8859-1"?><PNARequest><Version>2.0</Version>';
		$string.= '<TransactionHeader><SenderID>'.$PCG_SENDER.'</SenderID>';
		$string.= '<ReceiverID>INGRAM MICRO</ReceiverID>';
		$string.= '<CountryCode>MX</CountryCode><LoginID>'.$PGC_LOGIN.'</LoginID><Password>'.$PCG_PASS.'</Password>';
		$string.= '<TransactionID>{A0DEA52B-341F-40C3-9C80-77A4A84F9EB7}</TransactionID></TransactionHeader>';
		$string.= '<PNAInformation SKU="'.$sku.'" Quantity="1" ReservedInventory="N"/>';
		$string.= '<ShowDetail>0</ShowDetail></PNARequest>';
		$url = 'https://newport.ingrammicro.com/MUSTANG';

		$strRequest = utf8_encode($string);
		$Response = httpsPost($url, $strRequest);
		// validate xml response from pcg
		
		$doc = new DOMDocument();
		$doc->loadXML($Response);
		$pnaResp = "PNAResponse.xml";
		$doc->save("$pnaResp");
		
		// loocking for errors
		$ErrorStatus = $doc->getElementsByTagName("ErrorStatus");
		$ErrorNumber = $ErrorStatus->item(0)->getAttribute("ErrorNumber");
		if(strlen($ErrorNumber)<=0){
			// No errors
			$PriceAndAvailability = $doc->getElementsByTagName( "PriceAndAvailability" );
			  foreach( $PriceAndAvailability as $PriceAndAvailability ){
				  
				  
				  $Prices = $PriceAndAvailability->getElementsByTagName( "Price" );
				  $Price = $Prices->item(0)->nodeValue;
				  $Parts = $PriceAndAvailability->getElementsByTagName( "ManufacturerPartNumber" );
				  
				  $Branchs = $PriceAndAvailability->getElementsByTagName( "Branch" );
				  $Avails = $PriceAndAvailability->getElementsByTagName( "Availability" );
				  
				  for ($i = 0; $i < $Branchs->length; ++$i) {
						$TotAvail += $Avails->item($i)->nodeValue;
				  }
				  				  
				  $Price = str_replace(",",".",$Price);
				  // Agregamos el margen del producto
				  $FinalPrice = $Price;
				  
			  } //for each
		}
		else{
			die($ErrorStatus->item(0)->nodeValue);
		}
		$data = array("precio"=>$Price,"disponibilidad"=>$TotAvail);

		return $data;

}			

$time_start = microtime(true);
$data = getIngramPrice($_GET["sku"]);
$time_end = microtime(true);
echo "start time: ".date('h:i:s:u', $time_start);
echo "<br />";
print_r($data);
echo "<br />";
echo "end time: ".date('h:i:s:u', $time_end);
           ?>    
