<?php

require_once("config/connect.php");
require_once("config/pageConfig.php");
require_once("global_functions.php");
set_time_limit(600);
$synchronizeTables = array("products", "categories");

function get_table_from_host($url)
{
	global $incr;
	if ($incr === "TRUE") $CONDITION = "&incr=TRUE";
	else $CONDITION = "&incr=FALSE";
	//echo $url;
	$xml = simplexml_load_file($url . $CONDITION);
	if (!$xml) {
		echo "Fehler beim Laden der XML vom entfernten Rechner: $url$CONDITION\n";
		foreach (libxml_get_errors() as $error) {
			echo "\t", $error->message . "\n";
		}
	}
	return ($xml);
}

function does_a_record_exist($query)
{
	$sqlP = mysql_query($query);
	if (!$sqlP) {
		die('ERROR: ' . mysql_error(). ' Kommando: ' . $query);
	}
	if (mysql_num_rows($sqlP) >= 1) {
		$row = mysql_fetch_assoc($sqlP);
		//echo var_dump($row);
		return ($row['update_ts']);
	} else return (FALSE);
}

function run_sql_insert($query)
{
	$sqlP = mysql_query($query);
	if (!$sqlP) {
		die('ERROR: ' . mysql_error() . ' Kommando: ' . $query);
	} else return (TRUE);
}

function get_fields($table)
{
	$query = mysql_query("DESCRIBE $table;");
	$result = array();
	if ($query) {
		while ($row = mysql_fetch_assoc($query)) {
			$result[] = $row['Field'];
		}
	}
	return $result;
}

function transfer_table($url, $table_name, $table_key, $kassa_id)
{
	global $incr;
	ini_set('memory_limit', '-1');
	$xml = get_table_from_host($url . "/export_xml.php?TABELLE=" . $table_name . "&KASSA=" . $kassa_id . "&INCR=" . $incr . "&token=" . FILIALSYSTEM_TOKEN);
	$fields = get_fields($table_name);
	$rows = 0;
	mysql_query("Start transaction");
	foreach ($xml->row as $reihe) {
		set_time_limit(60);
		$table_id = urldecode($reihe->$table_key);

		$time = strtotime(urldecode($reihe->update_ts));


		$sql_string_update = "";
		$sql_string_insert1 = "";
		$sql_string_insert2 = "";

		$array = get_object_vars($reihe);

		foreach ($array as $key => $value) {
			if (in_array($key, $fields)) {
				$value = urldecode($value);
				$value = addslashes($value);

				if (isset($sql_string_update) && !empty($sql_string_update)) $sql_string_update = $sql_string_update . ", " . $key . "='" . $value . "'";
				else $sql_string_update = " " . $key . "='" . $value . "'";

				if (isset($sql_string_insert1) && !empty($sql_string_insert1)) $sql_string_insert1 = $sql_string_insert1 . ", " . $key;
				else $sql_string_insert1 = " (" . $key;

				if (isset($sql_string_insert2) && !empty($sql_string_insert2)) $sql_string_insert2 = $sql_string_insert2 . ", '" . $value . "'";
				else $sql_string_insert2 = " ('" . $value . "'";
			}
		}

		$sql_string_update = "UPDATE $table_name SET " . $sql_string_update . " WHERE $table_key='" . $table_id . "'";
		$sql_string_insert = "INSERT INTO $table_name " . $sql_string_insert1 . ") VALUES " . $sql_string_insert2 . ")";

		if ($ts = does_a_record_exist("SELECT $table_key, update_ts FROM $table_name WHERE $table_key='" . $table_id . "'")) { //TODO: return ts
			$ts = strtotime($ts);
			if ($ts < $time) {
				run_sql_insert($sql_string_update);
				$rows++;
			}
		} else {
			run_sql_insert($sql_string_insert);
			$rows++;
		}
		unset($xml);
	}
	mysql_query("commit");
	echo "Datensätze in Tabelle $table_name eingefügt/geändert: " . $rows . "<br>";
	return;
}

