<?php
//$debug=true;
// require_once("../config/connect.php");
ini_set('max_execution_time', -1);

function get_object_shopify($parsedResponse, $object_shopify)
{
	switch ($object_shopify) {
		case "products":
			$result = $parsedResponse['products'];
			break;
		case "collects":
			$result = $parsedResponse['collects'];
			break;
		case "collection":
			$result = $parsedResponse['collection'];
			break;
		case "variants":
			$result = $parsedResponse['variants'];
			break;
		case "metafields":
			$result = $parsedResponse['metafields'];
			break;
		case "order":
			$result = $parsedResponse['order'];
			break;
		case "fulfillment_orders":
			$result = $parsedResponse['fulfillment_orders'];
			break;
		case "fulfillment":
			$result = $parsedResponse['fulfillment'];
			break;


		default:
			$result =  $parsedResponse;
	}

	return $result;
}


function get_table_api_shopify_url($strurl, $object_shopify)
{



	$token = FILIALSYSTEM_TOKEN;
	$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
	$nextPage = NULL;
	$url .= $strurl;
	$curl = curl_init();
	//echo "<br>" . $url . "<br>";
	// set result limit and Basic auth

	curl_setopt_array(
		$curl,
		array(
			CURLOPT_URL => $url . "?limit=250",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_CUSTOMREQUEST => "GET",
			CURLOPT_SSL_VERIFYHOST => 0,
			CURLOPT_SSL_VERIFYPEER => 0,
			CURLOPT_HTTPHEADER => array(
				"Content-Type: application/json",
				"X-Shopify-Access-Token: $token"
			)
		)
	);

	// call back function to parse Headers and get Next Page Link
	curl_setopt(
		$curl,
		CURLOPT_HEADERFUNCTION,
		function ($curl, $header) use (&$nextPage) {
			$len = strlen($header);
			$header = explode(':', $header, 2);

			if (count($header) < 2) // ignore invalid headers
				return $len;

			if (trim($header[0]) === "Link" && strpos($header[1], 'next') !== false) {
				$links = explode(',', $header[1], 2);

				$link = count($links) === 2 ? $links[1] : $links[0];
				if (preg_match('/<(.*?)>/', $link, $match) === 1) $nextPage = $match[1];
			}

			return $len;
		}
	);

	// First request
	$response = curl_exec($curl);
	
	if (curl_errno($curl)) {
		$error_msg = curl_error($curl);
		print_r($error_msg);
	}
	$parsedResponse = json_decode($response, true);

	$result = null;

	$result = get_object_shopify($parsedResponse, $object_shopify);


	// generate new requests till next page is available

	while ($nextPage !== NULL) {
		curl_setopt($curl, CURLOPT_URL, $nextPage);

		$result = get_object_shopify($parsedResponse, $object_shopify);

		//$parsedResponse->$object_shopify = [];
		$nextPage = NULL;

		$response = curl_exec($curl);
		$parsedResponse = json_decode($response, true);

		if (curl_errno($curl)) {
			$error_msg = curl_error($curl);
		} else {

			$result = get_object_shopify($parsedResponse, $object_shopify);

			//$result = array_merge($result, $parsedResponse->$object_shopify);
			sleep(2);
		}
	};

	curl_close($curl);
	return  $result;
}

function existiert_id_in_sitpos($id, $table, $primary_key)
{
	global $con_i;

	$sql = "SELECT $primary_key from $table where $primary_key=" . $id . ";";
	//echo $sql."<br>";
	$Q1 = sIT_mysql_run_query($con_i, $sql, true);

	$retval = 0;

	if (sIT_mysql_num_rows($Q1) > 0)
		$retval = 1;

	return $retval;
}

function import_collection_into_sitpos($collection)
{
	global $con_i;
	if (existiert_id_in_sitpos($collection['id'], 'categories', 'id') == 0) {

		$sql_insert = "INSERT into categories SET ID=" . $collection['id'] . ",NAME = '" . $collection['title'] . "';";
		echo $sql_insert . "<br>";
		mysqli_set_charset($con_i, "utf8");
		sIT_mysql_run_query($con_i, $sql_insert, true);
	} else {
		$sql_update = "UPDATE categories SET NAME = '" . $collection['title'] . "' WHERE ID=" . $collection['id'] . ";";
		echo $sql_update . "<br>";
		mysqli_set_charset($con_i, "utf8");
		sIT_mysql_run_query($con_i, $sql_update, true);
	}
}

