<?php


$mysqli = new mysqli('localhost', 'sasa_site', 'kqt)?ussCSn}', 'sasa_site');
function curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
    function grab_image($url,$saveto){
      $ch = curl_init ($url);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
      $raw=curl_exec($ch);
      curl_close ($ch);
      if(file_exists($saveto)){
          unlink($saveto);
      }
      $fp = fopen($saveto,'x');
      fwrite($fp, $raw);
      fclose($fp);
    }   

$url = "http://www-1.dmcentralserver.com/api/imagenes";
$productos = json_decode(curl($url));
$coni     = 0;
$encontrados = 0;
foreach ($productos as $producto) {
	$if_exist_product = $mysqli->query("SELECT * FROM sin WHERE sku = '".$producto->sku."'");	
	
	if(mysqli_num_rows($if_exist_product)>0){
		$detalle = mysqli_fetch_assoc($if_exist_product);
		$encontrados++;
		$imagen = (!empty($producto->image) || $producto->image!=NULL)?$producto->image:NULL;
		if ($imagen!=NULL) {
			  $coni++;
              		$foto = "http://www-1.dmcentralserver.com/images/".$producto->sku.".jpg";
					$mysqli->query("UPDATE sin SET hasImage = 1, image ='".$foto."' WHERE id = " . $detalle["id"]);
		}else{
      $mysqli->query("UPDATE sin SET hasImage = 0 WHERE id = " . $detalle["id"]);
    }
	}
}
echo "Encontrados: ".$encontrados;
echo "Con imagen:".$coni;


?>