function run_import()
{
	$time = -microtime(true);
	$url = FILIALSYSTEM_URL_ZENTRALSYSTEM;
	$url = $url . "/synchronize";

	$kassa_id = FILIALSYSTEM_KASSA_NAME;
	//ini_set('memory_limit', '555555M');
	transfer_table($url, 'categories', 'ID', $kassa_id);
	transfer_table($url, 'products', 'ID', $kassa_id);
	//transfer($url, 'products', 'ID', $kassa_id);
	$time += microtime(true);
	echo "<br>Dauer: " . $time . "<br>";
	return;
}

$incr = "FALSE";

?>

<!DOCTYPE HTML>
<html>

<head>
	<title>SITPOS Synchronisieren</title>
	<?php echo META_DATA_ADMIN;  ?>
	<script src="jquery/jscolor.min.js"></script>
	<style type="text/css">
		<?php include 'include/main.css'; ?><?php include 'include/menue.css'; ?>.adminReportSelect {
			position: relative;
			float: left;
			padding-right: 10px;
			text-align: center;
			margin: 3px 10px 0 1.5%;
			border-radius: .3em;
			font: 20px/100% Arial, Helvetica, sans-serif;
			font-weight: bold;
			font-size: .9em;
			/*width: 27%;*/
			margin-top: 10px;
		}

		.loader {
			border: 10px solid #f3f3f3;
			border-radius: 50%;
			border-top: 10px solid #3498db;
			width: 50px;
			height: 50px;
			-webkit-animation: spin 2s linear infinite;
			/* Safari */
			animation: spin 2s linear infinite;
		}

		/* Safari */
		@-webkit-keyframes spin {
			0% {
				-webkit-transform: rotate(0deg);
			}

			100% {
				-webkit-transform: rotate(360deg);
			}
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}

		button {
			margin-top: 10px !important;
		}

		#responseDiv {
			position: relative;
			width: 98%;
			height: auto;
			min-height: 3%;
			margin: 0 auto;
			background: steelblue;
		}
	</style>

	<script>
		$(document).ready(function(response) {

			var resultMsg = "<p>Synchronisation ausführen.</p>";
			$('#syncProducts').click(function() {
				let selectVal = $('#typeSelect').val();
				var resultMsg = "";

				if (selectVal !== "") {
					let val = "false";
					if (selectVal == "incr") {
						val = "true";
					}
					$('#responseDiv').html("<div class='loader'></div>");
					$.post("ajax_funktionen.php", {
						funktion: "syncProducts",
						incremental: val
					}, function(response) {
						console.log("KPE - Test\n" + response);
						resultMsg += "<p>" + response + "</p>";

						//var test = "My cow always gives milk";
						//var cuttedRes = response.match("TABELLE=(.*)&KASSA");	/(?<=TABELLE).*?(?=KASSA)/		(?<=% of )(.*)(?= at )			var match = event.match( /^([\w:-]*)\s*(.*)$/ )
						cuttedRes = "";
						// cuttedRes = response.match(/TABELLE(.*)KASSA/g);
						// cuttedRes = response.match(/(?<=% TABELLE )(.*)(?= KASSA )/);

						//var regex = /\[(.*)\]/g;
						//var strToMatch = "This is [a test] string [more or less]";
						//var cuttedRes = regex.exec(strToMatch);

						//	cuttedRes=cuttedRes.join();



						//$('#responseDiv').html(resultMsg+"<pre>Synchronisierung Produkte abgeschlossen!</pre><p>######################</p>"+cuttedRes.length+" -- "+cuttedRes.join());
						$('#responseDiv').html(resultMsg + "<pre>Synchronisierung Produkte abgeschlossen!</pre>");
					});
					//console.log("Alle Tabellen an die Zentrale senden");
				} else {
					$('#responseDiv').html("Bitte auswählen, ob komplett oder inkrementiell synchronisiert werden soll!");
				}
			});

			$('#syncKunden').click(function() {
				let selectVal = $('#typeSelect').val();

				if (selectVal !== "") {
					let val = "false";
					if (selectVal == "incr") {
						val = "true";
					}
					$('#responseDiv').html("<div class='loader'></div>");
					$.post("ajax_funktionen.php", {
						funktion: "sync_von_Zentralsystem",
						incremental: val
					}, function(response) {
						console.log(response);
						$('#responseDiv').html(response + "<p>Synchronisierung Kunden abgeschlossen!</p>");
					});
					//console.log("Alle Tabellen an die Zentrale senden");
				} else {
					$('#responseDiv').html("Bitte auswählen, ob komplett oder inkrementiell synchronisiert werden soll!");
				}
			});
			$('#syncGutscheine').click(function() {
				let selectVal = $('#typeSelect').val();

				if (selectVal !== "") {
					let val = "false";
					if (selectVal == "incr") {
						val = "true";
					}
					$('#responseDiv').html("<div class='loader'></div>");
					$.post("ajax_funktionen.php", {
						funktion: "syncGutscheine",
						incremental: val
					}, function(response) {
						console.log(response);
						$('#responseDiv').html(response + "<p>Synchronisierung Gutscheine abgeschlossen!</p>");
					});
					//console.log("Alle Tabellen an die Zentrale senden");
				} else {
					$('#responseDiv').html("Bitte auswählen, ob komplett oder inkrementiell synchronisiert werden soll!");
				}
			});
			$('#syncGutscheineBuchungen').click(function() {
				let selectVal = $('#typeSelect').val();

				if (selectVal !== "") {
					let val = "false";
					if (selectVal == "incr") {
						val = "true";
					}
					$('#responseDiv').html("<div class='loader'></div>");
					$.post("ajax_funktionen.php", {
						funktion: "syncGutscheineBuchungen",
						incremental: val
					}, function(response) {
						console.log(response);
						$('#responseDiv').html(response + "<p>Synchronisierung Gutschein-Buchungen abgeschlossen!</p>");
					});
					//console.log("Alle Tabellen an die Zentrale senden");
				} else {
					$('#responseDiv').html("Bitte auswählen, ob komplett oder inkrementiell synchronisiert werden soll!");
				}
			});
			$('#syncNewDBFields').click(function() {
			
				$('#responseDiv').html("<div class='loader'></div>");
				$.post("ajax_funktionen.php", {
					funktion: "syncNewDBFields"
				}, function(response) {
					console.log(response);
					$('#responseDiv').html(response + "<p>Synchronisierung DB Felder abgeschlossen!</p>");
				});
				
			});
			
			$('#syncAll').click(function() {
				let selectVal = $('#typeSelect').val();

				if (selectVal !== "") {
					$('#responseDiv').html("<div class='loader'></div>");
					$.post("ajax_funktionen.php", {
						funktion: "upsync",
						selVal: selectVal
					}, function(response) {
						console.log(response);
						$('#responseDiv').html("<pre>" + response + "</pre>Synchronisierung abgeschlossen");
					});
					//console.log("Alle Tabellen an die Zentrale senden");
				} else {
					$('#responseDiv').html("Bitte auswählen, ob komplett oder inkrementiell synchronisiert werden soll!");
				}
			});

			$('#delProducts').click(function() {
				if (window.confirm("Haben Sie ein Backup durchgeführt?")) {
					if (window.confirm("Sind sie sicher, dass Sie alle Produkte löschen wollen?")) {
						$('#responseDiv').html("<div class='loader'></div>");
						$.post("ajax_funktionen.php", {
							funktion: "loesche_alle_produkte"
						}, function(response) {
							console.log(response);
							$('#responseDiv').html(response);
						});
					}
				}
			});

			$('#delCategories').click(function() {
				if (window.confirm("Haben Sie ein Backup durchgeführt?")) {
					if (window.confirm("Sind sie sicher, dass Sie alle Warengruppen löschen wollen?")) {
						$('#responseDiv').html("<div class='loader'></div>");
						$.post("ajax_funktionen.php", {
							funktion: "loesche_alle_warengruppen"
						}, function(response) {
							console.log(response);
							$('#responseDiv').html(response);
						});
					}
				}
			});
		});

		function infoClear(toClearId) {
			$("#" + toClearId).html('');


		}
	</script>

