<?php
/*
 *  This file is part of open3A.

 *  open3A is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.

 *  open3A is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  2007 - 2020, open3A GmbH - Support@open3A.de
 */

class ImportGUI extends TempFileGUI implements iGUIHTML2 {
	function getHTML($id){
		
		$FB = new FileBrowser();
		$FB->addDir("../open3A/Import/");
		
		if(isset($_SESSION["ImportDirs"]))
			foreach($_SESSION["ImportDirs"] as $k => $v)
				$FB->addDir($v);

		$file = $_SESSION["TempFiles"]->get($id);
		$autoLoad = false;

		$options = $FB->getAsLabeledArray("iImportable",".class.php",true);
		foreach($options AS $key => $value){
			if(stripos($file->A("originalFilename"), $key) !== false) $autoLoad = true;
			$options[$key] = "<option value=\"$value\" ".(stripos($file->A("originalFilename"), $key) !== false ? "selected=\"selected\"" : "").">$key</option>";
		}
		
		if(!file_exists($file->A("filename"))) {
			$t = new HTMLTable(1,"Fehler");
			$t->addRow("Die Datei <code>".$file->A("filename")."</code> wurde auf dem Datenträger nicht gefunden! ");
			$t->addRow("");
			$t->addRowClass("backgroundColor0");
			$t->addRow("Möglicherweise fehlt Ihrem Webserver die Erlaubnis, in das oben angegebene Verzeichnis zu schreiben.<br /><br />Versuchen Sie in diesem Fall zuerst, das Verzeichnis <code>/system/IECache</code> durch den Webserver beschreibbar zu machen. (Im FTP-Programm oder per Konsole die Rechte 777 vergeben.)");
			$t->addRow("Falls der Upload dann immer noch nicht funktioniert, gehen Sie bitte wie folgt vor:
			<ul>
			<li>Laden Sie mit einem FTP-Programm die Datei in das Verzeichnis <code>".dirname($file->A("filename"))."</code></li>
			<li>Benennen Sie die Datei um, so dass Sie <code>".basename($file->A("filename"))."</code> heißt.</li>
			</ul>");
			$t->addRow("");
			$t->addRowClass("backgroundColor0");
			$t->addRow("Temporäre Dateien werden automatisch gelöscht, wenn sie älter als 3 Minuten sind. Eventuell existiert die Datei deshalb nicht mehr auf dem Dateisystem.");
			return $t->getHTML();
		}

		$testLine = fgets(fopen($file->A("filename"),'rb'));


		$html = "
		<form id=\"importForm\">
		<div class=\"backgroundColor1 Tab\"><p>Datei Importieren</p></div>
		<table>
			<colgroup>
				<col class=\"backgroundColor2\" style=\"width:120px;\" />
				<col class=\"backgroundColor3\" />
			</colgroup>
			<tr>
				<td><label>Dateiname:</label></td>
				<td>{$file->A("originalFilename")}</td>
			</tr>
			<tr>
				<td><label>Dateigröße:</label></td>
				<td>".Util::formatByte($file->A("filesize"),2)."</td>
			</tr>
			<tr>
				<td><label>Dateityp:</label></td>
				<td>{$file->A("filetype")}</td>
			</tr>";
		
		/*if(strpos($file->getA()->filetype, "text/") === false){
			$html .= "
			<tr>
				<td colspan=\"2\">Diese Datei ist nicht zum Importieren geeignet.
				<br />Versuchen Sie, der Datei die Endung .txt zu geben.</td>
			</tr>
		</table>";
			return $html;
		}*/
		
		$html .= "
			<tr>
				<td class=\"backgroundColor0\"></td>
			</tr>
			<tr>
				<td><label>Kodierung:</label></td>
				<td>
					<select id=\"codepage\" name=\"codepage\">
						<option value=\"UTF-8\">UTF-8</option>
						<option value=\"nicht UTF-8\">nicht UTF-8</option>
					</select><br>
					<small>Ändern Sie diesen Wert, wenn die Umlaute nicht korrekt übernommen werden.</small>
				</td>
			</tr>
			<tr>
				<td><label>Zahlen:</label></td>
				<td>
					<select id=\"sepDecimal\" name=\"sepDecimal\">
						<option value=\",\" selected=\"selected\">Mit \",\"</option>
						<option value=\".\">Mit \".\"</option>
					</select><br>
					<small>Das Dezimaltrennzeichen</small>
				</td>
			</tr>
			<tr>
				<td><label>Trennzeichen:</label></td>
				<td>
					<select id=\"sep\" name=\"sep\">
						<option value=\"1\">,</option>
						<option value=\"2\" ".(stripos($testLine, "\";\"") !== false ? "selected=\"selected\"" : "").">;</option>
						<option value=\"3\">Tab</option>
					</select>
				</td>
			</tr>
			<tr>
				<td><label>Texttrenner:</label></td>
				<td>
					<select id=\"sepText\" name=\"sepText\">
						<option value=\"2\">\"</option>
						<option value=\"1\">'</option>
					</select>
				</td>
			</tr>
			<tr style=\"display:none;\">
				<td><label>neue Zeile:</label></td>
				<td>
					<input type=\"text\" value=\"\" id=\"newLine\" name=\"newLine\" />
				</td>
			</tr>
			<tr>
				<td><label>ab Zeile:</label></td>
				<td><input type=\"text\" id=\"startLine\" name=\"startLine\" value=\"0\" /></td>
			</tr>
			<tr>
				<td><label>bis Zeile:</label></td>
				<td><input type=\"text\" id=\"endLine\" name=\"endLine\" value=\"0\" /><br /><small style=\"color:grey;\">0 deaktiviert diese Funktion</small></td>
			</tr>
			<tr>
				<td><label>erste Zeile:</label></td>
				<td><input onclick=\"Import.preview('$id');\" type=\"checkbox\" id=\"firstLine\" name=\"firstLine\" value=\"1\" ".($autoLoad ? "checked=\"checked\"" : "")." /><br /><small style=\"color:grey;\">für Spaltennamen verwenden</small></td>
			</tr>
			<tr>
				<td colspan=\"2\"><input onclick=\"Import.preview('$id');\" type=\"button\" value=\"Vorschau laden/aktualisieren\" /></td>
			</tr>
			<!--<tr>
				<td colspan=\"2\"><div style=\"display:none;overflow:scroll;height:200px;width:399px;\" id=\"vorschau\"></div></td>
			</tr>-->
			<tr>
				<td class=\"backgroundColor0\"></td>
			</tr>
			<tr>
				<td><label>Plugin:</label></td>
				<td>
					<input type=\"hidden\" name=\"TempFileID\" id=\"TempFileID\" value=\"$id\" />
					<select name=\"importToPlugin\" id=\"importToPlugin\" onchange=\"Import.preview('$id');\">
						<option value=\"-\">bitte auswählen</option>
						".implode($options)."
					</select></td>
			</tr>
		</table>
		<div id=\"importFields\"></div>
		</form>".($autoLoad ? "<script type=\"text/javascript\">Import.preview('$id');</script>" : "");
		#$this->parse("\n","\"",";");
		
		
		return $this->settingsTable().$html;
	}
	
