<?php
set_time_limit(0);
        $link =  mysql_connect('localhost', 'tienda_new', 'Creactivo.1');
        if (!$link)
        {
            die('<div class=\"error\">No pudo conectarse: ' . mysql_error() ."</div>");
        }
        else
        {
            $db_selected = mysql_select_db('tienda_mook', $link);
            if (!$db_selected)
            {
                die ('<div class=\"error\">Can\'t use db : ' . mysql_error() . "</div>");
            }
		}
function getProductId($sku)
{

 $result = mysql_query("select id from price_file where sku = '$sku'"); 
if(mysql_num_rows($result)>0){
 $row = mysql_fetch_row($result);
 return $row[0];
}else{
 return false;
}
}

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);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	// 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($products)
{
		
		$string = '<?xml version="1.0" encoding="ISO-8859-1"?><PNARequest><Version>2.0</Version>';
		$string.= '<TransactionHeader><SenderID>DECOMPRAS COM</SenderID>';
		$string.= '<ReceiverID>INGRAM MICRO</ReceiverID>';
		$string.= '<CountryCode>MX</CountryCode><LoginID>PlAV4gDd13</LoginID><Password>JuAGaRS141212</Password>';
		$string.= '<TransactionID>{A0DEA52B-341F-40C3-9C80-77A4A84F9EB7}</TransactionID></TransactionHeader>';
		for($i=0;$i<sizeof($products);$i++){
			$string .= '<PNAInformation SKU="'.$products[$i]["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 = "PNAResponse10.xml";
		//$doc->save("$pnaResp");

		
		// loocking for errors
		$ErrorStatus = $doc->getElementsByTagName("ErrorStatus");
		$ErrorNumber = $ErrorStatus->item(0)->getAttribute("ErrorNumber");
		if(strlen($ErrorNumber)<=0){
			$productos =  array();
			$TotAvail = 0;
			// No errors
			$PriceAndAvailability = $doc->getElementsByTagName("PriceAndAvailability");
			  foreach( $PriceAndAvailability as $PriceAndAvailability ){
				  
				  
				  $Prices = $PriceAndAvailability->getElementsByTagName("Price");
				  $sku = $PriceAndAvailability->getAttribute("SKU");
				  $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;
				  $id = getProductId($sku);
				 
				  array_push($productos,array("id"=>$id,"sku"=>$sku,"precio"=>$Price,"disponibilidad"=>$TotAvail));
				  unset($id);
				  unset($TotAvail);
				  unset($sku);
			  } //for each
		}
		else{
			mail('oscar@creactivo.mx', 'WEBSERVICES MOOK [Error]', $ErrorStatus->item(0)->nodeValue." - ".date("Y-m-d h:m:s"));
			mail('alara@creactivo.mx', 'WEBSERVICES MOOK [Error]', $ErrorStatus->item(0)->nodeValue." - ".date("Y-m-d h:m:s"));
			die($ErrorStatus->item(0)->nodeValue);
		}
		return $productos;
}			
				
            $result = mysql_query("SELECT id,sku FROM price_file"); 
            if (!$result) {
                die('Invalid query: ' . mysql_error());
            }		
            else
            {
				$productos = array();
				$total_productos = mysql_num_rows($result);
				$numero_de_arreglos = ceil($total_productos/100);
                while ($row = mysql_fetch_assoc($result)) {
					array_push($productos,array("id"=>$row["id"],"sku"=>$row["sku"]));

                }
				$muchos = array_chunk($productos,100);

				$time_start = microtime(true);
				for($j=0;$j<sizeof($muchos);$j++){
					$products_consultados = getIngramPrice($muchos[$j]);
				
					for($k=0;$k<=sizeof($products_consultados);$k++){
									if(!empty($products_consultados[$k]["precio"]) && $products_consultados[$k]["precio"]>0 && !empty($products_consultados[$k]["disponibilidad"]) && $products_consultados[$k]["disponibilidad"]>0)
									{
											mysql_query("UPDATE price_file SET disponibilidad = '".$products_consultados[$k]["disponibilidad"]."', precio = ".$products_consultados[$k]["precio"]." WHERE id = ".$products_consultados[$k]['id']);																																								
									}						
					}
				}
				$time_end = microtime(true);
				$message = "comenzo a las: ".date('h:i:s', $time_start)."<br />";
				$message .= "y termino a las: ".date('h:i:s', $time_end);
				echo $message;				
				mail('oscar@creactivo.mx', 'MOOK [OK]', $message);
				mail('alara@creactivo.mx', 'MOOK [OK]', $message);
}
?>    