</head>

<body>
	<div id="wrapper_admin" class="wrapper_admin">
		<?php menue_anzeigen();	?>
		<br>

		<div id="adminContent">
			<div style="position:relative; width:45%; margin:0 2% 0 0; background:#bbb;" class="floatL">
				<!--<form method="post" action="<?php /*echo htmlentities($_SERVER['PHP_SELF']);*/ ?>">-->
				<table style="width:94%; margin:.2% auto;			">
					<tr>
						<td>
							<select id="typeSelect" name="type" class="adminReportSelect orange" style="width: 90%; margin-left: 5%;">
								<option value="">Bitte auswählen</option>
								<option value="incr">inkrememtiell</option>
								<option value="full">komplett</option>
							</select>
						</td>
					</tr>
					<tr>
						<td>
							<?php
							if (FILIALSYSTEM_UEBERNEHMEN_ZENTRALSYSTEM == "ja") {
								echo '<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncProducts" >Warengruppen und Produkte synchronisieren</button>';
							}
							?>
						</td>
					</tr>
					<tr>
						<td>
							<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncAll" <?php if (FILIALSYSTEM_TOKEN === ""  || FILIALSYSTEM_URL_ZENTRALSYSTEM == "" || FILIALSYSTEM_IST_FILIALSYSTEM === "nein") echo "disabled" ?> >Alle Tabellen an die Zentrale senden</button>
							<!--<input style="width: 90%; margin-left: 5%;" type="submit" id="upsync" class="button orange" name="upsync" value="Alle Tabellen an die Zentrale senden" >
					-->
						</td>
					</tr>
					<tr>
						<td>
							<?php
							if (FILIALSYSTEM_SYNCHRONISATION_KUNDEN_BON == "ja") {
								echo '<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncKunden"> Kunden von Zentrale synchronisieren</button>';
							}

							?>
						</td>
					</tr>
					<tr>
						<td>
							<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncNewDBFields">DB Felder syncronisieren</button>
						</td>
					</tr>
					<tr>
						<td>
							<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncGutscheine">Gutscheine synchronisieren</button>
						</td>
					</tr>
					<tr>
						<td>
							<button style="width: 90%; margin-left: 5%;" class="orange button" id="syncGutscheineBuchungen">Gutschein-Buchungen synchronisieren</button>
						</td>
					</tr>
					<?php
					echo '<tr><td><br>';
					echo '<button style="width: 90%; margin-left: 5%;" class="orange button" id="delProducts"> Alle Produkte l&ouml;schen</button>';
					echo '<button style="width: 90%; margin-left: 5%;" class="orange button" id="delCategories"> Alle Warengruppen l&ouml;schen</button>';
					echo '</td></tr>
							<tr>
								<td><br>
									<button  id="" style="width: 90%; margin-left: 5%;" class="orange button" onclick="infoClear(\'responseDiv\')"   > Infofeld löschen</button>
								</td>
							</tr>';
					?>
				</table>
				<br>
				<?php

				?>
				<br>
			</div>
			<div id="responseDiv" style="position:relative; width:52%; height:75%; margin:0; padding:.5%; overflow-y:auto; word-wrap:break-word; background:#bbb;" class="floatL">


			</div>
			<div class="cclear"></div>


			<!--</form>-->
			<br><br><br>
			<h3>
				<?php
				if (FILIALSYSTEM_TOKEN === "" || FILIALSYSTEM_URL_ZENTRALSYSTEM === "" || FILIALSYSTEM_IST_FILIALSYSTEM === "nein") {
					/*if (isset($_POST['submit'])) {
						session_write_close();
						run_import();
					} else if (isset($_POST['upsync'])) {
						session_write_close();
						include 'synchronize/sync_table_structure.php';
						include 'synchronize/sync_data.php';
						//run_import(); 
					} else if (isset($argv[1])) {
						session_write_close();
						if ($argv[1] === "false") {
							$incr = "FALSE";
						}
						run_import();
					}*/
					echo "<div>Kein Token bzw. keine URL in den Filialsystem Einstellungen gesetzt!<br>
						Bevor synchronisiert werden kann müssen diese Einstellungen getätigt werden</div>";
				}
				?>
			</h3>

		</div>
		<div id="responseDiv_X" style=""></div>
	</div>
</body>

</html>