	function settingsTable($echo = false){
		$ST = new HTMLSideTable("right");
		$ST->setTableID("settings");
		
		$B = $ST->addButton("Einstellungen\nspeichern", "save");
		$B->popup("", "Einstellungen speichern", "Import", $this->getID(), "settingsPopup");
		
		$AC = anyC::get("ImportSetting");
		$AC->addOrderV3("ImportSettingName");
		
		$TS = new HTMLTable(3, "Einstellungen");
		$TS->setTableStyle("width:100%;");
		$TS->useForSelection(false);
		$TS->setColWidth(1, 20);
		$TS->setColWidth(2, "100%");
		$TS->setColWidth(3, 20);
		$TS->weight("light");
		
		while($S = $AC->n()){
			$json = "";
			$data = explode("&", $S->A("ImportSettingData"));
			
			foreach($data AS $v){
				if(trim($v) == "")
					continue;
				
				$d = explode("=", $v);
				$f = $d[0];
				
				$json->$f = str_replace("%20", " ", $d[1]);
			}
			
			$BL = new Button("Einstellungen laden", "arrow_left", "iconic");
			$BL->onclick("Import.applySettings('".$this->getID()."', ".str_replace("\"", "'", json_encode($json, JSON_UNESCAPED_UNICODE)).");");
			
			$BD = new Button("Einstellungen löschen", "trash_stroke", "iconic");
			$BD->doBefore("if(confirm('Sollen diese Einstellungen gelöscht werden?')) %AFTER");
			$BD->rmePCR("ImportSetting", $S->getID(), "deleteMe", "", OnEvent::rme($this, "settingsTable", array(1), "function(t){ \$j('#settings').replaceWith(t.responseText); }"));
			
			$TS->addRow(array(
				$BL,
				$S->A("ImportSettingName"),
				$BD
			));
			
		}
		
		$ST->addRow($TS);
		
		if($echo)
			echo $ST;
		
		return $ST;
	}
	
