<?php
	require_once("../../config/connect.php");
	require_once("../../config/sIT_global_db_functions.php");  
	require_once("../../global_functions.php");
	
	ini_set('max_execution_time', -1);
	
	
	function get_table_api_shopify_url($strurl,$object_shopify)
	{
		
	

$token = FILIALSYSTEM_TOKEN;
$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
$nextPage = NULL;
$url .= $strurl;
$curl = curl_init();

// 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);
//$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
		
//$header = substr($response_shopify, 0, $header_size);
//$response = substr($response_shopify, $header_size);

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

$result = null;
echo "<br>-->".$object_shopify."<--<br>";
var_dump($parsedResponse);
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;
	
}

// generate new requests till next page is available

while ($nextPage !== NULL) {
    curl_setopt($curl, CURLOPT_URL, $nextPage);
    switch ($object_shopify) {
	case "products":
		$parsedResponse['products'] = [];
		break;
	case "collects":
		 $parsedResponse['collects'] = [];
		break;
	case "collection":
		 $parsedResponse['collection'] = [];
		break;
	case "variants":
		 $parsedResponse['variants'] = [];
		break;
		case "metafields":
		 $parsedResponse['metafields'] = [];
		break;
}
    //$parsedResponse->$object_shopify = [];
    $nextPage = NULL;

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

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

	switch ($object_shopify) {
		case "products":
			$result = array_merge($result, $parsedResponse['products']);
			break;
		case "collects":
			$result = array_merge($result, $parsedResponse['collects']);
			break;
		case "collection":
			$result = array_merge($result, $parsedResponse['collection']);
			break;
		case "variants":
			$result =array_merge($result,  $parsedResponse['variants']);
			break;
		case "metafields":
			$result =array_merge($result,  $parsedResponse['metafields']);
			break;
	}

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

curl_close($curl);
return  $result;
}
	
	
	function old__get_table_api_shopify_url($strurl)
	{
		try
		{
			$token = SHOPIFY_TOKEN;
			//$url =  'https://markta-demo.myshopify.com/admin/api/2023-04/';
			$url = SHOPIFY_REST_API_URL;
					 
			$url .= $strurl;
			
			$ch = curl_init();
			
			echo $url."<br>";
			curl_setopt( $ch, CURLOPT_URL, $url );
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			//curl_setopt( $ch, CURLOPT_POST, 1 );
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			curl_setopt($ch, CURLOPT_HEADER, TRUE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			$header = [
				"Content-Type:application/json",
				"X-Shopify-Access-Token: $token"
			];
			curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
			$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 "-->";
			//var_dump(json_decode($body, true));
			//echo "<--";
			return json_decode($body, true);
		
		}catch (Exception $e) {
			echo 'Exception abgefangen: ',  $e->getMessage(), "<br>";
		}
	}
	
	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;
		$anzeigen = 1;
		if( $collection['id'] == '404137935079' || $collection['id'] == '404137967847')
			$anzeigen = 1;
		
	if (existiert_id_in_sitpos($collection['id'], 'categories', 'id') == 0) {

		$sql_insert = "INSERT into categories SET ID=" . $collection['id'] . ",NAME = '" . $collection['title'] . "',anzeigen=".$anzeigen.";";
		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 anzeigen=".$anzeigen.",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;
		$produkt_name=mysql_real_escape_string($product['title']);
		
		
		echo "get variants<br>";
		echo date("H:i",$timestamp);
		echo "<br>";
		$variations = get_table_api_shopify_url('products/'.$product['id'].'/variants.json', 'variants');
		
		$meta_data = get_table_api_shopify_url('products/'.$product['id'].'/metafields.json','metafields');
		echo "--------------------------------------";
		echo $product['id'];
		echo "--------------------------------------";
		//var_dump($meta_data);
		var_dump($variations);
		$price = null;
		$barcode = null;
		$tax_product = null;
		$sku = null;
		if($taxcat == '0.1')
				$tax_product = 2;
			
		if($taxcat == '0.2')
				$tax_product = 4;
		echo "----------------------------------------------------->";	
		
		//$price = $variations[0]['price'];
		//if(!is_null($preis_pro_kilo))
		$meta_data = get_table_api_shopify_url('products/'.$product['id'].'/metafields.json','metafields');
			foreach ( $meta_data as $metafield)
			{
				if ( isset($metafield['namespace']) && $metafield['namespace']== 'markta' && $metafield['key'] == 'price_in_kg' )
				{ 
					var_dump($metafield['value']);
					$value_array=json_decode($metafield['value'], true);
					var_dump($value_array['amount']);
					if ( isset($value_array['amount']))
					 $preis_pro_kilo = $value_array['amount'];
					//exit;
					//if ( isset($metafield['value']) && isset($metafield['value']['amount']))
					//	$preis_pro_kilo = $metafield['value']['amount'];
				}
			}
		
				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('37-','',$variations[0]['sku']));
			$sku = preg_replace("/\s+/", "",str_replace('38-','',$sku));
			if (strlen($sku)<5) $sku=str_pad($sku, 5, '0', STR_PAD_LEFT);
		}

		if (isset($variations) && isset($variations[0]) && isset($variations[0]['barcode']))
		{
			$barcode = $variations[0]['barcode'];
			$barcode = preg_replace("/\s+/", "",str_replace('-','',$barcode));
		}
		
		if (existiert_id_in_sitpos($product['id'], 'products', 'id') == 0 )
		{
			
			$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);
				$netto_einzel = $price / (1 + $taxcat);
				
				echo "<br>PRICE: ".$price . "<br>" . (1 + $taxcat) . "<br>";
				
				// Pfand Rückgabe 10% & Pfand Rückgabe 20% in Shopify keinen Minuswert eingeben
				if( $product['id'] == '8499713376594' || $product['id'] == '8499713212754')
				{
					$netto_einzel = $netto_einzel*-1;
					echo "netto_einzel ".$netto_einzel."<br>";
					
				}
				
				$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 = '".$produkt_name."'";
			if (!is_null($price)) {
				list($netto_einzel, $netto_summe, $steuer, $steuer_summe) = berechne_nettopreis($price, $taxcat, 1);
				$netto_einzel = $price / (1 + $taxcat);
				echo "Taxcat<br>".$taxcat."<br>";
				
				echo "<br>PRICE: ".$price . "<br>" . (1 + $taxcat) . "<br>";
				
				// Pfand Rückgabe 10% & Pfand Rückgabe 20% in Shopify keinen Minuswert eingeben
				if( $product['id'] == '8499713376594' || $product['id'] == '8499713212754')
				{
					$netto_einzel = $netto_einzel*-1;
					echo "netto_einzel ".$netto_einzel."<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 = 0.1000;
		
		if ( $c['title'] == '20% Steuer' )
			$retVal = 0.2000;
		else if ( $c['title'] == 'Coffeeshop' )
			$retVal = 0.2000;
		else if ( $c['title'] == 'Taschen FL' )
			$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;
		else if($c['title'] == 'Pfand')
			$retVal = 0.1000;
		else if($c['title'] == 'Milchprodukte FL')
			$retVal = 0.1000;
		else if($c['title'] == 'Eis FL')
			$retVal = 0.1000;
			
		return $retVal;
	}
	
	function sitpos_sync_categories_and_products()
	{
		//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, 603548385618,603592196434,603592360274,603891073362,604735930706,604735799634);
		//$collect_array = array (384112951512,384189858008);
		//$collect_array = array (604735930706,604735799634);
				
		$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)
			{
				if($product['id'] == '8499715375442' || $product['id'] == '8499717013842' || $product['id'] == '8499715375442' || $product['id'] == '8499713376594' )
					$tax = 0.2000;
				
				import_products_into_sitpos($product, $tax, $c_id);

				if($product['id'] == '8499715375442' || $product['id'] == '8499717013842' || $product['id'] == '8499715375442' || $product['id'] == '8499713376594' )
					$tax = 0.1000;
				
				echo "Importiere Produkt $i in collection $c_id ";
				$i++;
			}
		
		}	 
		
	}

	if (isset($_REQUEST['funktion'])) {
		$funktion = $_REQUEST['funktion'];
	}
	else
	{
		sitpos_sync_categories_and_products();
		exit;
	}
	
	switch ($funktion) {		
		case "sync_categories_and_products":

			sitpos_sync_categories_and_products();
			break;
		default:
			echo "Falscher Aufruf";
	}
	
?>