<?php

$__g_remapping_p = "unset";
$__g_a_remapping_p = array();

$prods = parse_products("../tmp/prod_conv.txt");
foreach($prods as $product)
{
	$product["CURRENCY"] = $general_info["CURRENCY"];
	makeProduct($product);
}
reset($prods);
if( function_exists( "cb_isValidAllProducts" ) ) {
	list( $err, $aerr ) = cb_isValidAllProducts( $prods );
	if( $err ) {
		$error = $err;
		$aErrors = array_merge( $aerr, $aErrors );
	}
}

foreach($prods as $product)
{
	makeArticle2Group($product);
}

function remap( $product ) {
	global $__g_remapping_p;
	global $__g_a_remapping_p;
	if( $__g_remapping_p === false ) { return $product; }
	if( $__g_remapping_p === "unset" ) {
		if( file_exists( "./remapping_p.conf" ) ) {
			$__g_a_remapping_p = file( "./remapping_p.conf" );
			$__g_remapping_p = true;
		} else {
			$__g_remapping_p = false;
			return $product;
		}
	}
	$a_prod = array();
	foreach( $product as $x ) { $a_prod[] = $x; }
	$new_prod = array();
	$c = 0;
	foreach( $__g_a_remapping_p as $key ) {
		if( trim( $key ) ) {
			$new_prod[ trim( $key ) ] = $a_prod[ $c ];
		}
		$c++;
	}
	return $new_prod;
}