	function settingsPopup(){
		$F = new HTMLForm("saveSettings", array("name", "data"));
		$F->getTable()->setColWidth(1, 120);
		$F->setType("data", "hidden");
		$F->setSaveRMEPCR("Speichern", "", "Import", $this->getID(), "settingsSave", "function(){ ".OnEvent::closePopup("Import")."contentManager.rmePCR('Import', ".$this->getID().", 'settingsTable',[1], function(t){ \$j('#settings').replaceWith(t.responseText); });}");
		
		echo $F.OnEvent::script("\$j('[name=data]').val(joinFormFields('importForm'));");
	}
	
	function settingsSave($name, $data){
		$F = new Factory("ImportSetting");
		
		$F->sA("ImportSettingName", $name);
		$F->sA("ImportSettingData", $data);
		
		$F->store();
	}
	
	function loadFields($plugin){
		if($plugin == "-") die("");
		$c = new $plugin();

		$T = new HTMLTable(2, "Spaltenzuordnung");
		$T->setColWidth(1, 120);
		$T->maxHeight(400);
		
		$v = $c->getFieldsValues();
		$s = $c->getFieldsSeparators();
		$d = $c->getFieldsDescriptions();
		
		foreach($c->getFieldsList() AS $key => $value){
			if(isset($s[$value])){
				$T->addRow(array($s[$value]));
				$T->addRowClass("backgroundColor0");
				$T->addRowColspan(1, 2);
			}
			
			$spalten = "<option value=\"-\">nicht importieren</option>";
			
			if(isset($v[$value])){
				
				foreach($v[$value] AS $ID => $label)
					$spalten .= "<option value=\"$ID\">$label</option>";
				
				$T->addLV($key.":", "<select name=\"$value\" id=\"$value\">$spalten</select>");
				
				continue;
			}
			
			
			for($i=0;$i<130;$i++){
				if(isset($_SESSION["import1stLine"]) AND !isset($_SESSION["import1stLine"][$i]))
					continue;

				$selected = false;
				if(isset($_SESSION["import1stLine"]) AND $_SESSION["import1stLine"][$i] == $key)
					$selected = true;

				$spalten .= "<option value=\"$i\" ".($selected ? "selected=\"selected\"" : "").">Spalte ".(isset($_SESSION["import1stLine"]) ? $_SESSION["import1stLine"][$i] : $i+1)."</option>";
			}

			
			if(isset($v[$value."_append"])){
				$spalten .= "<optgroup label=\"Vorgaben\">";
				foreach($v[$value."_append"] AS $ID => $label)
					$spalten .= "<option value=\"$ID\">$label</option>";
				$spalten .= "</optgroup>";
			}
			
			$T->addLV($key.":", "<select name=\"$value\" id=\"$value\">$spalten</select>".(isset($d[$value]) ? "<br>".$d[$value] : ""));
		}
		$B = new Button("Jetzt\nimportieren", "./open3A/Import/Import.png");
		$B->style("margin:10px;float:right;");
		$B->doBefore("if(confirm('Sollen die Daten jetzt importiert werden?')) %AFTER");
		$B->popup("", "Jetzt importieren", "Import", "-1", "import", array("joinFormFields('importForm')"), "MyImportAlgorithm;-", "{width:600, blackout:true}");
		#$B->loading();
		#$B->onclick("if(confirm('Sollen die Daten jetzt importiert werden?')) saveClass($('importToPlugin').value.replace(/GUI/g,''), $('TempFileID').value, '', 'importForm');");
		
		/*$T->addRow(array("
					<input
						type=\"button\"
						onclick=\"\"
						value=\"Jetzt Importieren\"
					/>"));
		$T->addRowColspan(1, 2);*/
		
		echo $T.$B;
	}
	