function import_products_into_sitpos($product, $taxcat, $collection)
{
	date_default_timezone_set("Europe/Berlin");
	$timestamp = time();
	global $con_i;
	$active = 0;
	//		if ( $product['status'] == SHOPIFY_PRODUCTS_STATUS )
	//			$active = 0;

	// WaWi für Waagenexport

	$waagen_nr = null;
	$preis_pro_kilo = null;
	$haltbarkeit_in_tagen = null;
	$waage_produkt_aktivieren = 0;



	echo "get variants<br>";
	echo date("H:i", $timestamp);
	echo "<br>";
	$variations = get_table_api_shopify_url('products/' . $product['id'] . '/variants.json', 'variants');

	$price = null;
	$barcode = null;
	$tax_product = null;
	$sku = null;
	if ($taxcat == '0.1')
		$tax_product = 2;

	if ($taxcat == '0.2')
		$tax_product = 4;



	if (!is_null($preis_pro_kilo))
		$price = $preis_pro_kilo;
	else if (isset($variations) && isset($variations[0]) && isset($variations[0]['price']))
		$price = $variations[0]['price'];


	if (isset($variations) && isset($variations[0]) && isset($variations[0]['sku'])) {
		$sku = preg_replace("/\s+/", "", str_replace('-', '', $variations[0]['sku']));
	}

	if (isset($variations) && isset($variations[0]) && isset($variations[0]['barcode']))
		$barcode = $variations[0]['barcode'];

	if (existiert_id_in_sitpos($product['id'], 'products', 'id') == 0) {
		$produkt_name = mysql_real_escape_string($product['title']);
		$sql_insert = "INSERT into products SET geloescht = " . $active . ",REFERENCE= '" . $sku . "', CATEGORY=" . $collection . ",id=" . $product['id'] . ",NAME = '" . $produkt_name . "'";
		if (!is_null($price)) {
			list($netto_einzel, $netto_summe, $steuer, $steuer_summe) = berechne_nettopreis($price, $taxcat, 1);

			$sql_insert .= ",PRICESELL='" . $netto_einzel . "'";
		}
		if (!is_null($barcode))
			$sql_insert .= ",CODE='" . $barcode . "'";

		if (!is_null($tax_product))
			$sql_insert .= ",TAXCAT=" . $tax_product;

		$sql_insert .= ";";

		echo $sql_insert . "<br>";
		mysqli_set_charset($con_i, "utf8");
		sIT_mysql_run_query($con_i, $sql_insert, true);
	} else {
		$sql_update = "UPDATE products SET geloescht = " . $active . ",REFERENCE= '" . $sku . "',CATEGORY=" . $collection . ",NAME = '" . $product['title'] . "'";
		if (!is_null($price)) {
			list($netto_einzel, $netto_summe, $steuer, $steuer_summe) = berechne_nettopreis($price, $taxcat, 1);
			$netto_einzel = $price / (1 + $taxcat);
			echo $price . "<br>" . (1 + $taxcat) . "<br>";
			$sql_update .= ",PRICESELL='" . $netto_einzel . "'";
		}
		if (!is_null($barcode))
			$sql_update .= ",CODE='" . $barcode . "'";

		if (!is_null($tax_product))
			$sql_update .= ",TAXCAT=" . $tax_product;

		$sql_update .= " WHERE ID=" . $product['id'] . ";";
		echo $sql_update . "<br>";
		mysqli_set_charset($con_i, "utf8");
		sIT_mysql_run_query($con_i, $sql_update, true);
	}

	echo "ende get variants";
	echo "<br>";
	echo date("H:i", $timestamp);
	echo "<br>";
}

function get_tax_from_sitpos($c)
{
	$retVal = 10;
	if ($c['title'] == '20% Steuer')
		$retVal = 0.2000;
	else if ($c['title'] == '10% Steuer')
		$retVal = 0.1000;
	else if ($c['title'] == 'Brot & Gebäck FL')
		$retVal = 0.1000;
	else if ($c['title'] == 'Gemüse FL')
		$retVal = 0.1000;
	else if ($c['title'] == 'Obst FL')
		$retVal = 0.1000;

	return $retVal;
}