function makeProduct($product,$add=Array())
{
	// TODO: Date umwandeln d.m.y in Y-M-D

	global $fp;
	global $bme_prod_flds;
	global $prod_tpl;
	global $mimeinfo_tpl;
	global $mime_tpl;
	global $features_tpl;
	global $buyer;
	global $general_info;
	$error = 0;
	$str = $prod_tpl;

	reset($bme_prod_flds);
	
	if($general_info["TRANSACTION"]!="T_NEW_CATALOG")
	{
		if(!$product["article_mode"])
			$product["article_mode"]="update";
		$str = str_replace("<ARTICLE>","<ARTICLE mode=\"" . $product["article_mode"] . "\">",$str);
	}
	
	if(!$product["PRICE_AMOUNT_CUST"])
	{
		//$str = str_replace("\t\t\t<ARTICLE_PRICE price_type=\"net_customer\">\n\t\t\t\t<PRICE_AMOUNT>[!--PRICE_AMOUNT_CUST--]</PRICE_AMOUNT>\n\t\t\t\t<PRICE_CURRENCY>[!--PRICE_CURRENCY--]</PRICE_CURRENCY>\n\t\t\t\t<TAX>[!--TAX--]</TAX>\n\t\t\t</ARTICLE_PRICE>\n","",$str);
	}
	
	$ref= "";
	$product[ "TAX" ] = formatNumber( $product[ "TAX" ] );
	while(list($key,$val)=each($bme_prod_flds))
	{
		$rep = true;
		$required = ($val[0]=="#");
		$val = str_replace("#","",$val);
		$tag = "[!--" . $val . "--]";
		//echo $tag . "<br>";
		if($val=="valid_start_date"||$val=="valid_end_date")
		{
			$product[$val] = convertDate($product[$val]);
		}
		if( $val == "buyer_aid_type" ) {
			$rep_baid = "";
			$rep = false;
			if( trim( $product[ $val ] ) ) {
				foreach( explode("|", trim( $product[ $val ] ) ) as $baid_temp ) {
					if( trim( $baid_temp ) ) {
						$xxx = explode( "=", trim( $baid_temp ) );
						if( strlen( trim( $xxx[0] ) )  && strlen( trim( $xxx[1] ) ) ) {
							$rep_baid .= "<BUYER_AID type=\"". trim($xxx[0]) ."\">" . trim($xxx[1]) . "</BUYER_AID>\n";
						}
					}
				}
			}
			$str = preg_replace("#<BUYER_AID.+?</BUYER_AID>#i", $rep_baid, $str );
		}
		if( $val == "SPECIAL_TREATMENT_CLASS" ) {
			$rep_baid = "";
			$rep = false;
			if( trim( $product[ $val ] ) ) {
				foreach( explode("|", trim( $product[ $val ] ) ) as $baid_temp ) {
					if( trim( $baid_temp ) ) {
						$xxx = explode( "=", trim( $baid_temp ) );
						if( strlen( trim( $xxx[0] ) )  && strlen( trim( $xxx[1] ) ) ) {
							$rep_baid .= "<SPECIAL_TREATMENT_CLASS type=\"". trim($xxx[0]) ."\">" . trim($xxx[1]) . "</SPECIAL_TREATMENT_CLASS>\n";
						}
					}
				}
			}
			$str = preg_replace("#<SPECIAL_TREATMENT_CLASS.+?</SPECIAL_TREATMENT_CLASS>#i", $rep_baid, $str );
		}
		if( $val == "ARTICLE_ORDER" ) {
			if( $product[ $val ] ) {
				$str = str_replace("</ARTICLE_DETAILS>","<ARTICLE_ORDER>" . $product[ $val ] . "</ARTICLE_ORDER>\n</ARTICLE_DETAILS>\n", $str );
			}
		}
		if(preg_match("#^ARTICLE_REFERENCE_(.+)#",$val,$match)) {
			$rep = false;
			$_r_types = array(
				"SIMILA"=>"similar",
				"ACCESS"=>"accessories",
				"OTHERS"=>"others",
				"CONSISTSOF" => "consists_of",
				"DIFFORDERUNIT" => "diff_orderunit",
				"FOLLOWUP" => "followup",
				"MANDATORY" => "mandatory",
				"SELECT" => "select",
				"SPAREPART" => "sparepart",
			);
			$r_type = $_r_types[ $match[1] ];
			if( $r_type ) {
				if( trim( $product[ $val ] ) ) {
					foreach( explode( "|", trim( $product[ $val ] ) ) as $ref_val ) {
						$ref.="<ARTICLE_REFERENCE type=\"$r_type\">\n<ART_ID_TO>" . $ref_val . "</ART_ID_TO>\n</ARTICLE_REFERENCE>\n";
					}
				}
			}
		}
		if(!$prices_done && preg_match("#^PRICE_AMOUNT#",$val)) {
			$prices_done = true;
			$rep = false;
			preg_match( "#(<ARTICLE_PRICE price_type=.+?" . ">.+?</ARTICLE_PRICE>)#is", $str, $match );
			$p_tpl = $match[1];
			$p_data = "";
			foreach( array( "PRICE_AMOUNT","PRICE_AMOUNT2","PRICE_AMOUNT3" ) as $fkey ) {
				$price = trim( $product[ $fkey ] );
				$p_num = str_replace( "PRICE_AMOUNT", "", $fkey );
				$p_type = $product["price_type$p_num"];
				if( preg_match( "#\d:\d#", $price ) ) {
					if( strlen( $price ) ) {
						$p_temp = explode( " ", $price );
						foreach( $p_temp as $p_ttemp ) {
							$use_tpl = $p_tpl;
							$use_tpl = str_replace("[!--price_type--]", $p_type, $use_tpl );
							$p_ttemp = explode( ":", $p_ttemp );
							$use_tpl = str_replace("[!--PRICE_AMOUNT--]", formatNumber( $p_ttemp[1] ), $use_tpl);
							$use_tpl = str_replace("[!--PRICE_CURRENCY--]", $product["CURRENCY"], $use_tpl);
							$use_tpl = str_replace("[!--TAX--]", $product["TAX"], $use_tpl);
							$p_lb = "<LOWER_BOUND>" . $p_ttemp[0] . "</LOWER_BOUND>\n";
							$use_tpl = str_replace("</ARTICLE_PRICE>", $p_lb . "</ARTICLE_PRICE>", $use_tpl);
							$p_data .= $use_tpl;
						}
					}
				} else {
					if( strlen( $price ) ) {
						$use_tpl = $p_tpl;
						$use_tpl = str_replace("[!--price_type--]", $p_type, $use_tpl );
						$use_tpl = str_replace("[!--PRICE_AMOUNT--]", formatNumber( $price ), $use_tpl);
						$use_tpl = str_replace("[!--PRICE_CURRENCY--]", $product["CURRENCY"], $use_tpl);
						$use_tpl = str_replace("[!--TAX--]", $product["TAX"], $use_tpl);
						$use_tpl = str_replace("</ARTICLE_PRICE>", $p_lb . "</ARTICLE_PRICE>", $use_tpl);
						$p_data .= $use_tpl;
						unset( $product[ $fkey ] );
					}
				}
			}
			$str = str_replace( $match[0], $p_data . "\n", $str );
		}
		if($rep && $required && strlen($product[$val])<1)
		{
			$error = 1;
			echo "error: missing required tag $val<br>";
		}
		if(!$required && strlen($product[$val])<1)
		{
			if($val=="BUYER_AID") {
				//$str = str_replace("\t\t\t<BUYER_AID type=\"[!--buyer_aid_type--]\">[!--BUYER_AID--]</BUYER_AID>","",$str);
			}
			else
				$str = str_replace("<$val>$tag</$val>","",$str);
			//$str = preg_replace("/<$val.*>$tag</$val>/U","",$str);
		}
		if( $rep ) {
			$str = str_replace($tag,trim($product[$val]),$str);
		}
	}
	$features = "";
	foreach($product["features"] as $feature)
	{
		$fstr = $features_tpl;
		$fstr = str_replace("[!--FNAME--]",$feature[0],$fstr);
		$f_values = array();
		foreach( explode("|", $feature[1]) as $fval ) {
			$f_values[] = trim($fval);
		}
		//$fstr = str_replace("[!--FVALUE--]",$feature[1],$fstr);
		$fstr = str_replace("[!--FVALUE--]",implode( "</FVALUE>\n<FVALUE>", $f_values ),$fstr);
		if(strlen($feature[2])>0)
			$fstr = str_replace("[!--FUNIT--]",$feature[2],$fstr);
		else
			$fstr = str_replace("\t\t\t\t<FUNIT>[!--FUNIT--]</FUNIT>","",$fstr);
		$features .= $fstr; 
	}
	$str = str_replace("[!--FEATURES--]",$features,$str);
	$keywords = "";
	foreach($product["keywords"] as $keyword)
	{
		$keywords .= "\t\t\t<KEYWORD>$keyword</KEYWORD>\n";
	}
	$str = str_replace("[!--KEYWORDS--]",$keywords,$str);
	$mimeinfo = "";
	$mimes = "";
	if($product["image1"]||$product["image2"]||$product["image3"])
	{
		$mimeinfo = $mimeinfo_tpl;
		for($i=1;$i<10;$i++)
		{
			if($product["image$i"])
			{
				$mime = $mime_tpl;
				$mime_type = getMimeType($product["image$i"]);
				$mime = str_replace("[!--MIME_TYPE--]",$mime_type,$mime);
				$mime = str_replace("[!--MIME_SOURCE--]",$product["image$i"],$mime);
				$mime = str_replace("[!--MIME_DESCR--]",$product["image_desc$i"],$mime);
				$mime = str_replace("[!--MIME_PURPOSE--]",$product["image_type$i"],$mime);
				$mime = str_replace("<MIME_DESCR></MIME_DESCR>","",$mime);
				$order = $i;
				if( preg_match("#application#", $mime_type ) && $i == 7 ) {
					$order+=100;
				}
				if( preg_match("#application#", $mime_type ) && $i == 8 ) {
					$order+=1000;
				}
				$mime = str_replace("</MIME>","<MIME_ORDER>$order</MIME_ORDER>\n</MIME>",$mime);
				$mimes.=$mime;
			}
		}
		$mimeinfo = str_replace("[!--MIME--]",$mimes,$mimeinfo);
	}
	$str = str_replace("[!--MIME_INFO--]",$mimeinfo,$str);
	$str = str_replace("[!--PRICE_CURRENCY--]",$product["CURRENCY"],$str);
	$str = preg_replace("'\n\s*\n'","\n",$str);
	if( $product[ "udx" ] ) {
		$udx = array();
		$udx []= "\n<!-- UDX START -->";
		$udx []= "<USER_DEFINED_EXTENSIONS>";
		foreach( $product[ "udx" ] as $uk => $uv ) {
			$temp = explode( "|", $uv );
			foreach( $temp as $udv ) {
				$udx []= "\t" . "<$uk>" . trim( $udv ) . "</$uk>";
			}
		}
		$udx []= "</USER_DEFINED_EXTENSIONS>";
		$udx []= "<!-- UDX END -->\n\n";
		$str = str_replace("</ARTICLE>", implode( "\n", $udx ) . "</ARTICLE>", $str );
	}
	if( $ref ) {
		$str = str_replace("</ARTICLE>", $ref . "</ARTICLE>", $str );
	}
	if(!$error)
		fputs($fp,$str . "\n");
}