	function getPreview($sep, $sepText, $startWithLine = 0, $endWithLine = 0, $codepage = "UTF-8", $firstLine = "false"){
		if($sep == "1")
			$sep = ",";
		
		if($sep == "2")
			$sep = ";";
		
		if($sep == "3")
			$sep = "	";
		
		if($sepText == "1")
			$sepText = "'";
		
		if($sepText == "2")
			$sepText = "\"";

		$lines = array();
		for($i = 0; $i < 30; $i++){
			$data = $this->getLine($sepText, $sep, $codepage);
			if($data === false)
				break;
			
			$lines[] = $data;
		}
		
		
		if($endWithLine == 0 OR $endWithLine == "")
			$endWithLine = count($lines)+10;
		
		if($firstLine == "true") {
			$_SESSION["import1stLine"] = $lines[0];
			if($startWithLine == 0) $startWithLine = 2;
		}
		else
			unset($_SESSION["import1stLine"]);
		$broken = false;
		$maxcols = 0;
		$html = "
		<style type=\"text/css\">
			.Cell {
				border-bottom-style:solid;
				border-bottom-width:1px;
				border-left-style:solid;
				border-left-width:1px;
			}
			
			.Nr {
				vertical-align:top;
				border-bottom-style:solid;
				border-bottom-width:1px;
			}
		</style>
		<table style=\"font-size:0.8em;\">
			<tr>%%%TOPCOLS%%%
			</tr>";
		
		for($i = 0; $i<count($lines); $i++){
			if(count($lines[$i]) > $maxcols)
				$maxcols = count($lines[$i]);
			
			if($i % 20 == 19) $html .= "
			<tr>%%%TOPCOLS%%%
			</tr>";
			
			$html .= "
			<tr>";
			$html .= "
				<td class=\"Nr\" style=\"".(($startWithLine > $i+1 OR $i+1 > $endWithLine) ? "color:grey;" : "")."\">".($i+1)."</td>";
			
			#if($i % 5 == 0) echo "Speicher GUI $i 1: ".Util::formatByte(memory_get_usage(true),2)."<br />";
			for($j = 0;$j<count($lines[$i]);$j++)
				$html .= "
				<td class=\"borderColor1 Cell\" style=\"".(($startWithLine > $i+1 OR $i+1 > $endWithLine) ? "color:grey;" : "")."\">".nl2br($lines[$i][$j])."</td>";
			$html .= "
			</tr>";
			
			if($i == 20) {
				$broken = true;
				break;
			}
			#if($i % 5 == 0) echo "Speicher GUI $i 2: ".Util::formatByte(memory_get_usage(true),2)."<br />";
		}
		$html .= "
		</table>";
		
		if($broken)
			$html .= "Aus Performanzgründen können nicht mehr als 20 Einträge angezeigt werden";
		
		$cols = "
				<th class=\"borderColor1 backgroundColor1\" style=\"vertical-align:top;border-bottom-style:solid;border-bottom-width:1px;\"></th>";
		for($i=0;$i<$maxcols;$i++)
			$cols .= "
				<th class=\"borderColor1 backgroundColor1\" style=\"vertical-align:top;border-bottom-style:solid;border-bottom-width:1px;border-left-style:solid;border-left-width:1px;\">".($i+1)."</th>";
		
		#echo "Speicher GUI: ".Util::formatByte(memory_get_usage(true),2)."<br />";
		$html = str_replace("%%%TOPCOLS%%%",$cols,$html);
		
		echo "<div style=\"width:600px;overflow:auto;height:400px;\">".$html."</div>";
	}
	