function get_data_from_shopify()
{
	//echo SQL_DB."<br>";
	date_default_timezone_set("Europe/Berlin");
	$timestamp = time();
	echo "get collects";
	echo "<br>";
	echo date("H:i", $timestamp);
	echo "<br>";

	/*
	$collect_array=array();	
	$collect = get_table_api_shopify_url('collects.json', 'collects');
	foreach($collect as $c)
	{
		$collect_id=$c['collection_id'];
		if (! in_array($collect_id, $collect_array, true))
		{
			array_push($collect_array, $collect_id);
		}
		
	}
	var_dump($collect_array);
	exit;
	*/

	/*
	foreach($collect as $c)
	{
		
			echo "get collections";
			echo "<br>";
			echo date("H:i",$timestamp);
			echo "<br>";
		$c_id = $c['collection_id'];
		$collection = get_table_api_shopify_url('collections/'.$c_id.'.json', 'collection' );
		
		//if ( $collection['collection']['title'] != '20% Steuer' && $collection['collection']['title'] != '10% Steuer')
	//		continue;
	
	
		$tax = get_tax_from_sitpos( $collection);
		echo "-------------------->".$tax."<--------------------------<br>";
		import_collection_into_sitpos($collection);
		echo "get products";
		echo "<br>";
		echo date("H:i",$timestamp);
		echo "<br>";
		$i=0;
	*/
	$collect_array = array(404137935079, 404137967847, 603475968338, 603475902802, 603475837266);

	$i = 0;
	foreach ($collect_array as $c_id) {
		$collection = get_table_api_shopify_url('collections/' . $c_id . '.json', 'collection');
		import_collection_into_sitpos($collection);
		$tax = get_tax_from_sitpos($collection);
		echo "-------------------->" . $tax . "<--------------------------<br>";

		$products = get_table_api_shopify_url('collections/' . $c_id . '/products.json', 'products');
		var_dump($products);

		foreach ($products as $product) {
			import_products_into_sitpos($product, $tax, $c_id);
			echo "Importiere Produkt $i in collection $c_id ";
			$i++;
		}
	}
}

// ********************************************************************************************************************************************************
// ************************************************* POST/ PUT ********************************************************************************************
// ********************************************************************************************************************************************************