function makeArticle2Group($product,$add=Array())
{
	global $fp;
	global $art2group_tpl;
	

	$groups = explode( "|", $product["product_group"] );
	foreach( $groups as $group ) {	
		$str = $art2group_tpl;
		$str = str_replace("[!--ART_ID--]",$product["SUPPLIER_AID"],$str);
		$str = str_replace("[!--CATALOG_GROUP_ID--]",$group,$str);
		fputs($fp,$str . "\n");
	}
}



function parse_products($file)
{
	global $bme_prod_flds;
	global $aErrors;
	global $aAIDs;
	global $groupsys;
	
	unset($ret);
	$c=0;
	$data = file($file);
	foreach($data as $line)
	{
	//	$line = mb_convert_encoding( $line, "UTF-8", "UTF-16" );
		if( strlen( $line ) < 10 ) {
			continue;
		}
		$error = 0;
		$temp = explode("\t",$line);
		unset($prod);
		reset($bme_prod_flds);
		while(list($key,$val)=each($bme_prod_flds))
		{
			$required = ($val[0]=="#");
			$val = str_replace("#","",$val);
			$default = "";
			if(strpos($val,"|"))
			{
				$t = explode("|",$val);
				$val = $t[0];
				$default = $t[1];
			}
			if(strlen(trim($temp[$key]))<1)
			{
				$value = $default;
				if($required)
				{
					$error = 1;
					if(array_sum($temp)!=0)
						$aErrors[] = sprintf("Zeile %04s: Muss-Feld \"$val\" nicht vorhanden",($c+1+3));
				}
			}else
			{
				$value = $temp[$key];
			}
			//$value = preg_replace("#(^\"|\"$)#","",$value);
			$value = fixString($value);
			$prod[$val] = $value;
		}
		//print_r( $prod );
		$prod = remap( $prod );
		//print_r( $prod );
		//exit;
		$prod["product_group"] = $prod["CATALOG_GROUP_ID"];
		$prod["eclassversion"] = $prod["REFERENCE_FEATURE_SYSTEM_NAME"];
		$prod["eclass"] = $prod["REFERENCE_FEATURE_GROUP_ID"];

		$prod[ "udx" ] = array();
		foreach( $prod as $k => $v ) {
			if( preg_match( "#^UDX\..+#", $k ) ) {
				$prod[ "udx" ][ $k ] = $v;
			}
		}

		$prod["features"] = array();
		$key=count($bme_prod_flds)-1;
		$key--;
		while($key<count($temp))
		{
			$key++;
			$fname = fixString($temp[$key]);
			$key++;
			$fvalue = fixString($temp[$key]);
			$key++;
			$funit = fixString($temp[$key]);
			if(strlen($fname))
				$prod["features"][] = array($fname,$fvalue,$funit);
		}


		if($prod["product_group"])
		{
			$groups = explode( "|", $prod["product_group"] );
			foreach( $groups as $group ) {
				if(!isset($groupsys[$group]))
				{
					$error = 1;
					$aErrors[] = sprintf("Zeile %04s: Produktgruppe \"".$group."\" nicht vorhanden",($c+1+3));
				}
			}
		}
		if($prod["SUPPLIER_AID"])
		{
			if($aAIDs[$prod["SUPPLIER_AID"]])
			{
				$error = 1;
				$aErrors[] = sprintf("Zeile %04s: Artikelnummer \"".$prod["SUPPLIER_AID"]."\" bereits verwendet",($c+1+3));
			}
		}
		if( function_exists( "cb_isValidProduct" ) ) {
			list( $err, $aerr ) = cb_isValidProduct( $prod, $c+1+3 );
			if( $err ) {
				$error += $err;
				$aErrors = array_merge( $aerr, $aErrors );
			}
		}
		$prod["keywords"]=array();
		if(strlen($prod["KEYWORD"])>0)
			$prod["keywords"] = explode(",",$prod["KEYWORD"]);
		$aAIDs[$prod["SUPPLIER_AID"]]=1;
		//print_r( $prod );
		if( $error ) print_r( $aErrors );
		if(!$error)
			$ret[] = $prod;
			//$ret[] = $prod;
		$c++;
	}
	return $ret;
}
?>