	public function import($data){
		parse_str($data, $pdata);
		
		$sep = "";
		$sepText = "";
		if($pdata["sep"] == "1")
			$sep = ",";
		
		if($pdata["sep"] == "2")
			$sep = ";";
		
		if($pdata["sep"] == "3")
			$sep = "	";
		
		if($pdata["sepText"] == "1")
			$sepText = "'";
		
		if($pdata["sepText"] == "2")
			$sepText = "\"";
		
		$file = $_SESSION["TempFiles"]->get($pdata["TempFileID"]);
		
		$count = 0;
		$handle = fopen($file->A("filename"), "r");
		while(fgetcsv($handle, 0, $sep, $sepText))
			$count++;
				
		fclose($handle);

		$bpsName = "lastImportedLine";
		
		$imported = BPS::getProperty("MyImportAlgorithm", $bpsName, $pdata["startLine"]);
		
		$C = $pdata["importToPlugin"];
		$C = new $C($pdata["TempFileID"]);
		
		$A = new stdClass();
		foreach($pdata AS $k => $v)
			$A->$k = $v;
		
		$A->startLine = $imported;
		$A->endLine = $A->startLine + 100;
			
		if($pdata["endLine"] != 0 AND $A->endLine > $pdata["endLine"])
			$A->endLine = $pdata["endLine"];

		$C->setA($A);
		
		$row = $C->saveMe(false);
		
		
		if($pdata["endLine"] != 0 AND $pdata["endLine"] < $count)
			$count = $pdata["endLine"];
		
		BPS::setProperty("MyImportAlgorithm", $bpsName, $imported + $row);
		
		if($imported + $row >= $count){
			BPS::unsetProperty("MyImportAlgorithm", $bpsName);

			$B = new Button("Import abgeschlossen", "bestaetigung", "icon");
			$B->style("float:left;margin-right:10px;");

			$BC = new Button("OK", "bestaetigung");
			$BC->style("float:right;margin:10px;");
			$BC->onclick(OnEvent::closePopup("Import"));
			
			$end = "<p>".$BC.$B."Der Import der Datei <b>".basename($file->A("filename"))."</b> wurde erfolgreich abgeschlossen.</p>";
		} else {
			$B = new Button("Import wird fortgesetzt", "navigation", "icon");
			$B->style("float:left;margin-right:10px;");

			$end = "<div style=\"width:".ceil((($imported + $row)/$count) * 100)."%;text-align:center;\" class=\"confirm\"><div style=\"padding:10px;\">".ceil((($imported + $row)/$count) * 100)."%</div></div>";
			$end .= "<p>".$B."Bitte haben Sie Geduld, während der Import durchgeführt wird.<br>".($imported + $row)."/$count</p>";

			$reload = OnEvent::script(OnEvent::rme($this, "import", array("'$data'"), "function(t){ \$j('#editDetailsContentImport').html(t.responseText); }"));
		}
			echo $end."<div style=\"clear:both;height:10px;\"></div>".$reload;
		
	}
}
?>