function put_table_api_shopify_url($resource, $items_string = null)
{
	//$token ='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';
	//$url =  'https://markta-demo.myshopify.com/admin/api/2023-04/';
	$token = FILIALSYSTEM_TOKEN;
	//$url =  'https://markta-demo.myshopify.com/admin/api/2023-04/';
	$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;


	$ch = curl_init();


	$url .= $resource;

	//echo $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_CUSTOMREQUEST, "PUT");
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	if (!is_null($items_string))
		curl_setopt($ch, CURLOPT_POSTFIELDS, $items_string);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		"Content-Type: application/json",
		"X-Shopify-Access-Token: $token"

	));

	$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 post_table_api_shopify_url($resource, $items_string = null)
{
	//$token ='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';
	//$url =  'https://markta-demo.myshopify.com/admin/api/2023-04/';
	$token = FILIALSYSTEM_TOKEN;
	//$url =  'https://markta-demo.myshopify.com/admin/api/2023-04/';
	$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;


	$ch = curl_init();


	$url .= $resource;

	//echo $url."<br>";

	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);

	if (!is_null($items_string))
		curl_setopt($ch, CURLOPT_POSTFIELDS, $items_string);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		"Content-Type: application/json",
		"X-Shopify-Access-Token: $token"
	));

	$response = curl_exec($ch);
	log_to_file("-->");
	log_to_file($response);
	log_to_file("<--");
	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 send_order_to_shopify()
{
	global $debug;

	//if ($debug) echo "send_order_to_shopify \n";
		
	$sqlabp = "SELECT abgeschlossener_bon.bon_id,bon_erstellt_datum from abgeschlossener_bon 
	left join abgeschlossener_bon_produkte 
	ON abgeschlossener_bon.bon_id = abgeschlossener_bon_produkte.bon_id  
	WHERE abgeschlossener_bon.dep_nullbeleg = 0 
	AND filialsystem_sync_done = 0  
	AND (abgeschlossener_bon.storno_bemerkung = '' OR abgeschlossener_bon.storno_bemerkung NOT LIKE 'Storno zu Bon%')
	AND abgeschlossener_bon.woo_order_id is null
	GROUP BY abgeschlossener_bon.bon_id;";

	$timestamp = time();
	$datum = date("d.m.Y - H:i", $timestamp);

	$Q1abp = mysql_query($sqlabp);
	if (!$Q1abp) echo "Fehler " . mysql_error();
	else {
		while ($abp = mysql_fetch_assoc($Q1abp)) {
			$sql = "SELECT * from abgeschlossener_bon_produkte WHERE bon_id = " . $abp['bon_id'] . ";";

			// sITpos Bon ID
			$abgeschlossener_bon_id = $abp['bon_id'];
			// Anmerkung
			$note = SHOPIFY_FILIALE . "." . FILIALSYSTEM_KASSA_NAME . "." . $abgeschlossener_bon_id;
			
			$data['order']["line_items"] = array();
			$data['order']["financial_status"] = SHOPIFY_SYNC_ORDERS_STATUS;
			$data['order']["note"] = $note;
			$data['order']["currency"] = 'EUR';
			$data['order']['location_id'] = SHOPIFY_FILIALE;
			$data['order']['fulfillments'] = array();
			$data['order']['fulfillments'][0]['location_id'] = SHOPIFY_FILIALE;
			$data['order']['inventory_behaviour'] = SHOPIFY_SYNC_PRODUKTBESTAND;
			$data['order']['tags'] = "filiale";
			$data['order']['processed_at'] = date(DATE_ISO8601, strtotime($abp['bon_erstellt_datum']));
			$data['order']['taxes_included']= true;
			$totaltax = 0;

			$refund_products = null;

			$Q1 = mysql_query($sql);
			if (!$Q1) echo "Fehler " . mysql_error();
			else {
				$i = 0;
				while ($row1 = mysql_fetch_assoc($Q1)) {

					$articleId = (string)$row1['produkt_id'];
					
					$dp = abs($row1['stueck'] - (int)$row1['stueck']);
					$st_comma = ($dp>0 ? strlen(strval($dp))-2 : 0);
					$brutto_einzel = $row1['PRICESELL_brutto'];
					$brutto_gesamt = $row1['PRICESELL_brutto_gesamt'];

					$stueck = 1;
					if (intval($row1['stueck'])>1)
						$stueck = intval($row1['stueck']);

					echo "price: ".$brutto_einzel;
					echo "stueck: ".$stueck;
						
					if( $st_comma > 0)
					{
						

						if( $brutto_gesamt<0 || $stueck <0)
						{
							$data['order']['fulfillments'][0]['line_items'][$i]['variant_id'] = null;
							$data['order']['line_items'][$i]['variant_id'] = null;
						}
						else
						{
							$variations = get_table_api_shopify_url('products/' . $articleId . '/variants.json', 'variants');
						
							
							if ( is_null($variations) || empty($variations))
							{
								$data['order']['line_items'][$i]['variant_id'] = null;
							}
							else
							{
								$data['order']['fulfillments'][0]['line_items'][$i]['variant_id'] = $variations[0]['id'];
								$data['order']['line_items'][$i]['variant_id'] = $variations[0]['id'];
							}

						}
						$brutto_einzel = $row1['PRICESELL_brutto_gesamt']/$stueck;

					}
					else
					{
						if( $brutto_gesamt<0 || $row1['stueck'] <0)
						{
							
							$variations = get_table_api_shopify_url('products/' . $articleId . '/variants.json', 'variants');
							
							if ( is_null($variations) || empty($variations))
							{
								$data['order']['line_items'][$i]['variant_id'] = null;
							}
							else
							{
								$data['order']['fulfillments'][0]['line_items'][$i]['variant_id'] = $variations[0]['id'];
								$data['order']['line_items'][$i]['variant_id'] = $variations[0]['id'];
							}

							if( $brutto_einzel >0 )
								$brutto_einzel = $brutto_einzel * -1; 
						}
						else
						{
							$variations = get_table_api_shopify_url('products/' . $articleId . '/variants.json', 'variants');

							if ( is_null($variations) || empty($variations))
							{
								$data['order']['line_items'][$i]['variant_id'] = null;
							}
							else
							{
								$data['order']['fulfillments'][0]['line_items'][$i]['variant_id'] = $variations[0]['id'];
								$data['order']['line_items'][$i]['variant_id'] = $variations[0]['id'];
							}
							

						}

					}

					
					$data['order']['fulfillments'][0]['line_items'][$i]['quantity'] = $stueck;
					$data['order']['line_items'][$i]['quantity'] = $stueck;

					$data['order']['fulfillments'][0]['line_items'][$i]['price'] = $brutto_einzel;
					$data['order']['line_items'][$i]['price'] = $brutto_einzel;
					
					$data['order']['fulfillments'][0]['line_items'][$i]['location_id'] = SHOPIFY_FILIALE;
					$data['order']['line_items'][$i]['location_id'] = SHOPIFY_FILIALE;

					$data['order']['fulfillments'][0]['line_items'][$i]['title'] = $row1['printname'];
					$data['order']['line_items'][$i]['title'] = $row1['printname'];

					$data['order']['tax_lines'][$i] = array();
					$data['order']['tax_lines'][$i]['price'] = $row1['tax_gesamt'];
					$data['order']['tax_lines'][$i]['rate'] = $row1['tax_rate'];
					$data['order']['tax_lines'][$i]['title'] = 'AT VAT';
					$data['order']['tax_lines'][0]['taxable'] = false;

					
					$data['order']['fulfillments'][0]['line_items'][$i]['tax_lines'] = array();
					$data['order']['fulfillments'][0]['line_items'][$i]['tax_lines'][0]['price'] = $row1['tax_gesamt'];
					$data['order']['fulfillments'][0]['line_items'][$i]['tax_lines'][0]['rate'] = $row1['tax_rate'];
					$data['order']['fulfillments'][0]['line_items'][$i]['tax_lines'][0]['title'] = 'AT VAT';
					$data['order']['fulfillments'][0]['line_items'][$i]['tax_lines'][0]['taxable'] = false;

					$totaltax = $totaltax + $row1['tax_gesamt'];

					$i++;
				}
			}
			
			
			if ($totaltax < 0)
				$data['order']['total_tax'] = $totaltax * -1;
			else
				$data['order']['total_tax'] = $totaltax;

				
			$items_string = json_encode($data, JSON_PRETTY_PRINT);
			
			$result = post_table_api_shopify_url('orders.json', $items_string);
			
			$bon_id_ab = 0;
			if ($result !== false) {

				if (isset($result) && isset($result['order']) && isset($result['order']['id'])) {
					$bon_id_ab = $result['order']['id'];

					if ($debug) echo "woo_order_id: ".$bon_id_ab."\n";

					// lege eine transaktion an
					$data = null;
					$data['transaction']['currency'] = 'EUR';
					$data['transaction']['order_id'] = $bon_id_ab;
					$data['transaction']['source'] = 'external';
					$data['transaction']['gateway'] = 'cash';
					$data['transaction']['status'] = 'success';
					$data['transaction']['kind'] = 'sale';
					$data['transaction']['parent_id'] = null;
					//$data['transaction']['test'] = true;
					$items_string = json_encode($data, JSON_PRETTY_PRINT);
	
					$result2 = post_table_api_shopify_url('orders/' . $bon_id_ab . '/transactions.json', $items_string);

					// sitpos to shopify wurde erfolgreich ausgeführt
					 
					$flag_abp = true;
					$flag_ab = true;
					mysql_query("START TRANSACTION");
					$sql2 = "UPDATE abgeschlossener_bon_produkte SET filialsystem_sync_done=1 WHERE bon_id=$abgeschlossener_bon_id";
					//echo "<br>--->UPDATE abgeschlossener_bon_produkte SET filialsystem_sync_done=1 WHERE bon_id=$abgeschlossener_bon_id---><br>";
					$Q2 = mysql_query($sql2);
					if (!$Q2) {
						$flag_abp = false;
						echo "Fehler " . mysql_error();
					}
					   

					$sql3 = "UPDATE abgeschlossener_bon SET woo_order_id=$bon_id_ab WHERE bon_id=$abgeschlossener_bon_id";
					// echo "<br>--->UPDATE abgeschlossener_bon SET woo_order_id=$bon_id_ab WHERE bon_id=$abgeschlossener_bon_id---><br>";
					$Q3 = mysql_query($sql3);
					if (!$Q3) 
					{
						$flag_ab = false;
						echo "Fehler " . mysql_error();
					}

					if ($flag_abp && $flag_ab) {
						//echo "************** COMMIT ****************";
						mysql_query("COMMIT");
						if ($debug) echo "Bon $abgeschlossener_bon_id wurde gesynct mit Order ID: $bon_id_ab \n";
					} else {        
						echo "************** ROLLBACK ****************";
						//mysql_query("ROLLBACK");
					}
					
					
				} else {
					//echo "Post Error";
					echo "FEHLER: Bon $abgeschlossener_bon_id sync mit Order ID: $bon_id_ab \n";
					print_r($result);
				}
			}
		
		}
	}
	

	//if ($debug) echo "ende send_order_to_shopify";
}

