<?php

// Diese Seite durchsucht die Datenbank nach gespeicherten Werten (keine Brücken, Programme, etc..)



$meta = $_GET["meta"];
$view = $_GET["view"];

$db = new SQLite3('../db-test/test.db');

// Die Suche, auf welche nach der Durchführung einer Messung zugegriffen wird (ganz unten: möchten Sie die Messung in die Datenbank aufnehmen...)
if($view == "results") {
		
	?>
	<div class="inventory-table">
		<?php
		$result = 0;

		// Hole die Orte
		$result = $db->query(" SELECT * FROM  places WHERE name LIKE '%" . strtolower($meta) . "%' ");

		while ($row = $result->fetchArray(SQLITE3_ASSOC)) {

			// Wenn die suche leer ist, sollen auch keine Ergebnisse kommen (siehe Vorschläge ignorieren)
			if($meta == "") {
				return;
			}

			?>
			<div class="row" style="cursor: pointer" onclick="$('#database-search-term').val('<?php echo $row["name"]; ?>'); search('results');">
				<img src="/vendor/icons/map-pin.svg" class="map" /><span><?php echo $row["name"]; ?></span>
			</div>
			<?php
		}
		
		// Wenn ein Ergebnis gefunden wird...
		if($result == 1) {
			// ... biete an, alle Vorschläge zu ignorieren
			?>
			<div class="row" style="cursor: pointer; width:50%;margin:15px auto;background-color: #f6615173" onclick="$('#database-search-term').attr('onkeyup',''); search('results','x');">
				<img src="/vendor/icons/xmark.svg" class="" /><span align="center">Vorschläge ignorieren</span>
			</div>

			<?php
		}
		// Ende der Sucherergebnisse
		?>
	</div>
	<?php
}

