<?php
// 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()
{
	echo "<br>send_order_to_shopify<br>";
		
	$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_summe = mysql_query("SELECT gesamt_summe from abgeschlossener_bon WHERE bon_id = " . $abp['bon_id'] . ";");

			//if (!$sql_summe) {
			//	echo 'Fehler: ' . mysql_error();
			//	exit;
			//}
			//$row = mysql_fetch_row($sql_summe);
			//$neworder = 0;
			
			//if ( $row[0] < 0 )
			//{
			//	$neworder =1;
		//		echo "......................".$neworder."......................";
		//	}
			
			$sql = "SELECT * from abgeschlossener_bon_produkte WHERE bon_id = " . $abp['bon_id'] . ";";

			$article_ids_refund =array();
			// 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']['fulfillments'] = array();
			$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'] =  "2023-08-30T02:00:00-05:00";
			$data['order']['processed_at'] = date(DATE_ISO8601, strtotime($abp['bon_erstellt_datum']));
			//$data['order']['test'] = true;
			$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'];
					
					//if( ($articleId != '7716576821464' && $articleId != '8499713212754') || $row1['PRICESELL'] > 0)
					//echo "'''''''''''''''''''''''''''<br>";
					//echo $articleId."<br>";
					//echo $row1['stueck']."<br>";
					//echo $row1['PRICESELL']."<br>";
					//echo $row1['PRICESELL']."<br>";
					
					//echo "'''''''''''''''''''''''''''<br>";
					$dp = abs($row1['stueck'] - (int)$row1['stueck']);
					$st_comma = ($dp>0 ? strlen(strval($dp))-2 : 0);
					//echo "______________________<br>";
					//echo $st_comma;
					//echo "______________________<br>";
					//if( $articleId != '7716570661080' || is_numeric($row1['stueck']))
					$netto_einzel = $row1['PRICESELL_brutto'];

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

					if( $st_comma > 0)
					{
						

						if( $row1['PRICESELL']<0 || $stueck <0)
						{
							$data['order']['fulfillments'][0]['line_items'][$i]['variant_id'] = null;
							$data['order']['line_items'][$i]['variant_id'] = null;
							$article_ids_refund[$articleId] = $row1['PRICESELL'];
						}
						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'];
							}

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

						//list($netto_einzel, $netto_summe, $steuer, $steuer_summe) = berechne_nettopreis($netto_rechenen, $row1['tax_rate'],$row1['stueck']);
						//echo "Netto Einzel: ".$netto_einzel."<br>";
						//echo "Netto Summe: ".$netto_summe."<br>";
						//echo "Steuer: ".$steuer."<br>";
						//echo "Steuer Summe: ".$steuer_summe."<br>";
					}
					else
					{
						if( $row1['PRICESELL']<0 || $row1['stueck'] <0)
						{
							echo "-asdfasdfasdfdsafasdf->".$articleId."<--";
							
							
 							$article_ids_refund[$articleId] = $row1['PRICESELL'];
							
							$variations = get_table_api_shopify_url('products/' . $articleId . '/variants.json', 'variants');

							//$refund_products = $variations[0]['id'];
							//$netto_einzel = 0;
							
							
							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'];
							}
						}
						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'];
							}
							

						}

					}

					/*
					if ( $neworder == 1 )
					{
						$data['order']['fulfillments'][0]['line_items'][$i]['quantity'] = 1;
						$data['order']['line_items'][$i]['quantity'] = 1;

						$data['order']['fulfillments'][0]['line_items'][$i]['price'] = 0;
						$data['order']['line_items'][$i]['price'] = 0;
					}
					else
					{
						*/
						$data['order']['fulfillments'][0]['line_items'][$i]['quantity'] = $stueck;
						$data['order']['line_items'][$i]['quantity'] = $stueck;

						$data['order']['fulfillments'][0]['line_items'][$i]['price'] = $netto_einzel;
						//if ( $row1['PRICESELL']<0 )
						//	$netto_einzel = 0;
						$data['order']['line_items'][$i]['price'] = $netto_einzel;
					//}

					

					//$data['order']['fulfillments'][0]['line_items'][$i]['price'] = $row1['PRICESELL'];
					//$data['order']['line_items'][$i]['price'] = $row1['PRICESELL'];
					
					


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

					//if ($row1['PRICESELL_brutto'] < 0)
					//		$data['order']['line_items'][$i]['price'] = $row1['PRICESELL_brutto']*-1;
					//	else
					
					//$data['order']['fulfillments'][0]['line_items'][$i]['price'] = 200;
					//$data['order']['line_items'][$i]['price'] = 200;

					

					$data['order']['line_items'][$i]['location_id'] = SHOPIFY_FILIALE;
					$data['order']['line_items'][$i]['title'] = $row1['printname'];
					//$data['order']['line_items'][$i]['taxable'] = true;
					
					/*
					$data['order']['line_items'][$i]['tax_lines'] = array();
					$data['order']['line_items'][$i]['tax_lines'][0]['price'] = $row1['tax_gesamt'];
					$data['order']['line_items'][$i]['tax_lines'][0]['rate'] = $row1['tax_rate'];
					$data['order']['line_items'][$i]['tax_lines'][0]['title'] = 'AT VAT';
					*/

					$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]['location_id'] = SHOPIFY_FILIALE;
					$data['order']['fulfillments'][0]['line_items'][$i]['title'] = $row1['printname'];
					$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;

					//$data['order']['line_items'][$i]['title'] = $row1['printname'];
					//$data['order']['line_items'][$i]['product_id'] = $articleId;
					//$data['order']['line_items'][$i]['quantity'] = intval($row1['stueck']);

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

			//echo "-------------post---------><pre>";
			//print_r($items_string);
			//echo "<---------post ende---------------------------</pre>";

			$result = post_table_api_shopify_url('orders.json', $items_string);
			
			//echo "-------------test---------><pre>";
			//print_r($result);
			//echo "<---------test ende---------------------------</pre>";

			$bon_id_ab = 0;
			if ($result !== false) {

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

					echo "<br>woo_order_id: ".$bon_id_ab."<br>";
					// lege eine transaktion an
					$data = null;
					//$data['transaction']['amount'] = $row1['PRICESELL_brutto'];
					$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);
					$result2 = post_table_api_shopify_url('orders/' . $bon_id_ab . '/transactions.json', $items_string);



					//$data = null;
					//$data['fulfillment']['location_id'] = SHOPIFY_FILIALE;
					//$items_string = json_encode($data);
					//$test = post_table_api_shopify_url('orders/' . $bon_id_ab . '/fulfillments.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");
					} else {        
						echo "************** ROLLBACK ****************";
						mysql_query("ROLLBACK");
					}
					
					if (count($article_ids_refund) > 0 )
							send_storno_order_to_shopify($abgeschlossener_bon_id,$article_ids_refund);
				
				} else {
					echo "Error";
				}
			}
		
		}
	}
	

	echo "<br>ende send_order_to_shopify<br>";
}

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_shopify($bon_id,$article_ids_refund = null)
{

	
	echo "send_storno_order_to_shopify";
	var_dump($article_ids_refund);
	/*
	$sqlabp = "SELECT
	abp.produkt_id as produkt_id,
	abp.stueck as stueck,
	(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
	left join
		abgeschlossener_bon_produkte abp 
	on
		ab.bon_id = abp.bon_id
	where
		ab.bon_id = $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; 
		";
echo "****************".$sqlabp."*************************";


	$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;
			var_dump($article_ids_refund);
			$minus_price = false;
			 
			
			if(array_key_exists($pid, $article_ids_refund) )
				echo "das ist ein test";

			if(isset($article_ids_refund) && !array_key_exists($pid, $article_ids_refund))
			{
				echo "<br>scheiße<br>";
				continue;
			}
			else if( !is_null($article_ids_refund) && in_array($pid, $article_ids_refund))
			{
				$minus_price = true;
				
			}
			
				
			$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;
			";
		
			echo "SQL: ".$sql_produkt;
			$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++;
				}
				
			}
			
		}
		
	
			
			
			
		
		
		
		if (!is_null($article_ids_refund))
		{
			$storno_note = "Pfandrückgabe";
			
		}
			
			
		$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;
		
		var_dump($data);
		$items_string2 = json_encode($data);
		var_dump($items_string2);
		
		$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();
			}
		}

		/*
		$data2 = null;
		$data2['fulfillment']['id'] = $order['fulfillments'][0]['id'];
		$items_string = json_encode($data2);
		$result = post_table_api_shopify_url('fulfillments/' . $order['fulfillments'][0]['id'] . '/cancel.json', $items_string);
		*/

		
		//print_r($result);
		
		return $data;
	}
}


// ********************************************************************************************************************************************************
// ************************************************* ajax Call ********************************************************************************************
// ********************************************************************************************************************************************************

$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;
}