function send_not_sync_storno_order_to_shopiify()
{
	$sql = "SELECT 
					DISTINCT abgeschlossener_bon.bon_id as bon_id
				FROM 
					abgeschlossener_bon
				LEFT JOIN 
					abgeschlossener_bon_produkte 
				ON 
					abgeschlossener_bon.bon_id = abgeschlossener_bon_produkte.bon_id
				WHERE 
					abgeschlossener_bon_produkte.filialsystem_sync_done = 0
				AND 
				
					abgeschlossener_bon.storno = 1
				AND 
					abgeschlossener_bon.storno_bemerkung like 'Storno zu Bon%';";

	$Q1 = mysql_query($sql);
	if (!$Q1) echo "Fehler " . mysql_error();
	else {
			while ($row = mysql_fetch_assoc($Q1)) {
				send_storno_order_to_shopify($row['bon_id']);
			}
		}
}
function send_storno_order_to_shopify2($bon_id)
{

$sqlabp = "SELECT 
	(if (ab.woo_order_id IS NULL , (SELECT abgeschlossener_bon.woo_order_id FROM abgeschlossener_bon WHERE abgeschlossener_bon.bon_id = REPLACE(ab.storno_bemerkung, 'Storno zu Bon ', '')),ab.woo_order_id)) as woo_order_id 
	from 
		abgeschlossener_bon ab
	where
		bon_id = $bon_id; 
		";


	$Q1abp = mysql_fetch_assoc(mysql_query($sqlabp));

	if (!$Q1abp) echo "Fehler " . mysql_error();
	else {
		
		$bon_id_shopify = $Q1abp['woo_order_id'];


		$order = get_table_api_shopify_url('orders/' . $bon_id_shopify . '.json', 'order');
		
		
		$data2['refund']['order_id'] = $bon_id_shopify;
		$items_string2 = json_encode($data2);
		$data = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds/calculate.json', $items_string2);
		
		$refund_from_order = get_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds.json', 'refunds');
		
		$refund_array = array();
		if( isset($refund_from_order['refunds']['refund_line_items']))
		{
			$refund_items = $refund_from_order['refund_line_items'];
			
			foreach ($refund_items as $item)
			{
				array_push($refund_array,$item['line_item']['product_id']);
			}
		}
		$j = 0;
		//$line_items = null;
		$storno_note = "Storno von sITpos mit der BonID: ".$bon_id;
		foreach ($order['line_items'] as $retvallineitems) {
			
			$pid = (string)$retvallineitems['product_id'];
				
			$sql_produkt = "SELECT
				abp.produkt_id as produkt_id,
				abp.stueck as stueck,
				abp.tax_gesamt as tax_gesamt,
				abp.pricesell_brutto_gesamt as pricesell_brutto_gesamt,
				abp.name as name
				from 
					abgeschlossener_bon_produkte abp
				
				where
					abp.bon_id = $bon_id
				and
					abp.produkt_id = $pid;
			";

			$Qprodukt = mysql_fetch_assoc(mysql_query($sql_produkt));
			
			
			if ( isset($Qprodukt['stueck']) && !in_array($Qprodukt['produkt_id'],$refund_array))
			{
				
				$data3['refund']['currency'] = 'EUR';
				$data3['refund']['refund_line_items'][$j]['line_item_id'] = $retvallineitems['id'];
				$storno_stueck = intval($Qprodukt['stueck']);
				//if ( $storno_stueck < 0 )
					//$storno_stueck = $storno_stueck*-1;
				
				echo "itemid: ".$retvallineitems['id'].", stueck: ".$storno_stueck;
				
				
				//$data3['refund']['refund_line_items'][$j]['subtotal'] = $Qprodukt['pricesell_brutto_gesamt'];
				//$data3['refund']['refund_line_items'][$j]['total_tax'] = $Qprodukt['tax_gesamt'];
				//$data3['refund']['refund_line_items'][$j]['total_tax_set'] = $Qprodukt['tax_gesamt'];
				
				
				$data3['refund']['refund_line_items'][$j]['quantity'] = $storno_stueck;
				$data3['refund']['refund_line_items'][$j]['restock_type'] = 'return';
				
				$items_string = json_encode($data3);
				$datatest = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds/calculate.json', $items_string);
				$datatest['refund']['refund_line_items'][$j]['subtotal'] = $Qprodukt['pricesell_brutto_gesamt'];
				$datatest['refund']['refund_line_items'][$j]['total_tax'] = $Qprodukt['tax_gesamt'];
				$datatest['refund']['refund_line_items'][$j]['total_tax_set'] = $Qprodukt['tax_gesamt'];
				
				if ( isset($datatest['refund']))
				{
					$data['refund'] = $datatest['refund'];
					
					$j++;
				}
				
			}
			
		}
		
		$t = 0;
		foreach ($data['refund']['transactions'] as $test) {
			$data['refund']['transactions'][$t]['kind'] = 'refund';
			$t++;
		}

		$data['refund']['order_id'] = $bon_id_shopify;
		$data['refund']['currency'] = "EUR";
		$data['refund']['notify'] = false;
		$data['refund']['note'] = $storno_note;
			
		$items_string2 = json_encode($data);
		
		$result = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds.json', $items_string2);

		if (isset($result) && isset($result['refund']) )
		{
			$sql3 = "UPDATE abgeschlossener_bon SET woo_order_id=".$bon_id_shopify." WHERE bon_id=$bon_id";
			echo "<br>--->".$sql3."<---<br>";
			$Q3 = mysql_query($sql3);
			if (!$Q3) 
			{
				
				echo "Fehler " . mysql_error();
			}

			$sql4 = "UPDATE abgeschlossener_bon_produkte SET filialsystem_sync_done=1 WHERE bon_id=$bon_id";
			echo "<br>--->UPDATE abgeschlossener_bon_produkte SET filialsystem_sync_done=1 WHERE bon_id=$bon_id---><br>";
			$Q4 = mysql_query($sql4);
			if (!$Q4) {
				
				echo "Fehler " . mysql_error();
			}
		}
		
		return $data;
	}
}
function send_storno_order_to_shopify($bon_id)
{


$sqlabp = "SELECT 
	(if (ab.woo_order_id IS NULL , (SELECT abgeschlossener_bon.woo_order_id FROM abgeschlossener_bon WHERE abgeschlossener_bon.bon_id = REPLACE(ab.storno_bemerkung, 'Storno zu Bon ', '')),ab.woo_order_id)) as woo_order_id 
	from 
		abgeschlossener_bon ab
	where
		bon_id = $bon_id; 
		";




	$Q1abp = mysql_fetch_assoc(mysql_query($sqlabp));

	if (!$Q1abp) echo "Fehler " . mysql_error();
	else {
		
		$bon_id_shopify = $Q1abp['woo_order_id'];
		$order = get_table_api_shopify_url('orders/' . $bon_id_shopify . '.json', 'order');
		
		$data2['refund']['order_id'] = $bon_id_shopify;
		$items_string2 = json_encode($data2);
		$data = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds/calculate.json', $items_string2);
		
		$refund_from_order = get_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds.json', 'refunds');
		
		$refund_array = array();
		if( isset($refund_from_order['refunds']['refund_line_items']))
		{
			$refund_items = $refund_from_order['refund_line_items'];
			
			foreach ($refund_items as $item)
			{
				array_push($refund_array,$item['line_item']['product_id']);
			}
		}
		$j = 0;
		//$line_items = null;
		$storno_note = "Storno von sITpos mit der BonID: ".$bon_id;
		foreach ($order['line_items'] as $retvallineitems) {
			
			$pid = (string)$retvallineitems['product_id'];
			echo "Product ID: ".$pid;
			
		
				
			$sql_produkt = "SELECT
				abp.produkt_id as produkt_id,
				abp.stueck as stueck,
				abp.pricesell_brutto_gesamt as pricesell_brutto_gesamt,
				abp.name as name
				from 
					abgeschlossener_bon_produkte abp
				
				where
					abp.bon_id = $bon_id
				and
					abp.produkt_id = $pid;
			";
		
			$Qprodukt = mysql_fetch_assoc(mysql_query($sql_produkt));
			
			
			if ( isset($Qprodukt['stueck']) && !in_array($Qprodukt['produkt_id'],$refund_array))
			{
				
				$data3['refund']['currency'] = 'EUR';
				$data3['refund']['refund_line_items'][$j]['line_item_id'] = $retvallineitems['id'];
				$storno_stueck = intval($Qprodukt['stueck']);
				if ( $storno_stueck < 0 )
					$storno_stueck = $storno_stueck*-1;
				
				//echo "itemid: ".$retvallineitems['id'].", stueck: ".$storno_stueck;
				
				$data3['refund']['refund_line_items'][$j]['quantity'] = $storno_stueck;
				$data3['refund']['refund_line_items'][$j]['restock_type'] = 'return';
				
				$items_string = json_encode($data3);
				$datatest = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds/calculate.json', $items_string);
		
				if ( isset($datatest['refund']))
				{
					$data['refund'] = $datatest['refund'];
					
					$j++;
				}
				
			}
			
		}
		
		$t = 0;
		foreach ($data['refund']['transactions'] as $test) {
			$data['refund']['transactions'][$t]['kind'] = 'refund';
			$t++;
		}

		$data['refund']['order_id'] = $bon_id_shopify;
		$data['refund']['currency'] = "EUR";
		$data['refund']['notify'] = false;
		$data['refund']['note'] = $storno_note;
		
		$items_string2 = json_encode($data);
		
		$result = post_table_api_shopify_url('orders/' . $bon_id_shopify . '/refunds.json', $items_string2);

		if (isset($result) && isset($result['refund']) )
		{
			$sql3 = "UPDATE abgeschlossener_bon SET woo_order_id=".$bon_id_shopify." WHERE bon_id=$bon_id";
			echo "<br>--->".$sql3."<---<br>";
			$Q3 = mysql_query($sql3);
			if (!$Q3) 
			{
				
				echo "Fehler " . mysql_error();
			}

			$sql4 = "UPDATE abgeschlossener_bon_produkte SET filialsystem_sync_done=1 WHERE bon_id=$bon_id";
	
			$Q4 = mysql_query($sql4);
			if (!$Q4) {
				
				echo "Fehler " . mysql_error();
			}
		}

		
		return $data;
	}
}