// Hier wird der Bestand angezeigt, der in der Bestandsuche nach einem Tastenanschlag erscheint
if($view == "program" && isset($meta) && !empty($meta)) {
	
	
	// weil die Bestandssuche (im Gegensatz zur Ortssuche) die Programmbezeichnung durhcsucht, ist hier etwas mehr Aufwand erforderlich
	// hole die Programmbezeichnung via 2x JOIN aus der Datenbank
	$result = $db->query("

		SELECT 
		m.id AS measurement_id,
		m.comment AS comment,
		m.timestamp AS timestamp,
		m.place_name AS place_name,
		b.value AS bit_value,
		b.position AS bit_position
		FROM 
		measurements m
		JOIN places p ON p.name = m.place_name
		JOIN measurement_program_id_bits b ON b.measurement_id = m.id
		ORDER BY m.id

	");

	/*
	Ausgabe sieht z.B. so aus:

	| measurement_id | comment | timestamp | place_name   | bit_value | bit_position |
	| -------------- | ------- | --------- | ------------ | --------- | ------------ |
	| 1              | xyz..   | 34535454  | Dudweiler Df | S         | 0            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 1            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | 4         | 2            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 3            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 4            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | A         | 0            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | 6         | 1            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | 4         | 2            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | -         | 3            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | S         | 4            | 

	*/
   
	// Die Datenbank wird als dreifach indexiertes Array gespeichert
	$database_db = [];
	while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
		$database_db[$row["place_name"]][$row["measurement_id"]]["program_id_bits"][$row["bit_position"]] = $row["bit_value"];
		$database_db[$row["place_name"]][$row["measurement_id"]]["comment"] = $row["comment"];
		$database_db[$row["place_name"]][$row["measurement_id"]]["timestamp"] = $row["timestamp"];
	}
	
	/*
	
	$database_db
	└── $row["place_name"]         
		└── $row["measurement_id"]       
			├── "program_id_bits"
			│   └── $row["bit_position"]    
			│       └── $row["bit_value"] 
			├── "program_id_string"
			│   └── implode('', $bits)
			├── "comment"
			│   └── $row["comment"]    
			└── "timestamp"
				└── $row["timestamp"]   
	
	*/
	
	// speichere die Bits als String, damit diese einfacher durchsuchbar sind
	foreach ($database_db as $place => $entries) {
		foreach ($entries as $index => $info) {
			$bits = $info['program_id_bits'];
			$database_db[$place][$index]['program_id_string'] = implode('', $bits);
		}
	}

	// durchsuche nach der Query im Programm-ID-String
	foreach($database_db as $place_name => $measurements) {
		$found = false;
		foreach ($measurements as $measurement_id => $measurement) {
			if(str_contains(strtolower($measurement["program_id_string"]), strtolower($meta))) {
				$found = true;
			}
		}
		if($found != true) {
			continue;
		}
		?>

		<div class="row">
			<img src="/vendor/icons/map-pin.svg" class="map" />
			<span>
				&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <?php echo $place_name; ?>
			</span>
			<div class="plug-table" style="display: block;" id="<?php echo $database_db[$place_name]; ?>">
				<?php
				foreach ($measurements as $measurement_id => $measurement) {

					if(!str_contains(strtolower($measurement["program_id_string"]), strtolower($meta))) {
						continue;
					}

					print('
					<div class="row">
						<div class="label" style="width: 180px;">
							<span>');


								$i = 0;
								foreach($measurement["program_id_bits"] as $programIDChar) {
								echo '<span class="label-char">' . $programIDChar . '</span>';
								$i++;
								}

								print('
							</span>
						</div>
						<div>
							<div class="label" style="width: 50%;">
								<span>' . date("d.m.Y H:i:s", $measurement["timestamp"]) . '</span>
							</div>');

							?>

							<div class="options">
								<img src="/vendor/icons/trash.svg" onclick="if(confirm('Sicher? Diese Änderung kann nicht rückgängig gemacht werden! )') == true){save('inventory','remove','<?php echo $measurement_id; ?>')}">
							</div>

							<?php


							print('
						</div>
					</div>');

					if(!empty($measurement["comment"])) {

						print('
						<div class="row" style="position: relative; height: auto;padding: 0 15;padding-left: 40px;box-sizing:border-box;">
							<img src="/vendor/icons/info-circle.svg" style=" top: 2.5px;left: 10px;" />');
							echo $measurement["comment"];
						print('
						</div>');
					}
				}
				?>
			</div>
		</div>
		<?php
	}
}

// Hier wird der Bestand angezeigt, der in der Bestandssuche nach dem Klick auf "Alle Einträge holen" angezeigt wird
elseif ($view == "program") {
	
	/*
	Ausgabe sieht z.B. so aus:

	| measurement_id | comment | timestamp | place_name   | bit_value | bit_position |
	| -------------- | ------- | --------- | ------------ | --------- | ------------ |
	| 1              | xyz..   | 34535454  | Dudweiler Df | S         | 0            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 1            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | 4         | 2            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 3            | 
	| 1              | xyz..   | 34535454  | Dudweiler Df | -         | 4            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | A         | 0            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | 6         | 1            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | 4         | 2            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | -         | 3            | 
	| 7              | abc..   | 48548574  | Mannheim Hbf | S         | 4            | 

	*/

	$result = $db->query("

	SELECT 
	m.id AS measurement_id,
	m.comment AS comment,
	m.timestamp AS timestamp,
	m.place_name AS place_name,
	b.value AS bit_value,
	b.position AS bit_position
	FROM 
	measurements m
	JOIN places p ON p.name = m.place_name
	JOIN measurement_program_id_bits b ON b.measurement_id = m.id
	ORDER BY m.id

	");

	// Die Datenbank wird als dreifach indexiertes Array gespeichert
	$database_db = [];
	while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
		$database_db[$row["place_name"]][$row["measurement_id"]]["program_id_bits"][$row["bit_position"]] = $row["bit_value"];
		$database_db[$row["place_name"]][$row["measurement_id"]]["comment"] = $row["comment"];
		$database_db[$row["place_name"]][$row["measurement_id"]]["timestamp"] = $row["timestamp"];
	}
	
	/*
	
	$database_db
	└── $row["place_name"]         
		└── $row["measurement_id"]       
			├── "program_id_bits"
			│   └── $row["bit_position"]    
			│       └── $row["bit_value"] 
			├── "program_id_string"
			│   └── implode('', $bits)
			├── "comment"
			│   └── $row["comment"]    
			└── "timestamp"
				└── $row["timestamp"]   
	
	*/

	foreach($database_db as $place_name => $measurements) {



		?>

		<div class="row">
			<img src="/vendor/icons/map-pin.svg" class="map" /><span>[<?php echo count($database_db[$place_name]); ?>]  <?php echo $place_name; ?></span>
			<img src="/vendor/icons/arrow-down-tag.svg" class="down" onclick="$('#<?php echo  preg_replace('/[^a-zA-Z0-9]/', '',$place_name); ?>').css('display','block');"/>
			<div class="plug-table" style="display: none;" id="<?php echo  preg_replace('/[^a-zA-Z0-9]/', '',$place_name); ?>">

				<?php

				foreach ($measurements as $measurement_id => $measurement) {

					print('
					<div class="row" style="margin-bottom: 0;">
						<div class="label" style="width: 180px;">
							<span>');

								foreach($measurement["program_id_bits"] as $programIDChar) {
									echo '
									<span class="label-char">' . $programIDChar . '</span>';
								}

								print('
							</span>
						</div>
						<div>
							<div class="label" style="width: 50%;">
								<span>' . date("d.m.Y H:i:s", $measurement["timestamp"]) . '</span>
							</div>');
							?>

							<div class="options"><img src="/vendor/icons/trash.svg" onclick="if(confirm('Sicher? Diese Änderung kann nicht rückgängig gemacht werden! )') == true){save('inventory','remove','<?php echo $measurement_id; ?>')}"></div>

							<?php

							print('
						</div>
					</div>');

					if(!empty($measurement["comment"])) {

						print('
						<div class="row" style="position: relative; height: auto;padding: 0 15;padding-left: 40px;box-sizing:border-box;"><img src="/vendor/icons/info-circle.svg" style=" top: 2.5px;left: 10px;" />');
							echo $measurement["comment"];
						print('
						</div>');
					}
				}
				?>
			</div>
		</div>
		<?php
	}
}
