<?php
	
	if(file_exists(stream_resolve_include_path("../../global_functions.php")))
	{
		require_once("../../global_functions.php");    
	}
	//require_once("../../global_functions.php");
	//require_once("../../config/connect.php");
	/*
	define('CONSUMER_KEY','ck_590345e45bd3a196082ceae661a000bbc7eeade0');
	define('CONSUMER_SECRET','cs_b70e44d1a9ecd248e23cb434190e1a3e9db4e538');
	define('WEBSHOP_URL','https://www.businessdrucker.at/wp-json/wc/v3/');
	*/
	
	
	function get_WeClapp_undefined_kategorie()
	{
		global $con_i;
		$query="SELECT * FROM categories WHERE NAME='WeClapp_undefined'";
		$Q1=sIT_mysql_run_query($con_i, $query, true);
		if (sIT_mysql_num_rows($Q1)==0)
		{
			echo "Lege Default Weclapp Kategorie an: 'WeClapp_undefined'";
			$sql2="INSERT INTO categories SET NAME='WeClapp_undefined'";
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);
			$weclapp_id=sIT_mysql_insert_id($Q2);
		}
		else
		{
			$row=sIT_mysql_get_row($Q1);
			$weclapp_id=$row['ID'];
		}
		return($weclapp_id);
	}
	
	function transfer_table_WeClapp($table_name, $kassa_id) 
	{
		if ($table_name=='categories')
		{
			$array=transfer_table_WeClapp_categories();
			$array=rename_array_key($array, 'id', 'ID');
			$array=rename_array_key($array, 'name', 'NAME');
			$array=rename_array_key($array, 'parentCategoryId', 'PARENTID');
			
			//var_dump($array);
			update_table_mit_array('categories', $array, 'ID');
		}
		else if ($table_name=='products')
		{
			//$array1=transfer_table_WeClapp_findSalestax();
			$array1['STANDARD']=0.2000;
			$array1['REDUCED']=0.1000;
			$array1['ZERO']=0.0000;
			$array1['SLIGHTLY_REDUCED']=0.1300;
			$array1['SUPER_REDUCED']=0.0500;
			$array=transfer_table_WeClapp_products();
			
			//var_dump($array1);
			
			// Für das Produkt die TAXCAT heraussuchen
			foreach ($array as $key => $value)
			{
				$tax_string=$array[$key]['taxRateType'];
				$Q1=mysql_query("SELECT ID from taxes WHERE RATE='".$array1[$tax_string]."'");
				if (!$Q1)
				{
					echo "Fehler :".mysql_error();
					exit;
				}
				if (mysql_num_rows($Q1)==0)
				{
					echo "Steuersatz ".$array1[$tax_string]." WeClapp $tax_string existiert in sITpos nicht";
					exit;
				}
				$row1=mysql_fetch_assoc($Q1);
				$tax_id=$row1['ID'];
				$array[$key]['taxRate']=$array1[$tax_string];
				$array[$key]['TAXCAT']=$tax_id;
				// In WeClapp muss keine Kategorie gesetzt werden, wenn das nicht ist, dann eine Kategorie mit Namen WeClapp_undefiniert anlegen
				if (!array_key_exists('articleCategoryId',$array[$key]))
				{
					//echo "Keine Kategorie gesetzt";
					if ($default_kategorie=get_WeClapp_undefined_kategorie())
					{
						$array[$key]['articleCategoryId']=$default_kategorie;
					}
				}
				//echo "<br><br><br>";
			}
			//var_dump($array);
			//echo "<br><br><br>";
			//exit;
			$array=rename_array_key($array, 'id', 'ID');
			$array=rename_array_key($array, 'name', 'NAME');
			$array=rename_array_key($array, 'ean', 'CODE');
			$array=rename_array_key($array, 'articleCategoryId', 'CATEGORY');
			//$array=rename_array_key($array, '', 'TAXCAT');
			$array=rename_array_key($array, 'articleNumber', 'REFERENCE');
			$array=rename_array_key_price($array, 'PRICESELL');
			
			update_table_mit_array('products', $array, 'ID');
		}
		else if ($table_name=='taxes')
		{
			$array=transfer_table_WeClapp_steuern();
			$array=rename_array_key($array, 'id', 'ID');
			$array=rename_array_key($array, 'name', 'NAME');
			$array=rename_array_key($array, 'ean', 'CODE');
			$array=rename_array_key($array, 'taxValue', 'RATE');
			foreach ($array as $key => $value)
			{
				if ($array[$key]['taxType']==='VALUE_ADDED_TAX' || $array[$key]['taxType']==='TAX_FREE')
				{
					$array[$key]['RATE']=$array[$key]['RATE']/100;
				}
				else unset($array[$key]);
				
			}			
			update_table_mit_array('taxes', $array, 'ID');
		}
		else if ($table_name=='warehouse')
		{
			
		}
	}
	
	// Alle daten Auslesen - macht pagination
	function transfer_table_WooCommerce_get_data($resource)
	{
		$result_array_gesamt=array();
		list($result_arr, $anzahl_seiten)=transfer_table_WooCommerce_get_data_page($resource, 1);
		$result_array_gesamt=array_merge ($result_array_gesamt, $result_arr);
		$page=2;
		while ($page <= $anzahl_seiten)
		{
			//echo "Seiten: $anzahl_seiten<br>";
			list($result_arr, $anzahl_seiten)=transfer_table_WooCommerce_get_data_page($resource, $page);
			$result_array_gesamt=array_merge($result_array_gesamt, $result_arr);
			$page++;
		}
		return($result_array_gesamt);
	}
	
	function transfer_table_WooCommerce_get_data_page($resource, $page=1)
	{
		$ch = curl_init();
		$url = WEBSHOP_URL;
		//$url=$url.$resource."?pageSize=500&page=".$page;

		$url=$url.$resource."?consumer_key=".WEBSHOP_CONSUMER_KEY."&consumer_secret=".WEBSHOP_CONSUMER_SECRET;
		
		if( $resource == "products/")
			$url=$url."&per_page=500";
		else if ( $resource == "products/categories/")
			$url=$url."&per_page=100";

		echo 'Resource: '.$resource.'<br>';
		echo 'Url: '.$url.'<br>';
		
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
		//curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		//curl_setopt($ch, CURLOPT_POSTFIELDS, $items_string);
		
		//curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		//  "Content-Type: application/json"
		//));

		$response = curl_exec($ch);
		if ($response === false) echo 'Curl-Fehler: ' . curl_error($ch);
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		curl_close($ch);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);

		//echo $header."<br>";
		$pos_pages=strpos($header, "X-WP-TotalPages: ");
		$header_rechts=substr($header, $pos_pages+17);
		$pos_pages=strpos($header_rechts, "\n");
		$pages=substr($header_rechts,0,$pos_pages);
		//echo $pages."<br>";
		//var_dump($response);
		$resArr = json_decode($body, true);
		return(array($resArr, $pages));
	}
	
	function transfer_table_WeClapp_put_data($resource, $items_string)
	{
		$ch = curl_init();
		$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
		$url=$url.$resource;
		//echo $url;
		$token=FILIALSYSTEM_TOKEN;
		
		curl_setopt($ch, CURLOPT_URL, $url);
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);

		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		curl_setopt($ch, CURLOPT_POSTFIELDS, $items_string);
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  "Content-Type: application/json",
		  "AuthenticationToken: $token"
		));

		$response = curl_exec($ch);
		if ($response === false) 
		{
			echo 'Curl-Fehler: ' . curl_error($ch);
			return (false);
		}
		curl_close($ch);
		
		//var_dump($response);
		$resArr = json_decode($response, true);
		return($resArr);
	}
	
	function transfer_table_WeClapp_categories()
	{
		$anzahl_produkte=transfer_table_WeClapp_get_data('articleCategory/count');
		$number_pages=ceil($anzahl_produkte/1000); // ceil=Aufrunden
		$page=1;
		$result_array_gesamt=array();
		while ($page <= $number_pages)
		{
			$result_arr=transfer_table_WeClapp_get_data('articleCategory', $page);
			$result_array_gesamt=array_merge($result_array_gesamt, $result_arr);
			$page++;
		}
		
		return($result_array_gesamt);
	}
	
	function transfer_table_WooCommerce_products()
	{
		$result_array_gesamt=transfer_table_WooCommerce_get_data('products/');
		update_produkte_from_woocommerce($result_array_gesamt);
	}
	
	function existiert_fremdid_produkt_in_sitpos($fremd_id)
	{
		
		global $con_i;
		$sql="SELECT ID, fremd_last_modified from products where fremd_id='".$fremd_id."'";
		
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			$row1=sIT_mysql_get_row($Q1);
			$fremd_last_modified=$row1['fremd_last_modified'];
			return($fremd_last_modified);
		}
		else return(false);		
	}
	
	function getTableTaxeIdAndRATE()
	{
		log_to_file("Abfrage Datenbank 'taxes' und befülle ein Array.");
		
		$result = mysql_query("SELECT ID,RATE from taxes");
		$retValArray=array();
		
		while ($row = mysql_fetch_assoc($result)) {
			
			log_to_file("ID: ".$row['ID']);
			log_to_file("RATE: ".$row['RATE']);
			
			$retValArray+=array($row['RATE'] => $row['ID']);
		}
		
		return $retValArray;
	}
		
	function getTaxcatProductWert($produkt, $taxRateID)
	{
		log_to_file("WooCommerce nach sIT TAXCAT");
		
		// Gibt die SteuerOptionen von WooCommerce return
		$tax_arr=transfer_table_WooCommerce_get_data('taxes/');

		if(empty($produkt['tax_class'])) $produkt['tax_class'] = 'standard';

		log_to_file("tax_class: ".$produkt['tax_class']);
				
		foreach($tax_arr as $tax)
		{
			if ($tax['class'] == $produkt['tax_class'])
			{
				foreach($taxRateID as $key => $wert) {
					
					if ( $key == number_format($tax['rate']/100, 4, '.', '') ){
						log_to_file("return Tax: ".$wert);
						return $wert;
					}
					
				}
			}
		}
		log_to_file("WooCommerce tax_class: ".$produkt['tax_class']." -_> Kein eintrag in der Datenbank ( Table:taxes )");
		echo("<font color=red>WooCommerce tax_class: ".$produkt['tax_class']." --> Kein eintrag in der Datenbank ( Table:taxes )</font><br>");
		return -1;
	}
	/*
	if (!function_exists("log_to_file")) {
		function log_to_file($string, $logfile = false, $tee = false)
		{
			if ($tee) echo $string . PHP_EOL;
	
			if (!$logfile) {
				$logfile = "log/logfile.log";
				if (!file_exists("log")) mkdir("log");
			}
			$zeit = date("Y-m-d H:i:s");
			$myfile = file_put_contents($logfile, $zeit . "\t" . $string . PHP_EOL, FILE_APPEND | LOCK_EX);
		}
	}
	*/
	function getTaxcatProductKey($produkt, $taxRateID)
	{
		log_to_file("Abfrage nach Mwst");
		
		// Gibt die SteuerOptionen von WooCommerce return
		$tax_arr=transfer_table_WooCommerce_get_data('taxes/');

		if(empty($produkt['tax_class'])) $produkt['tax_class'] = 'standard';
		
		log_to_file("tax_class: ".$produkt['tax_class']);
		//echo("tax_class Product: ".$produkt['tax_class'].'<br>');
		
		foreach($tax_arr as $tax)
		{
			//echo("tax_class Taxes: ".$tax['class'].'<br>');
			if ($tax['class'] == $produkt['tax_class'])
			{
				foreach($taxRateID as $key => $wert) {
					
					if ( $key == number_format($tax['rate']/100, 4, '.', '') ){
						log_to_file("return Tax: ".$key);
						//echo("return Tax: ".$key.'<br>');
						return $key;
					}
					
				}
			}
		}
		log_to_file("Abfrage nach Mwst fehlgeschlagen");
		echo("Abfrage nach Mwst fehlgeschlagen<br>");
		return -1;
	}
	
	function getEnableTaxesWooCommerce()
	{
		$retval = false;
		log_to_file("Steuersätze und Berechnungen. WooCommerce --> Einstellungen (Tab Allgemein)");
		
		$settingtax=transfer_table_WooCommerce_get_data('settings/general/woocommerce_calc_taxes/');
		
		log_to_file("woocommerce_calc_taxes/value: ".$settingtax['value']);
		
		if ($settingtax['value'] == 'yes') $retval = true;
		
		return $retval;
		
	}
	
	function getPriceIncludeTaxWooCommerce($price, $taxcat)
	{
		
		log_to_file("Preise mit Steuern eingegeben, befindet sich im 'WooCommerce' --> Einstellungen (Tab Allgemein)");
		
		$settingtax=transfer_table_WooCommerce_get_data('settings/tax/woocommerce_prices_include_tax/');
		
		log_to_file("woocommerce_prices_include_tax/value: ".$settingtax['value']);
		
		//echo 'value: '.$settingtax['value'].'<br>';
		//echo 'price: '.$price.'<br>';
		//echo 'taxcat: '.($taxcat+1).'<br>';
		$netto_einzel = $price;
		if ($settingtax['value'] == 'no') 
		{
			// ? berechne_nettopreis
			list($netto_einzel, $steuer_einzel, $brutto_gesamt, $netto_gesamt, $steuer_gesamt, $db_gesamt)=berechne_bruttopreis($price, $price, $taxcat, 1);
			log_to_file("BruttoPreis: ".$netto_einzel);
			//echo("NettoPreis: ".$netto_einzel);
		}
		else{
			list($netto_einzel, $steuer_einzel, $brutto_gesamt, $netto_gesamt, $steuer_gesamt, $db_gesamt)=berechne_nettopreis($price, $price, $taxcat, 1);
			log_to_file("Netto_Preis: ".$netto_einzel);
			//echo("NettoPreis: ".$netto_einzel);
		}
				
		
		//echo 'Netto: '.$netto_einzel.'<br>';
		return $netto_einzel;
		
	}
	
	function get_options_from_woocommerce_product($produkt)
	{
		$options_array = array();
		if($produkt['attributes'] != null && $produkt['attributes'][0] != null && $produkt['attributes'][0]['options'] != null)
		{
			foreach($produkt['attributes'][0]['options'] as $option)
			{
				$options_array+= $option.';';
				//echo $option.'<br>';
			}
		}
		return $options_array;
	}
	
	function lege_woocommerce_produkt_an($produkt, $fremd_id, $taxRateID)
	{
		$name=$produkt['name'];
		$sku=$produkt['sku'];
		$fremd_last_modified=$produkt['date_modified'];
		$taxcat=getTaxcatProductWert($produkt, $taxRateID);
		$brutto=getPriceIncludeTaxWooCommerce($produkt['price'],getTaxcatProductKey($produkt, $taxRateID));
		
		// Logfile 
		log_to_file("ProduktID: ".$produkt['id']);
		log_to_file("Name: ".$produkt['name']);
		log_to_file("Preis: ".$produkt['price']);
		log_to_file("SKU: ".$produkt['sku']);
		log_to_file("Last Modified: ".$produkt['date_modified']);
		log_to_file("TAXCAT: ".$taxcat);
		
		// Alex: GetProductCategorie
		$categorieID = getCategorieIDFromWooCommerceProduct($produkt);
		
		
		if ( $taxcat != -1 )
		{
			global $con_i;
						
			$sql="INSERT into products SET fremd_id='".$fremd_id."', NAME='".$name."', REFERENCE='".$sku."',ist_beilage = 0 ,
				   PRICESELL='".$brutto."', TAXCAT='".$taxcat."',CATEGORY='".$categorieID."', fremd_last_modified='".$fremd_last_modified."'";
			$Q1=sIT_mysql_run_query($con_i, $sql, true);
			$productid = sIT_mysql_insert_id($con_i);	
			
			
			
			if( isset($produkt['attributes'][0]['options']))
			{
				// TODO options
				//var_dump($produkt['attributes'][0]['options']);
			}
			//var_dump($produkt);
			log_to_file("Produkt: ".$produkt['name']." wurde neu angelegt.");
			echo("Produkt: ".$produkt['name']." wurde neu angelegt.<br>");
		}
		else{
			log_to_file("Neus Produkt konnte nicht angelegt werden.");
			echo("<font color=red>Neus Produkt konnte nicht angelegt werden.</font><br>");
		}
	}
	function update_woocommerce_produkt($produkt, $fremd_id, $taxRateID)
	{
		
		$name=$produkt['name'];
		$sku=$produkt['sku'];
		$fremd_last_modified=$produkt['date_modified'];
		$taxcat=getTaxcatProductWert($produkt, $taxRateID);
		$brutto=getPriceIncludeTaxWooCommerce($produkt['price'],getTaxcatProductKey($produkt, $taxRateID));
		
		// Logfile
		log_to_file("ProduktID: ".$produkt['id']);
		log_to_file("Name: ".$produkt['name']);
		log_to_file("Preis: ".$produkt['price']);
		log_to_file("SKU: ".$produkt['sku']);
		log_to_file("Last Modified: ".$produkt['date_modified']);
		log_to_file("TAXCAT: ".$taxcat);
		
		
		//echo("Preis: ".$produkt['price'].'<br>');
		//echo("Preis: ".$brutto.'<br>');
		
		// Alex: GetProductCategorie
		$categorieID = getCategorieIDFromWooCommerceProduct($produkt);
		
		if ( $taxcat != -1 )
		{
			global $con_i;
			$sql="UPDATE products SET NAME='".$name."', REFERENCE='".$sku."',ist_beilage = 0 ,
				   PRICESELL='".$brutto."', fremd_last_modified='".$fremd_last_modified."', CATEGORY='".$categorieID."', TAXCAT='".$taxcat."' WHERE fremd_id='".$fremd_id."'";
			$Q1=sIT_mysql_run_query($con_i, $sql, true);
			
			
			
			if( isset($produkt['attributes'][0]['options']))
			{
				// TODO options
				//var_dump($produkt['attributes'][0]['options']);
			}
			//var_dump($produkt);
			log_to_file("Produkt: ".$produkt['name']." wurde upgedatet.");
			echo("Produkt: ".$produkt['name']." wurde upgedatet.<br>");
		}
		else{
			log_to_file("Produkt konnte nich upgedatet werden.");
			echo("<font color=red>Produkt konnte nich upgedatet werden.</font><br>");
		}
	}
	function insert_combi_Artikel($produkt, $productid)
	{
		global $con_i;
		
		$combiartikel = $produkt['attributes'][0]['options'];
		foreach($combiartikel as $key => $value)
		{
			$childvon=	get_set_product_for_combi_artikel($value, $productid);
			$sql2 = "INSERT INTO `combiartikel`(`productid`, `childvon`) 
			VALUES ($productid, $childvon )";
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);
		}
	}
	function variation_exsit($fremd_id, $variation_id)
	{
		global $con_i;
		$sql="SELECT ID from webshop_variations where woocommerce_id='".$fremd_id."' AND variation_id='".$variation_id."' ";
		echo("SQL: ". $sql);
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			return true;
		}
		else 
		{
			return false;
			
		}		
		
	}
	function insert_woocommerce_produkt_terms($produkt, $fremd_id, $taxRateID)
	{
		//https://ellies-diner.com/wp-json/wc/v3/products/36/variations?consumer_key=ck_bf50d2991e6555886411ffc2a32d466732fe6ac0&consumer_secret=cs_1e6ba68d67106b3416ba28006b09b0dd93ae1208
		// Logfile

		$variations_array=transfer_table_WooCommerce_get_data('products/'.$produkt['id'].'/variations');

//echo "<pre>";
//	var_dump($variations_array);
//echo "</pre>";
//echo "1<br>";
		if ( isset($variations_array))
		{
			echo "2<br>";
			global $con_i;
			
			foreach($variations_array as $option)
			{
				echo "3<br>";
				/*
				if ( !variation_exsit($fremd_id, $option['id']))
				{
					$sql="INSERT into webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$option['id']."'";
					echo($sql);
					$Q1=sIT_mysql_run_query($con_i, $sql, true);
					echo("Produkt Variation: ".$option['id']." wurde neu angelegt.<br>");
				}
				*/
				$fremd_last_modified=existiert_fremdid_produkt_in_sitpos("woocommerce_term_".$option['id']);
				$name_var = "";
				if( $fremd_last_modified !== false)
				{
					echo "4<br>";
					
					
					foreach ($option['attributes'] as $variation)
					{
						$name_var .= $variation['option']." ";
					}
					echo "----------------------------------------------------><br>";
					echo "*********************** UPDATE **********************<br>";
					echo "Variation Name: ".$name_var."<br>";
					$taxcat=getTaxcatProductWert($option, $taxRateID);
					$brutto=getPriceIncludeTaxWooCommerce($option['price'],getTaxcatProductKey($option, $taxRateID));
					
					$sql="UPDATE products SET ist_beilage = 1 , NAME='".$name_var."', PRICESELL='".$brutto."', fremd_last_modified='".$fremd_last_modified."', TAXCAT='".$taxcat."' WHERE fremd_id='woocommerce_term_".$option['id']."'";
					echo $sql."<br>";
					$Q1=sIT_mysql_run_query($con_i, $sql, true);
					echo "<----------------------------------------------------<br>";
					
				}
				else
				{
					$fremd_last_modified=$option['date_modified'];
					echo "last modified: ".$option['date_modified'];
					foreach ($option['attributes'] as $variation)
					{
						$name_var .= $variation['option']." ";
					}
					echo "----------------------------------------------------><br>";
					echo "*********************** NEW *************************<br>";
					echo "Variation Name: ".$name_var."<br>";
					$taxcat=getTaxcatProductWert($option, $taxRateID);
					$brutto=getPriceIncludeTaxWooCommerce($option['price'],getTaxcatProductKey($option, $taxRateID));
					$sql="INSERT INTO products SET ist_beilage = 1 ,  fremd_id='woocommerce_term_".$option['id']."', NAME='".$name_var."', PRICESELL='".$brutto."', fremd_last_modified='".$fremd_last_modified."', TAXCAT='".$taxcat."'";
					echo $sql."<br>";
					$Q1=sIT_mysql_run_query($con_i, $sql, true);
					echo "<----------------------------------------------------<br>";
					
				}
				
			if ( !variation_exsit($fremd_id, $option['id'], $option))
					{
						$sql="INSERT into webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$option['id']."', variation_name='".$name_var."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option['id']." wurde neu angelegt.<br>");
					}
					else
					{
						$sql="UPDATE webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$option['id']."', variation_name='".$name_var."' WHERE woocommerce_id='".$fremd_id."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option['id']." wurde upgedatet.<br>");
					}
			}
			
		}
		else{
			log_to_file("Keine Produkt Variation.");
			echo("Keine Produkt Variation.<br>");
		}
	}
	function insert_woocommerce_produkt_terms2($produkt, $fremd_id)
	{
		
		// Logfile
		if($produkt['attributes'] != null && $produkt['attributes'][0] != null)
		{
			$i = 0;
			global $con_i;
			foreach($produkt['attributes'][0]['options'] as $option)
			{
				
				if ( isset($produkt['variations'][$i]))
				{
					$variation_id = $produkt['variations'][$i];
					echo ("<br>Variation: ".$variation_id);
					echo ("<br>fremd_id: ".$fremd_id);
					echo ("<br>variation_name: ".$option);
					
					if ( !variation_exsit($fremd_id, $variation_id, $option))
					{
						$sql="INSERT into webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$variation_id."', variation_name='".$option."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option." wurde neu angelegt.<br>");
					}
					else
					{
						$sql="UPDATE webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$variation_id."', variation_name='".$option."' WHERE woocommerce_id='".$fremd_id."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option." wurde upgedatet.<br>");
					}
				}
				$i++;
			}
			if($produkt['attributes'] != null && $produkt['attributes'][1] != null)
		{
			$i = 0;
			global $con_i;
			foreach($produkt['attributes'][1]['options'] as $option)
			{
				
				if ( isset($produkt['variations'][$i]))
				{
					$variation_id = $produkt['variations'][$i];
					echo ("<br>Variation: ".$variation_id);
					echo ("<br>fremd_id: ".$fremd_id);
					echo ("<br>variation_name: ".$option);
					
					if ( !variation_exsit($fremd_id, $variation_id, $option))
					{
						$sql="INSERT into webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$variation_id."', variation_name='".$option."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option." wurde neu angelegt.<br>");
					}
					else
					{
						$sql="UPDATE webshop_variations SET woocommerce_id='".$fremd_id."', variation_id='".$variation_id."', variation_name='".$option."' WHERE woocommerce_id='".$fremd_id."'";
						//echo($sql);
						$Q1=sIT_mysql_run_query($con_i, $sql, true);
						echo("<br>Produkt Variation: ".$option." wurde upgedatet.<br>");
					}
				}
				$i++;
			}
		}
		}
		else{
			log_to_file("Keine Produkt Variation.");
			echo("Keine Produkt Variation.<br>");
		}
	}
	function get_set_product_for_combi_artikel($value, $productid)
	{
		$id =0;
		global $con_i;
		$sql = "SELECT ID FROM products WHERE NAME = '".$value."'";
		$Q1 =  sIT_mysql_run_query($con_i, $sql, true);
		$row = sIT_mysql_get_row($Q1);
		$id = $row['ID'];
		if (sIT_mysql_num_rows($Q1)== 0)
		{
			$sql2="INSERT into products SET ist_beilage= 1, NAME='".$value."'";
			$Q1=sIT_mysql_run_query($con_i, $sql2, true);
			$id = sIT_mysql_insert_id($con_i);
		}
		return $id;
	}
	function update_produkte_from_woocommerce($result_array)
	{
		// Array RATE und ID befüllen
		$taxRateID = getTableTaxeIdAndRATE();
		
		foreach($result_array as $produkt)
		{
			log_to_file("tax_class : ".$produkt['tax_class']);
			//var_dump($produkt);
			$fremd_id="woocommerce_".$produkt['id'];
			log_to_file("WooCommerce_".$produkt['id']);
			$fremd_last_modified=existiert_fremdid_produkt_in_sitpos($fremd_id);
			if ($fremd_last_modified!==false)
			{
				log_to_file("Produkt $fremd_id existiert");
				if ($fremd_last_modified!==$produkt['date_modified'])
				{
					update_woocommerce_produkt($produkt, $fremd_id, $taxRateID);
				}
				else 
				{
					echo "Produkt '".$produkt['name']."' ist aktuell und wurde nicht upgedatet.<br>";
					log_to_file("Produkt '".$produkt['name']."' ist aktuell und wurde nicht upgedatet.");
				}
			}
			else
			{
				log_to_file("Lege Produkt".$fremd_id." in sITpos an.");
				lege_woocommerce_produkt_an($produkt, $fremd_id, $taxRateID);
			}
			
			insert_woocommerce_produkt_terms($produkt,$fremd_id,$taxRateID);
		}
	}
	
	function variation_exsit2($fremd_id, $variation_id, $name)
	{
		global $con_i;
		$sql="SELECT ID from webshop_variations where woocommerce_id='".$fremd_id."' AND variation_id='".$variation_id."' AND variation_name='".$name."'";
		echo("SQL: ". $sql);
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			return true;
		}
		else 
		{
			return false;
			
		}		
		
	}
	function get_All_Categories_From_WooCommerce()
	{
		echo('Start Sync Kategorien.<br>');
		// tabelle categories / fremd_id hinzufügen / parentid auslesen
		$categories_array=transfer_table_WooCommerce_get_data('products/categories/');
		
		foreach($categories_array as $categorie)
		{
			if ( $categorie['count'] > 0 )
			{
				if (!existiert_fremdid_categories_in_sitpos($categorie['id']))insert_categories_in_sITPos($categorie['id'], $categorie['name'], $categorie['parent']);
			}
		}
		echo('Ende Sync Kategorien.');
	}
	function insert_terms_in_categories($fremd_id, $name)
	{	
		global $con_i;

		$sql="SELECT ID FROM categories WHERE name='".$name."'";
		$Q1 = mysqli_query($con_i, $sql);
		$row1=sIT_mysql_get_row($Q1);
		$categorieID = NULL;
		
		if ($row1<=0) {
			$sql2="INSERT into categories SET fremd_id='".$fremd_id."', NAME='".$name."', ist_beilage=1";
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);
			$categorieID = mysqli_insert_id($con_i);

			$sql3="INSERT into categories_sortiment_categories SET categories_sortiment_id=1, geloescht=0, categories_id=".$categorieID;
			$Q3=sIT_mysql_run_query($con_i, $sql3, true);
			if (!$Q3) 
			{	
				echo $sql3."<br>";
				echo "Fehler beim INSERT: ".mysqli_error($con_i);
				exit;
			}
			log_to_file("Kategorie: ".$name." wurde neu angelegt.");
			echo("Kategorie: ".$name." wurde neu angelegt.<br>");
			echo ('Categorie ID: '.$categorieID.'<br>');	
		} else {
			$categorieID = $row1['ID'];
		}

		
		return $categorieID;
		
	}
	function getProductTermsFromWooCommerce()
	{
		log_to_file("Start: getProductTermsFromWooCommerse");
		global $con_i;
		$result_attributes=transfer_table_WooCommerce_get_data('products/attributes/');
		if($result_attributes == NULL)
		{
			echo "Keine Beilagen gefunden.";
			exit;
		}

		foreach ($result_attributes as $attribute)
		{
			$fremd_id = $attribute["id"];
			$name = $attribute["name"];
			
			$categorieID = insert_terms_in_categories($fremd_id,$name);

			$result_terms=transfer_table_WooCommerce_get_data('products/attributes/'.$attribute["id"].'/terms/');
			foreach($result_terms as $term)
			{
				$name = $term['name'];
				$langtext = $term['description'];
				$ist_beilage = 1;
				$sichtbar = 0;
				$fremd_id = "woocommerce_term_".$term['id']; 
				$logtext = "Beilagen Produkt: ".$name." wurde neu angelegt.<br>";
				//$categorieID = get_categorie_for_beilagen();	
				$taxes = 2;
				
				$fremd_last_modified=existiert_fremdid_produkt_in_sitpos($fremd_id);
				echo ("Fremd ID: ".$fremd_last_modified);
				if ($fremd_last_modified !== false)
				{
					$sql="UPDATE products SET geloescht = 0, TAXCAT=".$taxes." ,NAME='".$name."',fremd_id='".$fremd_id."', CATEGORY='".$categorieID."', ist_beilage='".$ist_beilage."', SICHTBAR='".$sichtbar."', langtext='".$langtext."' WHERE fremd_id='".$fremd_id."'";
					$logtext= "Beilagen Produkt: ".$name." wurde upgedatet.<br>";
				}
				else
				{
					$sql="INSERT into products SET geloescht = 0, TAXCAT=".$taxes.", NAME='".$name."',fremd_id='".$fremd_id."', CATEGORY='".$categorieID."', ist_beilage='".$ist_beilage."', SICHTBAR='".$sichtbar."', langtext='".$langtext."'";
				}
				
				log_to_file("SQL Terms WooCommerce: ".$sql);
				$Q1=sIT_mysql_run_query($con_i, $sql, true);
				
				log_to_file($logtext);
				echo($logtext);
			}
		}
		log_to_file("Ende: getProductTermsFromWooCommerse");
	}
	function oldgetProductTermsFromWooCommerse()
	{
		log_to_file("Start: getProductTermsFromWooCommerse");
		global $con_i;
		$result_terms=transfer_table_WooCommerce_get_data('products/attributes/2/terms/');
		foreach($result_terms as $term)
		{
			$name = $term['name'];
			$langtext = $term['description'];
			$ist_beilage = 1;
			$sichtbar = 0;
			$fremd_id = "woocommerce_term_".$term['id']; 
			$logtext = "Beilagen Produkt: ".$name." wurde neu angelegt.<br>";
			$categorieID = get_categorie_for_beilagen();	
			$taxes = 2;
			
			
			$fremd_last_modified=existiert_fremdid_produkt_in_sitpos($fremd_id);
			if ($fremd_last_modified !== false)
			{
				$sql="UPDATE products SET TAXCAT=".$taxes." ,NAME='".$name."',fremd_id='".$fremd_id."', CATEGORY='".$categorieID."', ist_beilage='".$ist_beilage."', SICHTBAR='".$sichtbar."', langtext='".$langtext."' WHERE fremd_id='".$fremd_id."'";
				$logtext= "Beilagen Produkt: ".$name." wurde upgedatet.<br>";
			}
			else
			{
				$sql="INSERT into products SET TAXCAT=".$taxes.", NAME='".$name."',fremd_id='".$fremd_id."', CATEGORY='".$categorieID."', ist_beilage='".$ist_beilage."', SICHTBAR='".$sichtbar."', langtext='".$langtext."'";
			}
			
			log_to_file("SQL Terms WooCommerce: ".$sql);
			$Q1=sIT_mysql_run_query($con_i, $sql, true);
			
			log_to_file($logtext);
			echo($logtext);
		}
		log_to_file("Ende: getProductTermsFromWooCommerse");
	}
	
	function get_categorie_for_beilagen()
	{
		global $con_i;
		$sql="select ID from categories where NAME='WooCommerce'";
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		$row1=sIT_mysql_get_row($Q1);
		
		if (sIT_mysql_num_rows($Q1)<=0) 
		{
			return insert_categories_in_sITPos(NULL, 'WooCommerce', 0);
			
			
		}
				
		return $row1['ID'];
	}
	
	function insert_categories_in_sITPos($fremd_id, $name, $parent)
	{
		
		global $con_i;
		$sql="INSERT into categories SET fremd_id='".$fremd_id."', NAME='".$name."', PARENTID=".$parent;
		//$Q1=sIT_mysql_run_query($con_i, $sql, true);
		

		if (mysqli_query($con_i, $sql)) {
			$last_id = mysqli_insert_id($con_i);
			$sql2="INSERT into categories_sortiment_categories SET categories_sortiment_id=1, geloescht=0, categories_id=".$last_id;
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);
			return $Q2['ID'];
		} else {
			echo "Error: " . $sql . "<br>" . mysqli_error($con_i);
		}
		
		
		
		log_to_file("Kategorie: ".$name." wurde neu angelegt.");
		echo("Kategorie: ".$name." wurde neu angelegt.<br>");
				
	}
	
	function existiert_fremdid_categories_in_sitpos($fremd_id)
	{
		global $con_i;
		$sql="SELECT fremd_id, name, ID from categories where fremd_id='".$fremd_id."'";
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			return true;
		}
		else 
		{
			return false;
			
		}		
	}
	
	function get_Categorie_From_sITpos()
	{
		global $con_i;
		$sql="SELECT ID from categories where fremd_id='".$fremd_id."'";
		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			return true;
		}
		else {
			return false;
			
		}	
	}
	
	function getCategorieIDFromWooCommerceProduct($product)
	{
		// *********************************
		// 	import in prodcuts --> products_warengruppe_id
		
		// tabelle categories / fremd_id hinzufügen / parentid auslesen
	
		$categories = ($product['categories']);
	
	
		
		foreach($categories as $categorie)
		{
			global $con_i;
			$sql="SELECT ID from categories where fremd_id='".$categorie['id']."'";
			$Q1=sIT_mysql_run_query($con_i, $sql, true);
			
			if (sIT_mysql_num_rows($Q1)>0) 
			{
				$row1=sIT_mysql_get_row($Q1);
				foreach ($row1 as $key => $id)
				{
					return $id;
				}
			}
			else {
				return null;
			}
		}

	}
	
	// Aufruf in ajax_funktionen.php
	function getWoocomerceProducts()
	{
		log_to_file("Start: Sync von WooCommerce nach sITpos");
		echo('Start Sync Products.<br>');
		$retval = getEnableTaxesWooCommerce();
		
		if ( $retval ) transfer_table_WooCommerce_products();
		
		if (!$retval) {
			log_to_file("Die Funktion 'Steuersätze und Berechnungen' muss aktiviert sein.");
			echo("<font color=red>Die Funktion 'Steuersätze und Berechnungen' muss aktiviert sein.</font><br>");
			echo("Ende: Sync von WooCommerce nach sITpos<br>");
		}
		log_to_file("Ende: Sync von WooCommerce nach sITpos");
		echo('Ende Sync Products.');
	}
	
	// Aufruf in ajax_funktionen.php
	function getAllOrderWoocommerce()
	{
		
		echo('Start Sync Rechnungen von WooCommerce.<br>');
		
		$orders_array=transfer_table_WooCommerce_get_data('orders/');

		//var_dump($orders_array);
		foreach($orders_array as $order)
		{
			insertIntoWooCommerceAbgeschlossenerBon($order);
			//print "<pre>"; 
			//print_r($order);
			//print "</pre>"; 
			//exit;
		}		
		echo('Ende Sync Rechnungen von WooCommerce.');
		
	}
	function insertIntoWooCommerceAbgeschlossenerBon($order)
	{
		log_to_file("INFO: -->WooCommerce.php Function: insertIntoWooCommerceAbgeschlossenerBon");
		
		global $con_i;
		$bon_id = $order['id'];
		$zusatztext = $order['status']; //pending, processing, on-hold, completed, cancelled, refunded, failed, trash
		$gastro_tisch_id = $order['payment_method_title'];
		$create_ts = $order['date_created'];
		$gesamt_summe = $order['total'];								
		$total_tax = $order['total_tax'];

		log_to_file("bon_id: ".$bon_id);
		log_to_file("zusatztext: ".$zusatztext);
		
		//$sql = "INSERT INTO ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon ( bon_id, zusatztext, gastro_tisch_id, create_ts, gesamt_summe) VALUES ('".$bon_id."', '".$zusatztext."', '".$gastro_tisch_id."', '".$create_ts."', '".$gesamt_summe."')
		//		ON DUPLICATE KEY UPDATE zusatztext='".$zusatztext."', gastro_tisch_id='".$gastro_tisch_id."', create_ts='".$create_ts."', gesamt_summe='".$gesamt_summe."'";		
		
		$sql = "SELECT bon_id FROM ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon WHERE bon_id = ".$bon_id;
		$Q1=sIT_mysql_run_query($con_i, $sql, true);			
		
		
		
		if ( sIT_mysql_num_rows($Q1)==0 )
		{
			$sql2 = "INSERT INTO ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon SET bon_id='".$bon_id."', zusatztext='".$zusatztext."', gastro_tisch_id='".$gastro_tisch_id."', create_ts='".$create_ts."', gesamt_summe='".$gesamt_summe."'";		
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);			
			echo('Bon '.$bon_id.' wurde in der Tabelle "abgeschlossener_bon" importiert.<br>');		
			insertIntoWooCommerceAbgeschlossenerBonProdukte($order);	
		}
		else{
			$sql2 = "UPDATE ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon SET zusatztext='".$zusatztext."', gastro_tisch_id='".$gastro_tisch_id."', create_ts='".$create_ts."', gesamt_summe='".$gesamt_summe."' WHERE bon_id='".$bon_id."'";		
			$Q2=sIT_mysql_run_query($con_i, $sql2, true);			
			echo('Bon '.$bon_id.' wurde in der Tabelle "abgeschlossener_bon" upgedatet.<br>');		
		}
		
	}
	
	function insertIntoWooCommerceAbgeschlossenerBonProdukte($order)
	{
		log_to_file("INFO: -->WooCommerce.php Function: insertIntoWooCommerceAbgeschlossenerBonProdukte");
		global $con_i;	
		
		$product_array = $order['line_items'];
		
		foreach($product_array as $product)
		{
			//tax_class
			$taxRateID = getTableTaxeIdAndRATE();
			$taxRate = getTaxcatProductKey($product, $taxRateID);
			$taxcat = getTaxcatProductWert($product, $taxRateID);
			
			//ID, bon_id, produkt_id, REFERENCE, CODE, NAME, PRINTNAME, PRICEBUY, PRICESELL, CATEGORY, TAXCAT, stueck, tax_rate, kassa_id 
			$sql = "INSERT INTO ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon_produkte SET bon_id='".$order['id']."',tax='".$order['cart_tax']."',tax_rate='".$taxRate."',PRICESELL='".$product['price']."', tax_gesamt='".$product['total_tax']."',TAXCAT='".$taxcat."', produkt_id='".$product['product_id']."', code='".$product['sku']."', name='".$product['name']."', stueck='".$product['quantity']."'";		
			log_to_file("sql:".sql);
			$Q1=sIT_mysql_run_query($con_i, $sql, true);	
			
			echo('Produkt '.$product['name'].' wurde in der Tabelle "abgeschlossener_bon_produkte" importiert.<br>');
		
		}
		steuern_aus_abgeschlossenen_bon_berechnen($order['id']);
		zahlung_aus_abgeschlossenen_bon_berechnen($order['id'], $order['total']);
	}
	function zahlung_aus_abgeschlossenen_bon_berechnen($bon_id, $gesamt_summe)
	{
		log_to_file("INFO: -->WooCommerce.php Function: zahlung_aus_abgeschlossenen_bon_berechnen");
		global $con_i;	
		
		$sql = "INSERT INTO ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon_zahlung SET bon_id='".$bon_id."', Name='WooCommerce', zahlbetrag='".$gesamt_summe."', zahlbetrag_tatsaechlich='".$gesamt_summe."'";
		$Q1=sIT_mysql_run_query($con_i, $sql, true);	
	}
	
	// Funktion schreibt die Steuer einträge
	// in die Tabelle abgeschlossener_bon_steuern
	// Steuern werden aus der Tabelle abgeschlossener_bon_produkte genommen
	function steuern_aus_abgeschlossenen_bon_berechnen($insertedBonId)
	{
		log_to_file("INFO: -->WooCommerce.php Function: steuern_aus_abgeschlossenen_bon_berechnen");
		$sqlS="SELECT SUM(stueck*PRICESELL) as steuer_summe, tax_rate FROM ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon_produkte WHERE bon_id=".$insertedBonId." AND has_childs=0 GROUP by tax_rate";
		//var_dump ($sqlS);
		$QS=mysql_query($sqlS);
		if (!$QS) echo "Fehler :".mysql_error($QS). " ".$sqlS."<br>";		
		
		while ($rowS=mysql_fetch_assoc($QS))
		{
			$tax_rate=$rowS['tax_rate'];
			$steuer_summe=$rowS['steuer_summe'];
			$QIsql="INSERT INTO ".SQL_WOOCOMMERCE_DB.".abgeschlossener_bon_steuern SET bon_id=$insertedBonId, tax_rate=$tax_rate, gesamt_betrag=$steuer_summe";
			$QI=mysql_query($QIsql);
		}
	}
	
	//**********************************************************************************************************
	//********************************** json to WooCommerce ***************************************************
	//**********************************************************************************************************
	
	function exitstWooCommerceIdInProducts($woocommerc_id)
	{
		log_to_file("INFO: -->WooCommerce.php Function: exitstWooCommerceIdInProducts");
		global $con_i;
		$sql="SELECT * from products where fremd_id='".$woocommerc_id."'";
		log_to_file("SQL: ".$sql);
		$Q1=sIT_mysql_run_query($con_i, $sql, true);			
		
		if (sIT_mysql_num_rows($Q1)>0) 
		{
			return true;
		}
		return false;
	}
	
	function instertIntoWebshopDB($transaction_id, $woocommerc_id, $kassenname, $insert_webshop)
	{
		log_to_file("INFO: -->WooCommerce.php Function: instertIntoWebshopDB");
		
		global $con_i;
		
		$sql="INSERT into webshop SET transaction_id='".$transaction_id."', woocommerc_id='".$woocommerc_id."', kassenname='".$kassenname."', insert_webshop=".$insert_webshop;
		$Q1=sIT_mysql_run_query($con_i, $sql, true);			
		log_to_file("SQL: ".$sql);
		//echo('Wurde in die Tabelle "webshop" importiert.<br>');
	}
	
	function updateWebshopDB($transaction_id, $woocommerc_id, $kassenname, $insert_webshop)
	{
		log_to_file("INFO: -->WooCommerce.php Function: updateWebshopDB");
		
		global $con_i;
		if(exitstWooCommerceIdInProducts($woocommerc_id))
		{
			$sql="UPDATE webshop SET transaction_id='".$transaction_id."', woocommerc_id='".$woocommerc_id."', kassenname='".$kassenname."', insert_webshop=".$insert_webshop;
			$Q1=sIT_mysql_run_query($con_i, $sql, true);			
			log_to_file("SQL: ".$sql);
		}
	}
	
	function putdata($product_array, $bon_id, $datenbank, $tisch = "")
	{
		
		log_to_file("INFO: -->WooCommerce.php Function: putdata");
		
		$data['transaction_id'] = $bon_id;
		
		$data['status'] = WEBSHOP_SYNC_ORDERS_STATUS; //pending, processing, on-hold, completed, cancelled, refunded, failed, trash
			
		
		$data['payment_method_title'] = "Bestellung/Bezahlt von der ".$datenbank."<br>";
		$data['line_items'] = null;
		
		$i = 1;
		//$data['customer_note'] =  $tisch. "<br>";
		
		$data['meta_data'][0]['key'] = '_billing_table';
		//$data['meta_data'][0]['value'] =  str_replace("Tisch:","",$tisch)."<br>By: ". $_SESSION["userName"]. "<br>BON ID: ". $bon_id;
		$data['meta_data'][0]['value'] =  str_replace("Tisch:","",$tisch)."<br>by ". $_SESSION["userName"];
		//log_to_file("###################################".$data['meta_data'][0]['value']."###########################################");
		
		$data['meta_data'][1]['key'] = 'fdoe_delivery_mode';
		$data['meta_data'][1]['value'] =  'eathere';
			
		$timestamp = time();
		$datum = date("d/m/Y H:i", $timestamp);
		$data['meta_data'][2]['key'] = 'fdoe_picked_time_localized';
		$data['meta_data'][2]['value'] =  $datum;
		$data['meta_data'][3]['key'] = 'fdoe_picked_time_timestamp';
		$data['meta_data'][3]['value'] =  $timestamp;
		
		// fdoe_picked_time_localized 26/12/2022 15:36
		// fdoe_picked_time_timestamp
		// fdoe_delivery_mode eathere,pickup,delive
		
		if(WEBSHOP_ORDER_SPLITTER_PLUGIN == "ja")
		{
			$data['line_items'][0]['product_id'] = '239';
			$data['line_items'][0]['quantity'] = '1.0000';
		}
		global $con_i;
		foreach($product_array as $product)
		{
			//var_dump($product);
			//echo "Categorie: ". $product[12];
			$getcategoriearray = explode(";",WEBSHOP_CATEGORIES_IGNOR); 
			//log_to_file("<br>+++++++++++++++++++++".$product['beilagen_plus']);
			//log_to_file("<br>---------------------".$product['beilagen_plus']);
			if(count($getcategoriearray) == 0 || in_array($product[12],$getcategoriearray)) 
			{
				
				if( WEBSHOP_ORDER_SPLITTER_PLUGIN == "nein" )
					$data['status'] = WEBSHOP_ORDER_STATUS_MONITOR; 
				
				$beilagen = explode(";",$product[6]);
				
				if ($product[3] < 0)
					$data['customer_note'] = '<span style="color:red;font-weight: bold;">STORNO<br><br>';
				
				log_to_file("beilagen plus count: ".count($beilagen));
				if ( count($beilagen) > 0 )
				{
					
					$sql="SELECT variation_id FROM ".SQL_DB.".webshop_variations 
							WHERE woocommerce_id='".$product[13]."'
							AND variation_name='".$beilagen[0]."'";
							log_to_file('<br>-->'.$sql.'<--<br>');
					$Q1=sIT_mysql_run_query($con_i, $sql, true);
					$j=0;
					log_to_file("j: ".$j);
					if (sIT_mysql_num_rows($Q1)>0) 
					{
						$row1=sIT_mysql_get_row($Q1);
						log_to_file("********************************************");
						log_to_file("varationid: ".$row1['variation_id']);
						$data['line_items'][$i]['variation_id'] = $row1['variation_id'];
						$j=1;
					}
					log_to_file("j: ".$j);
					
					
					$customernote_zähler = $j;
						
					for($j;$j<count($beilagen);$j++)
					{
						
						//log_to_file("j: ".$j);
						//log_to_file("note: ".$beilagen[$j]);
						$plus = trim($beilagen[$j]," ");
						//log_to_file("plus: -->".$plus."<---");
						if (isset($plus) && !is_null($plus) && $plus != '')
						{
							if ($customernote_zähler == $j )
							{
								//echo "####################".$product[2]."***********************";
								$data['customer_note'] .= "<b>".$product[2]."</b><br>";
							}
							
							//$data['customer_note'] .= "+ ".utf8_encode(trim($beilagen[$j]))."<br>";
							//echo $beilagen[$j];
							$data['customer_note'] .= "+ <span style='color:green;'>".trim($beilagen[$j])."</span><br>";
							log_to_file("********************************************");
							log_to_file("beilagen: ".$data['customer_note']);
						}
						
						
						
					}
				}
				$beilagen_minus = explode(";",$product[5]);
				//log_to_file("beilagen minus count: ".count($beilagen_minus));
				if ( count($beilagen_minus) > 0 )
				{
					
					
					for($j=0;$j<count($beilagen_minus);$j++)
					{
						//log_to_file("note: ".$beilagen_minus[$j]);
						$minus = trim($beilagen_minus[$j]," ");
						//log_to_file("minus: ".$minus);
						if (isset($minus) && !is_null($minus) && $minus != '')
						{
								if ($j==0)
								{
									$data['customer_note'] .= "<b>".$product[2]."</b><br>";
								}
								//$data['customer_note'] .= "- ".utf8_encode(trim($beilagen_minus[$j]))."<br>";
								//$data['customer_note'] .= "- ".trim($beilagen_minus[$j])."<br>";
								$data['customer_note'] .= "- <span style='color:red;'>".trim($beilagen_minus[$j])."</span><br>";
								
							log_to_file("customer note: ".$data['customer_note']);
						}
						
					}
				}
				//log_to_file("customer note: ".$data['customer_note']);
				$data['line_items'][$i]['product_id'] = trim($product[13],'woocommerce_');
				$data['line_items'][$i]['quantity'] = $product[3];
				
				log_to_file("********************************************");
				log_to_file("produktid: ".trim($product[13],'woocommerce_'));
				$i++;
			}
			
		}
		
		/*
		log_to_file("Beilagen Plus ID: ".$product['beilagen_plus']);
		log_to_file("WooCommerce ID: ".$product['fremd_id']);
		log_to_file("Stück: ".$product['stueck']);
		*/
		
		$items_string=json_encode($data);
		 
		// zum Testen
		/*
		$handle = fopen ("woocommerce.txt", "w");
		fwrite ($handle, $items_string);
		fclose ($handle);
		*/

		//var_dump($items_string);

		//$QIsql="SELECT distinct woo_order_id from offener_bon SET woo_order_id=$retID where bon_id=".$bon_id;
		//$QI=mysql_query($QIsql);
		//$result = false;
		
		//if (sIT_mysql_num_rows($Q1)==0)
		$result=transfer_table_woocommerce_put_data("orders/", $items_string);

		//$mail = konfiguration_anzeigen("WEBSHOP_ERROR_MAIL");
		$result_string=json_encode($result);
		log_to_file("result: ".$result_string);
		if ($result!=false)
		{
			
			// Technisch hat es funktioniert, jetzt könnte es noch einen logischen Fehler geben
			//$result_string=json_encode($result);
			$retVal = json_decode($result_string, TRUE);
			//sendEmail(false, WEBSHOP_ERROR_MAIL, "Rechnung seppis wurde erstellt", $result_string);
			$retID = -1;
			if (isset($retVal['id']) && $retVal['id'] > 0)
			{

				$retID = $retVal['id'];
				
				$QIsql="UPDATE offener_bon SET woo_order_id=$retID where bon_id=".$bon_id;
				$QI=mysql_query($QIsql);
				
				//$datastatus['id']=$retID;
				//$datastatus['status']='processing';
				if( WEBSHOP_ORDER_SPLITTER_PLUGIN == "ja" )
				{
					$datastatus['status']=WEBSHOP_ORDER_STATUS_MONITOR;
					
					//$datastatus['meta_data'][0]['key'] = '_billing_table';
					//$datastatus['meta_data'][0]['value'] =  $tisch;
					
					$setdatastatus=json_encode($datastatus);
					log_to_file("setdatastatus: ".$setdatastatus);
					
					
					transfer_table_woocommerce_put_data("orders/".$retID, $setdatastatus);
				}
				/*
				Für eingenständige Order Notes

				$datanote['id'] = $retID;
				
				$datanote['customer_note'] = "Produkt: ".$product['printname']."\nPlus: ".$product['beilagen_plus']."\nMinus: ".$product['beilagen_minus'];
				//$datanote['note'] = "Produkt: ".$product['printname']."\nPlus: ".$product['beilagen_plus']."\nMinus: ".$product['beilagen_minus'];
				//$datanote['customer_note'] = false;
				log_to_file(" note: ".$datanote['note']);
				log_to_file(" datanote: ".$datanote);
				$setnote=json_encode($datanote);
				log_to_file(" setnote: ".$setnote);
				//$result=transfer_table_woocommerce_put_data("orders/".$retID, $setnote);
				
				$result_string=json_encode($result);
				log_to_file("result: ".$result_string);
				

				if ($result!=false)
				{
					if (isset($retVal['id']) && $retVal['id'] > 0)
					{
						// kein Error
					}
				}
				*/
				
			}
			else
			{
				
				
				//require_once("../../global_functions.php");
				$text = "Keine Daten vom WooCommerce: ".$result_string;
				//sendEmail(false, WEBSHOP_ERROR_MAIL, "WooCommerce Schnittstelle Error Return ID", $text);
				
				//sendEmail(false, $mail , "WooCommerce Schnittstelle Error Return ID", false, $result_string);
			}
			
		}
		else
		{	
				//$datastatus['status']='processing';
				//$setdatastatus=json_encode($datastatus);
				//log_to_file("setdatastatus: ".$setdatastatus);
				//log_to_file("update orderid: ".$retID);
				//transfer_table_woocommerce_put_data("orders/".$retID, $setdatastatus);	
			//require_once("../../global_functions.php");
			$text = "Keine Daten vom WooCommerce: ".$result_string;
			//sendEmail(false, WEBSHOP_ERROR_MAIL, "WooCommerce Schnittstelle Error", $text);
			
		}
		return $retID;
		
	}
	
	function transfer_table_woocommerce_put_data($resource, $items_string)
	{
		log_to_file("INFO: -->WooCommerce.php Function: transfer_table_woocommerce_put_data");
		log_to_file($items_string);
		$ch = curl_init();
		$url = WEBSHOP_URL;
		//$url=$url.$resource."?pageSize=1000&page=".$page;
		$url=$url.$resource."?consumer_key=".WEBSHOP_CONSUMER_KEY."&consumer_secret=".WEBSHOP_CONSUMER_SECRET;
		log_to_file($url);
		curl_setopt($ch, CURLOPT_URL, $url);
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		curl_setopt($ch, CURLOPT_POSTFIELDS, $items_string);
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  "Content-Type: application/json"
		));

		$response = curl_exec($ch);
		log_to_file($response);
		if ($response === false) 
		{
			log_to_file('Curl-Fehler: ' . curl_error($ch).'<br>');
			echo 'Curl-Fehler: ' . curl_error($ch).'<br>';
			return (false);
		}
		curl_close($ch);
		
		//var_dump($response);
		$resArr = json_decode($response, true);
		return($resArr);
	}
	function storno_bon($resource)
	{
		log_to_file("---> Storno");
		log_to_file("Resource: ".$resource);
		$data['status'] = 'cancelled';
		$items_string=json_encode($data);
		$result = transfer_table_woocommerce_put_data($resource, $items_string);
		$result_string=json_encode($result);
		log_to_file("Result: ".$result_string);
		if ($result!=false)
		{
			// Technisch hat es funktioniert, jetzt könnte es noch einen logischen Fehler geben
			//$result_string=json_encode($result);
			$retVal = json_decode($result_string, TRUE);
			$retID = -1;
			if (isset($retVal['id']) && $retVal['id'] > 0)
			{
				$retID = $retVal['id'];
			}
			else
			{
				//require_once("../../global_functions.php");
				$text = "Keine Daten vom WooCommerce: ".$result_string;
				//sendEmail(false, WEBSHOP_ERROR_MAIL, "WooCommerce Schnittstelle Error Return ID", $text);
				//sendEmail(false, $mail , "WooCommerce Schnittstelle Error Return ID", false, $result_string);
			}
			log_to_file("Storno Ende <---");
			return $retID;
			
		}
		else
		{		
			//require_once("../../global_functions.php");
			$text = "Keine Daten vom WooCommerce: ".$result_string;
			//sendEmail(false, WEBSHOP_ERROR_MAIL, "WooCommerce Schnittstelle Error", $text);
			return -1;
		}
	}
	function woocommerce_sync_db_offenen_bon2($supllyPrinter, $tisch)
	{
		log_to_file("woocommerce_sync_db_offenen_bon");
		//echo "woocommerce_sync_db_offenen_bon<br>";
		
		
			$sql = "SELECT articlePrinted, stueck FROM offener_bon WHERE bon_id='" . $bon_id . "'";
			//echo $sql."<br>";
			$sql_q = mysql_query($sql);
			$sql_arr = mysql_fetch_array($sql_q);
			$articlePrinted = $sql_arr['articlePrinted'];
			$stueck = $sql_arr['stueck'];
			//echo "stueck: ".$stueck."<br>";
			//echo "printed: ".$articlePrinted."<br>";
			$article_to_print = $stueck - $articlePrinted;
/*
			$sql = "SELECT offener_bon.bon_id, offener_bon.produkt_id, offener_bon.REFERENCE, offener_bon.CODE, 
					offener_bon.NAME, offener_bon.PRICEBUY, offener_bon.PRICESELL, offener_bon.CATEGORY, offener_bon.TAXCAT, 
					offener_bon.IMAGE, offener_bon.DISPLAY, offener_bon.VARPRICE, offener_bon.printname, offener_bon.NEGATIVEPRICE, 
					offener_bon.PRODUKTORDER, offener_bon.SICHTBAR, offener_bon.supplyprint, offener_bon.articlePrinted, offener_bon.stueck, 
					offener_bon.tax_rate, offener_bon.aus_ls_nr, offener_bon.article_art_id, offener_bon.beilagen_aenderung_minus, 
					offener_bon.beilagen_aenderung_plus, offener_bon.beilagen_prod_orig_preis, offener_bon.beilagen_sum_netto, 
					offener_bon.beilagen_sum_brutto, offener_bon.benutzer_id, offener_bon.kunden_id, offener_bon.parent_id, 
					offener_bon.has_childs, offener_bon.has_parent, offener_bon.childPrint, offener_bon.abholschein_nr, '1' , products.fremd_id, tische.tischname as tischname
					FROM offener_bon  
					left join products on offener_bon.produkt_id = products.id 
					left join tische on offener_bon.id = tische.id 
					WHERE bon_id='" . $bon_id . "'";
					*/
					//echo "article_to_print: ".$article_to_print."<br>";
			if ($article_to_print != 0 )
			{
				/*
					$sql = "SELECT products.ID as ID,offener_bon.bon_id as bon_id, offener_bon.produkt_id as produkt_id, offener_bon.REFERENCE as REFERENCE, offener_bon.CODE as CODE, 
					offener_bon.NAME as NAME, offener_bon.PRICEBUY as PRICEBUY, offener_bon.PRICESELL as PRICESELL, offener_bon.CATEGORY as CATEGORY, offener_bon.TAXCAT as TAXCAT, 
					offener_bon.IMAGE as IMAGE, offener_bon.DISPLAY as DISPLAY, offener_bon.VARPRICE as VARPRICE, offener_bon.printname as printname, offener_bon.NEGATIVEPRICE, 
					offener_bon.PRODUKTORDER as PRODUKTORDER, offener_bon.SICHTBAR as SICHTBAR, offener_bon.supplyprint as supplyprint, offener_bon.articlePrinted as articlePrinted, ".$article_to_print." as stueck, 
					offener_bon.tax_rate as tax_rate, offener_bon.aus_ls_nr, offener_bon.article_art_id, offener_bon.beilagen_aenderung_minus as beilagen_minus, 
					offener_bon.beilagen_aenderung_plus as beilagen_plus, offener_bon.beilagen_prod_orig_preis, offener_bon.beilagen_sum_netto, 
					offener_bon.beilagen_sum_brutto, offener_bon.benutzer_id, offener_bon.kunden_id, offener_bon.parent_id as parent_id, 
					offener_bon.has_childs, offener_bon.has_parent, offener_bon.childPrint, offener_bon.abholschein_nr, '1' , products.fremd_id as fremd_id
					FROM offener_bon  
					left join products on offener_bon.produkt_id = products.id 
					left join tische on offener_bon.id = tische.id 
					WHERE bon_id='" . $bon_id . "'";
					*/
					$sql = " SELECT products.ID as ID,
						".$article_to_print." as stueck,
						offener_bon.beilagen_aenderung_plus as beilagen_plus,
						offener_bon.beilagen_aenderung_minus as beilagen_minus,
						offener_bon.CATEGORY as CATEGORY,
						offener_bon.printname as printname ,
						products.fremd_id as fremd_id
					FROM offener_bon  
					left join products on offener_bon.produkt_id = products.id 
					left join tische on offener_bon.id = tische.id 
					WHERE bon_id='" . $bon_id . "'";
					
				//echo $sql;
				//mysql_query($sql);
				log_to_file($sql);
				//echo $sql."<br>";#
				global $con_i;
				//$Q1=sIT_mysql_run_query($con_i, $sql, true);	
				$Q1 = mysql_query($sql);
				
				//while ($row = mysql_fetch_assoc($Q1)) {
					//woocommerce_sync_bon("sitpos", $row, $row['bon_id'],  $row['tischname']);
					
					woocommerce_sync_bon("sitpos", $Q1, $bon_id, $tisch);
				//}
			
			}
		
		log_to_file("ENDE woocommerce_sync_db_offenen_bon");
	}
	function woocommerce_sync_db_offenen_bon_deleteorder()
	{
		
		log_to_file ("woocommerce_sync_db_offenen_bon_deleteorder");
		
		if (isset($_REQUEST['bon_id']))
		{
			$bon_id = $_REQUEST['bon_id'];
			$sql = " SELECT DISTINCT woo_order_id
					FROM offener_bon  
					WHERE bon_id='" . $bon_id . "'";
			
				global $con_i;
				
				$Q1 = mysql_query($sql);
				$row = mysql_fetch_assoc($Q1);
				
					
			storno_bon("orders/".$row['woo_order_id']."/");
		}
		else
		{
			log_to_file("Keine bon_id gesetzt");
		}
		log_to_file ("ENDE woocommerce_sync_db_offenen_bon_deleteorder");
	}
	
	function woocommerce_sync_db_offenen_bon_delete_order_neue_rechnung()
	{
		
		log_to_file ("woocommerce_sync_db_offenen_bon_deleteorder");
		
		if (isset($_REQUEST['bon_id']))
		{
			$bon_id = $_REQUEST['bon_id'];
			$sql = " SELECT DISTINCT woo_order_id
					FROM offener_bon  
					WHERE bon_id='" . $bon_id . "'";
			
				global $con_i;
				
				$Q1 = mysql_query($sql);
				$row = mysql_fetch_assoc($Q1);
				
					
			storno_bon("orders/".$row['woo_order_id']."/");
		}
		else
		{
			log_to_file("Keine bon_id gesetzt");
		}
		log_to_file ("ENDE woocommerce_sync_db_offenen_bon_deleteorder");
	}
	
	function woocommerce_sync_db_delete_offener_bon($bon_id)
	{
		
		log_to_file ("woocommerce_sync_db_delete_offener_bon");
		
		$checkSupllyPrint = mysql_query("SELECT offener_bon.ID, produkt_id, offener_bon.name as name, offener_bon.printname as printname, articlePrinted, offener_bon.supplyprint as supplyprint, beilagen_aenderung_minus, beilagen_aenderung_plus, article_art_id, funktion, artikel_art.bezeichnung AS artikelArtBezeichnung, reihung, offener_bon.PRICESELL as PRICESELL, offener_bon.tax_rate as tax_rate, offener_bon.category as category, has_parent, products.fremd_id as fremd_id 
															FROM offener_bon 			
															LEFT JOIN drucker ON supplyprint = drucker_id
															LEFT JOIN artikel_art ON article_art_id = artikel_art.id
															LEFT JOIN products ON products.id = offener_bon.produkt_id
															WHERE offener_bon.bon_id=" . $bon_id . " ");
														
	
		
			$supllyPrinter_woocommerce = array();
			$currentTable = "";
			while ($rowPr = mysql_fetch_array($checkSupllyPrint)) {
				if ($rowPr['articlePrinted'] > 0) {
					if (strtolower(BONZEILE_LOESCHEN_ON_PRINTED) == 'ja' || $_SESSION['userLevel'] < ENABLERKEY_BONZEILE_LOESCHEN) {
						echo "Fehlende Berechtigung, Bonzeile Löschen für gedruckte Artikel";
						return false;
					}
					$tId = $_SESSION['gastroTisch'];
					$tischN = mysql_fetch_assoc(mysql_query("SELECT tischName FROM tische WHERE id = " . $tId . " "));
				
					$currentTable = $_SESSION['gastroTisch'];
					$printerId = $rowPr['supplyprint'];
					$qtyToPrint = 0 - $rowPr['articlePrinted'];
					$userName = $_SESSION['userName'];
					$price = false;
					$price = ($rowPr['PRICESELL'] * (1 + $rowPr['tax_rate'])) * $qtyToPrint;
					//$qtyToPrint = $qtyToPrint * -1;
						
					
					array_push($supllyPrinter_woocommerce, array(
							$rowPr['produkt_id'], $rowPr['name'], $rowPr['printname'], $qtyToPrint , $rowPr['ID'],
							$rowPr['beilagen_aenderung_minus'], $rowPr['beilagen_aenderung_plus'], $rowPr['article_art_id'],
							$rowPr['artikelArtBezeichnung'], $price, $rowPr['ID'],  $rowPr['has_parent'], 
							$rowPr['category'], $rowPr['fremd_id']
						));
					//var_dump($supllyPrinter_woocommerce);
				
					woocommerce_sync_bon("sitpos", $supllyPrinter_woocommerce, $bon_id, $currentTable);
				}
			}		
		
		log_to_file ("ENDE woocommerce_sync_db_delete_offener_bon");
	}
	
	function woocommerce_sync_db_offenen_bon_delete_order($bon_id)
	{
		
		log_to_file ("woocommerce_sync_db_offenen_bon_deleteorder");
		
		
		
			$sql = " SELECT DISTINCT woo_order_id
					FROM offener_bon  
					WHERE bon_id='" . $bon_id . "'";
			
				global $con_i;
				
				$Q1 = mysql_query($sql);
				$row = mysql_fetch_assoc($Q1);
				
					log_to_file("**********************************");
					log_to_file($row['woo_order_id']);
					log_to_file("**********************************");
			storno_bon("orders/".$row['woo_order_id']."/");
		
		log_to_file ("ENDE woocommerce_sync_db_offenen_bon_deleteorder");
	}
	
	function woocommerce_sync_db_offenen_bon_delete_product($supllyPrinter,$currentTable,$cT)
	{
		//echo "woocommerce_sync_db_offenen_bon";
		//$supllyPrinter = $_REQUEST['suppllyPrinter'];
		//var_dump($supllyPrinter);
		//$tisch = $_REQUEST['currentTable'];
		$tisch = $currentTable;
		//$bon_id = $_REQUEST['cT'];
		$bon_id = $cT;
		log_to_file("woocommerce_sync_db_offenen_bon");
		//echo "woocommerce_sync_db_offenen_bon<br>";
		
		woocommerce_sync_bon("sitpos", $supllyPrinter, $bon_id, $tisch);
		
		log_to_file("ENDE woocommerce_sync_db_offenen_bon");
	}
	function woocommerce_sync_db_offenen_bon_delete_product_ajax()
	{
		//echo "woocommerce_sync_db_offenen_bon_delete_product_ajax";
		$supllyPrinter = $_REQUEST['suppllyPrinter'];
		//var_dump($supllyPrinter);
		$tisch = $_REQUEST['currentTable'];
		$bon_id = $_REQUEST['id'];
		
		log_to_file("woocommerce_sync_db_offenen_bon");
		//echo "woocommerce_sync_db_offenen_bon<br>";
		
		woocommerce_sync_bon("sitpos", $supllyPrinter, $bon_id, $tisch);
		
		log_to_file("ENDE woocommerce_sync_db_offenen_bon_delete_product_ajax");
	}
	function woocommerce_sync_db_offenen_bon($supllyPrinter,$currentTable,$cT)
	{
		//echo "woocommerce_sync_db_offenen_bon";
		//$supllyPrinter = $_REQUEST['suppllyPrinter'];
		//var_dump($supllyPrinter);
		//$tisch = $_REQUEST['currentTable'];
		$tisch = $currentTable;
		//$bon_id = $_REQUEST['cT'];
		$bon_id = $cT;
		log_to_file("woocommerce_sync_db_offenen_bon");
		//echo "woocommerce_sync_db_offenen_bon<br>";
		
		woocommerce_sync_bon("sitpos", $supllyPrinter, $bon_id, $tisch);
		
		log_to_file("ENDE woocommerce_sync_db_offenen_bon");
	}
	function woocommerce_sync_db_offenen_bon_ajax()
	{
		//echo "woocommerce_sync_db_offenen_bon";
		$supllyPrinter = $_REQUEST['suppllyPrinter'];
		//var_dump($supllyPrinter);
		$tisch = $_REQUEST['currentTable'];
		$bon_id = $_REQUEST['cT'];
		
		log_to_file("woocommerce_sync_db_offenen_bon");
		//echo "woocommerce_sync_db_offenen_bon<br>";
		
		woocommerce_sync_bon("sitpos", $supllyPrinter, $bon_id, $tisch);
		
		log_to_file("ENDE woocommerce_sync_db_offenen_bon");
	}
	function woocommerce_sync_db_abgeschlossener_bon($datenbank, $bon_id=null)
	{
		
		global $con_i;
		//echo('<details><summary>Datenbankname: '.$datenbank.'</summary><p>');
		log_to_file("INFO: -->WooCommerce.php Function: woocommerce_sync_db_abgeschlossener_bon");
		
		if (!is_null($bon_id) && isset($bon_id))
		{
			log_to_file("INFO: -->STORNO BON_ID: ".$bon_id);
			$sql = "SELECT 
					".SQL_DB."_".$datenbank.".abgeschlossener_bon.bon_id as bon_id, ".SQL_DB."_".$datenbank.".abgeschlossener_bon.storno as storno, ".SQL_DB.".webshop.transaction_id as transaction_id
				FROM 
					".SQL_DB."_".$datenbank.".abgeschlossener_bon
				LEFT JOIN 
					".SQL_DB.".webshop
				ON
					".SQL_DB."_".$datenbank.".abgeschlossener_bon.bon_id = cast(trim(replace(".SQL_DB.".webshop.woocommerc_id,'woocommerce_','')) as double)
				WHERE 
				".SQL_DB."_".$datenbank.".abgeschlossener_bon.bon_id = ".$bon_id;
			/*
			".SQL_DB."_".$datenbank.".abgeschlossener_bon.storno = 0 
				&& (
					".SQL_DB.".webshop.transaction_id is null
				OR	
					".SQL_DB.".webshop.transaction_id = '')";

			*/
			//echo($sql);
			log_to_file("Storno SQL Bon: -->".$sql);
			$Q1=sIT_mysql_run_query($con_i, $sql, true);	


			foreach($Q1 as $bon)
			{
				storno_bon("orders/".$bon['transaction_id']."/");
			}		
		}
		$sql = "SELECT 
					".SQL_DB."_".$datenbank.".tische.tischName as tischname, ".SQL_DB."_".$datenbank.".abgeschlossener_bon.bon_id as bon_id, ".SQL_DB."_".$datenbank.".abgeschlossener_bon.storno as storno, ".SQL_DB.".webshop.transaction_id as transaction_id
				FROM 
					".SQL_DB."_".$datenbank.".abgeschlossener_bon
				LEFT JOIN 
					".SQL_DB.".webshop
				ON
					".SQL_DB."_".$datenbank.".abgeschlossener_bon.bon_id = cast(trim(replace(".SQL_DB.".webshop.woocommerc_id,'woocommerce_','')) as double)
				LEFT JOIN 
					".SQL_DB."_".$datenbank.".tische 
				ON 
					".SQL_DB."_".$datenbank.".tische.id = ".SQL_DB."_".$datenbank.".abgeschlossener_bon.gastro_tisch_id
				
				WHERE 
				".SQL_DB."_".$datenbank.".abgeschlossener_bon.storno = 0 
				&& (
					".SQL_DB.".webshop.transaction_id is null
                OR	
                	".SQL_DB.".webshop.transaction_id = '')";
		/*
		".SQL_DB."_".$datenbank.".abgeschlossener_bon.storno = 0 
				&& (
					".SQL_DB.".webshop.transaction_id is null
                OR	
                	".SQL_DB.".webshop.transaction_id = '')";
		 
		 */
		//echo($sql);
		log_to_file("SQL Bon: -->".$sql);
		$Q1=sIT_mysql_run_query($con_i, $sql, true);	
		
		if (sIT_mysql_num_rows($Q1)==0) return null;
		
		foreach($Q1 as $bon)
		{
			woocommerce_sync_bon($datenbank, $bon['bon_id'],  $bon['tischname']);
		}
		//echo('</p></details>');
	}
	 
	function woocommerce_sync_bon($datenbank, $produkt, $bon_id, $tisch = "")
	{
		
		log_to_file("INFO: -->WooCommerce.php Function: woocommerce_sync_bon");
		//$produkt=woocommerce_get_produkte_array($datenbank, $bon_id);
		
		if ( !is_null($produkt) )
		{
			$orderid = putdata($produkt, $bon_id, $datenbank, $tisch);
			
			log_to_file('-->Bon Nummer: '.$bon_id.'<--');
			log_to_file ('Rechnungsnummer: '.$orderid);
			log_to_file("Upload nach WooCommerce war erfolgreich");
			//instertIntoWebshopDB($orderid, "woocommerce_".$bon_id, $datenbank, true);
		}	
		
	}
	
	function woocommerce_get_produkte_array($datenbank, $bon_id)
	{
		log_to_file("INFO: -->WooCommerce.php Function: woocommerce_get_produkte_array");
		
		global $con_i;
		// TODO: Ticket ID: 8 Kategorien filtern nach woocommerce, categories hinzugefügt
		$sql="SELECT 
					products.ID as ID,
					stueck,
					offener_bon.beilagen_aenderung_plus as beilagen_plus,
					offener_bon.beilagen_aenderung_minus as beilagen_minus,
					offener_bon.CATEGORY,
					offener_bon.printname as printname ,
					products.fremd_id
				FROM 
					".$datenbank.".offener_bon 
				LEFT JOIN 
					".SQL_DB.".products 
				ON 
					offener_bon.produkt_id = products.ID 
				WHERE 
					products.fremd_id<>'' AND bon_id =".$bon_id;

		$Q1=sIT_mysql_run_query($con_i, $sql, true);
		//echo '<br>-->'.$sql.'<--<br>';
		log_to_file("SQL: ".$sql);
		if (sIT_mysql_num_rows($Q1)==0) return null;
		
		return $Q1;
	}
	
	
	$funktion = null;
	if (isset($_REQUEST['funktion']) && $_REQUEST['funktion'] != '') $funktion = $_REQUEST['funktion'];

	if (!is_null($funktion))
	{
		switch ($funktion) {
			case "woocommerce_sync_db_offenen_bon":
				woocommerce_sync_db_offenen_bon();
				break;
			case "woocommerce_sync_db_offenen_bon_ajax":
				woocommerce_sync_db_offenen_bon_ajax();
				break;
			case "woocommerce_sync_db_offenen_bon_deleteorder":
				woocommerce_sync_db_offenen_bon_deleteorder();
				break;
			case "woocommerce_sync_db_offenen_bon_delete_product_ajax":
				woocommerce_sync_db_offenen_bon_delete_product_ajax();
				break;
		}
	}
	
	?>