// ********************************************************************************************************************************************************
// ************************************************* ajax Call ********************************************************************************************
// ********************************************************************************************************************************************************
function test_order()
{
	$items_string='{
		"order": {
        "line_items": [
            {
                "variant_id": 42961916985560,
                "quantity": 1,
                "price": "49.9",
                "location_id": "83102925124",
                "title": "Weinviertel - einfach koestlich"
            },
            {
                "variant_id": 47108954456388,
                "quantity": 1,
                "price": "0",
                "location_id": "83102925124",
                "title": "Caffeebecher"
            }
        ],
        "financial_status": "pending",
        "note": "83102925124.test_kassa_1.4",
        "currency": "EUR",
        "location_id": "83102925124",
        "fulfillments": [
            {
                "location_id": "83102925124",
                "line_items": [
                    {
                        "variant_id": 42961916985560,
                        "quantity": 1,
                        "price": "0",
                        "location_id": "83102925124",
                        "title": "Weinviertel - einfach koestlich",
                        "tax_lines": [
                            {
                                "price": "4.54000000",
                                "rate": "0.1000",
                                "title": "AT VAT",
                                "taxable": false
                            }
                        ]
                    },
                    {
                        "variant_id": 47108954456388,
                        "quantity": 1,
                        "price": "-1.00000000",
                        "location_id": "83102925124",
                        "title": "Caffeebecher",
                        "tax_lines": [
                            {
                                "price": "-0.17000000",
                                "rate": "0.2000",
                                "title": "AT VAT",
                                "taxable": false
                            }
                        ]
                    }
                ]
            }
        ],
        "inventory_behaviour": "inventory_behaviour",
        "tags": "filiale",
        "processed_at": "2023-09-24T19:28:04+0200",
        "taxes_included": true,
        "tax_lines": [
            {
                "price": "4.54000000",
                "rate": "0.1000",
                "title": "AT VAT",
                "taxable": false
            },
            {
                "price": "-0.17000000",
                "rate": "0.2000",
                "title": "AT VAT"
            },
            {
                "price": "0.58000000",
                "rate": "0.1000",
                "title": "AT VAT"
            }
        ],
        "total_tax": 4.37
    }
}';
	$result = post_table_api_shopify_url('orders.json', $items_string);
	var_dump($result);

	//$bon_id_ab = $result['order']['id'];
	//$items_string='{"transaction":{"currency":"EUR","order_id":5799369900356,"source":"external","gateway":"cash","status":"success","kind":"sale","parent_id":null}}';
	//$result2 = post_table_api_shopify_url('orders/' . $bon_id_ab . '/transactions.json', $items_string);
	//var_dump($result);
}

//test_order();
//exit;

$funktion = '';
if (isset($_REQUEST['funktion'])) {
	$funktion = $_REQUEST['funktion'];
}


switch ($funktion) {
	case "get_data_from_shopify":
		get_data_from_shopify();
		break;
	case "send_order_to_shopify":
		send_order_to_shopify();
		break;
	case "send_not_sync_storno_order_to_shopiify":
		send_not_sync_storno_order_to_shopiify();
		break;
	case "send_not_sync_order_to_shopify";
		send_order_to_shopify();
		break;
}
