<?php
	require_once("config/connect.php");
	require_once("config/pageConfig.php");
	require_once("global_functions.php");
	check_login('', '', 'ENABLERKEY_ADMIN_DATEN_IMPORT');
	$message="";
	
	register_shutdown_function("importTimeoutError");
	
	
	if(isset($_POST['dataImputForm'])) {
		
		$bruttoSwitch=true;
		if(!isset($_POST['csvBruttoSwitch'])){	$bruttoSwitch=false;			}
		
		$target_dir = "uploads/imports/";
			$target_file = $target_dir .date('Ymd_H-i-s')."_".basename($_FILES["fileToUpload"]["name"]);
			$uploadOk = 1;
			$fSizeLimit=1500000;				#	500000
			$fSize=$_FILES["fileToUpload"]["size"];
			$fType=pathinfo($target_file,PATHINFO_EXTENSION );
			
			if(strtolower(pathinfo($target_file,PATHINFO_EXTENSION )) == 'csv' && $_FILES["fileToUpload"]["size"] < $fSizeLimit){

				 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
					$message.="Die Datei ". $target_file. " wurde hochgeladen.<br />";					
				} else {
					$message.="Fehler beim hochladen der Datei !!!<br />";
				}
				
				if($fSize > 300000 && $fSize <= 600000) set_time_limit(120);
				else if($fSize > 600000 && $fSize <= 900000) set_time_limit(180);
				else if($fSize > 900000 && $fSize <= 1500000) set_time_limit(240);
							
				$ipSuccess=importFromCsv($target_file, 'productsImport', ';', false, $bruttoSwitch );
		
				set_time_limit(30);
				if(is_array($ipSuccess) ) {
					$message='';
					print_r($ipSuccess);
				}
				else $message=preg_replace('/\n/', '<br />', $ipSuccess);
			}
			else $message.="Falscher Datei Type (".$fType.") oder Dateigröße (". $fSizeLimit ." / ".$fSize .") !!<br />Datei Import abgebrochen.<br />";
	}
	
	else if(isset($_POST['csbDatenFormForm'])){
			$bruttoSwitch=false;
			if(isset($_POST['csbBruttoSwitch']) && $_POST['csbBruttoSwitch'] == 'on') $bruttoSwitch=true;
			else $bruttoSwitch=false;
			writeLog(basename( __FILE__)." ". __LINE__ , "brutto: ".$bruttoSwitch." / ");
			
			$target_dir = "export_import/";
			$target_file = $target_dir .basename($_FILES["fileToUploadCsbSql"]["name"]);
			$uploadOk = 1;
			$fSizeLimit=5000000;
			$fSize=$_FILES["fileToUploadCsbSql"]["size"];
			$fType=pathinfo($target_file,PATHINFO_EXTENSION );
			
			if(strtolower(pathinfo($target_file,PATHINFO_EXTENSION )) == 'sql'){
				if (move_uploaded_file($_FILES["fileToUploadCsbSql"]["tmp_name"], $target_file)) {
					$message.="Die Datei ". $target_file. " wurde hochgeladen.<br />";
					require_once("export_import/csb.php");
					$writeCsv=exportCsbToFile($target_file);
					if (strpos(strtolower($writeCsv[1]), 'success') == 1){
						$writeCsv[1]=preg_replace(array('/\s/', '/success/i'), "", $writeCsv[1], 1);
						$message.=$writeCsv[1];
						
						$ipSuccess=importFromCsv($writeCsv[0], 'productsImport', ';', false, $bruttoSwitch );
						
						if(is_array($ipSuccess) ) {
							print_r($ipSuccess);
						}
						else $message.=$ipSuccess;
					}
				} else {
					$message.="Fehler beim hochladen der Datei !!!<br />";
				}
			}
			else $message.="Falscher Datei Type (".$fType.") oder Dateigröße (". $fSizeLimit ." / ".$fSize .") !!<br />Datei Import abgebrochen.<br />";
	}
	
	else if(isset($_POST['bildImputForm'])){
		$target_dir = "uploads/imports/";
			$target_file = $target_dir ."_".basename($_FILES["fileToUploadImg"]["name"]);				 
			$uploadOk = 1;
			$fSizeLimit=2000000;
			$fSize=$_FILES["fileToUploadImg"]["size"];
			$fType=pathinfo($target_file,PATHINFO_EXTENSION );
			
			if((strtolower(pathinfo($target_file, PATHINFO_EXTENSION )) == 'png' || strtolower(pathinfo($target_file, PATHINFO_EXTENSION )) == 'jpg'
						 || strtolower(pathinfo($target_file, PATHINFO_EXTENSION )) == 'jpeg')&& $_FILES["fileToUploadImg"]["size"] < $fSizeLimit){
				$logoTarget=false;
				if(isset($_POST['radioLogo'])){
						if($_POST['radioLogo']=='radioLogoBon')	$logoTarget='bonlogo';
						else if($_POST['radioLogo']=='radioLogoA4')		$logoTarget='a4logo';
						else{
							$logoTarget=false;
						}
				}
				
				
				if (move_uploaded_file($_FILES["fileToUploadImg"]["tmp_name"], $target_file) && $logoTarget != false) {
					$message.="Die Datei ". $target_file. " wurde hochgeladen.<br />";
									
					list($imgX, $imgY) = getimagesize($target_file);
					
					$checkImg=mysql_fetch_assoc(mysql_query("SELECT name FROM images WHERE name = '".$logoTarget."'"));
					if($checkImg['name'] == true){
						$storeImg=mysql_query("UPDATE images SET image ='". mysql_real_escape_string(file_get_contents($target_file))."', 
								imgx=".$imgX.", imgy=".$imgY." WHERE name = '".$logoTarget."' ");
					}
					else{
						$storeImg=mysql_query("INSERT INTO images SET image ='". mysql_real_escape_string(file_get_contents($target_file))."', 
							name = '".$logoTarget."', imgx=".$imgX.", imgy=".$imgY." ");
					}
					
					if(!$storeImg)$message.= "Datenbank Insert/Update Fehler. ".mysql_error()."<br />";
					else $message.= "Image Daten in die Datenbank geschrieben.<br />";

				} else {
					$message.="Fehler beim hochladen der Datei !!!<br />";
				}
			}
			else $message.="Falscher Datei Type (".$fType.") oder Dateigröße (". $fSizeLimit ." / ".$fSize .") !!<br />Datei Import abgebrochen.<br />";
	}
	
	else if(isset($_POST['a4TemplImputForm'])){
			$target_dir = "docs/auto_backup/";
			$target_file = $target_dir ."_".basename($_FILES["fileToUploadSqlTempl"]["name"]);				 
			$uploadOk = 1;
			$fSizeLimit=500000;
			$fSize=$_FILES["fileToUploadSqlTempl"]["size"];
			$fType=pathinfo($target_file,PATHINFO_EXTENSION );
			
			if(strtolower(pathinfo($target_file, PATHINFO_EXTENSION )) == 'sql' && $_FILES["fileToUploadSqlTempl"]["size"] < $fSizeLimit){
				if (move_uploaded_file($_FILES["fileToUploadSqlTempl"]["tmp_name"], $target_file)) {
					$message.="Die Datei ". $target_file. " wurde hochgeladen.<br />";
					
					$dataPath=urldecode(AUTOMATISCH_BACKUP_PFAD);	
					$filename=$target_file;
				
					$checkLocation=getenv("HOMEPATH");
					if(preg_match("/users\\\kp_/i", $checkLocation)){
						$command="e:\\Programme\\xampp\\mysql\\bin\\mysql --user=".SQL_USER." --password=".SQL_PW." ".SQL_DB." < ".$filename." ";	
					}
					else {
						$command="c:\\xampp\\mysql\\bin\\mysql --user=".SQL_USER." --password=".SQL_PW." ".SQL_DB." < ".$filename." ";
					}
					
					$output=array();
					
					exec($command, $output, $error_code);
					if($error_code == 0) $message= "Funktion importiert.";
					else $message.="Fehler ".$error_code.", beim Import aufgetreten.<br />";
					
					
				} else {
					$message.="Fehler beim hochladen der Datei !!!<br />";
				}
				
			
			
			}
			else $message.="Falscher Datei Type (".$fType.") oder Dateigröße (". $fSizeLimit ." / ".$fSize .") !!<br />Datei Import abgebrochen.<br />";
	}
	
		$csvImportInfoTxt="Ist Brutto gesetzt werden die Preise aus der CSV Import Datei als Bruttopreise importiert, wenn nicht gesetzt als Nettopreise";
		$csbImportInfoTxt="Ist Brutto gesetzt werden die Preise aus dem CSB Import als Bruttopreise importiert, wenn nicht gesetzt als Nettopreise";
	
	
?>
<!DOCTYPE HTML>
<html>
	<head>
		<title>SITPOS Datenimport</title>
		<?php 	echo META_DATA_ADMIN;
				echo PAGE_CACHE_OFF; ?>
		<style type="text/css">
			<?php include 'include/main.css'; ?>
			<?php include 'include/menue.css'; ?>
			/*
			*/
			#exportCSVform {
				position: relative;
				width: 97%;
				margin: 12px auto 10px;
				padding: 5px 4px;
				border: silver 1px solid;
				border-radius: 5px;
			}

		</style>
		<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css">

		<script>
		$(document).ready(function() {
			$('#exportCSVbutton').click(function () {

				$.post("ajax_funktionen.php", {funktion: "get_products"}, function(response) {
					console.log((response)); 
					let csvContent = "";
					response = JSON.parse(response);

					let headers = response.shift();

					headers.forEach(function(entry) {
						csvContent += entry + ";";
					});
					csvContent = csvContent.substring(0, csvContent.length - 1);
					csvContent += "\r\n";
					
					response.forEach(function(entry) {
						for(let key in entry) {
							csvContent += entry[key] + ";";
						}
						csvContent = csvContent.substring(0, csvContent.length - 1);
						csvContent += "\r\n";
					});
					
					let encodedUri = "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent);
            
        	    	let link = document.createElement("a");
        	    	link.setAttribute("href", encodedUri);
        	    	link.setAttribute("download", "importliste.csv");
        	    	document.body.appendChild(link);
alert(link);
	  		    	link.click();

				});

				/*let csvContent = "";
            	tableData.forEach(function(rowData) {
            	    //let row = rowData.join(";");
            	    let row = rowData[0] + ";" + rowData[1] + ";" + (rowData[3]) + ";" + (rowData[4]) + ";"+ (rowData[5]);
            	    csvContent += row + "\r\n";
            	});
		
        	    let encodedUri = "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent);
            
        	    let link = document.createElement("a");
        	    link.setAttribute("href", encodedUri);
        	    link.setAttribute("download", "report_csv.csv");
        	    document.body.appendChild(link);

	  		    link.click();*/

 				
			});
		});
			
		</script>

	</head>
	<body >
		<div id="wrapper_admin" class="wrapper_admin">
			<div id="generalDialog"  ></div>
			<?php	menue_anzeigen();		?>
		<div class="cclear"></div>
			<div id="adminContent">
				<div class='dataImportContentDiv'>
					<h4 class="adminTxtHeaderH4">Produkt Daten Import</h4>
					<p class="adminTxt adminTxtUpload" >Die import Datei muss ein "csv" sein.</p>
					<form id="uploadForm" action="daten_import.php" method="post" enctype="multipart/form-data" 
							onSubmit="document.getElementById('uploadSubmitBut').setAttribute('disabled','disabled');">
						<input type="hidden" name="dataImputForm" />	
						Datei auswählen:
						<input type="file" name="fileToUpload" id="fileToUpload" />
						<label for="csvBruttoSwitch" >Brutto</label><input type="checkbox" id='csvBruttoSwitch' name='csvBruttoSwitch' value='on' checked />
						<button class="configInfoBut" type="button"
							onclick="openGeneralDialog('configInfo', 'Import Info, Brutto Button', '<p class=\'configDialogContent\' ><?php echo $csvImportInfoTxt; ?></p>', 'wrapper_admin');">i</button>
						
					<!--	<input type="submit" id="uploadSubmitBut" value="Datei importieren" name="submit" />	-->
						<button class="button button_groß orange ipSubmitBut" type="submit" id="uploadSubmitBut" value="Datei importieren" name="submit" >CSV importieren</button>
					</form>
					
					<h4 class="adminTxtHeaderH4">Bild, Logo Import</h4>
					<p class="adminTxt adminTxtUpload" >Das Bild muss ein png od. jpg/jpeg sein.
									
							</p>
						
					
					<form id="uploadFormImg" action="daten_import.php" method="post" enctype="multipart/form-data" 
							onSubmit="document.getElementById('uploadSubmiImgtBut').setAttribute('disabled','disabled');">
								<div style='position:relative; width:40%; margin:5px auto; border:blue 1px solid;'>
									<div class='floatL' ><label class='uploadRadioLabel' for="bonLogoRadio">Bon Logo</label>
											<input checked id="bonLogoRadio" type='radio' name='radioLogo' value="radioLogoBon" /></div>
									<div class='floatR' ><label class='uploadRadioLabel' for="a4LogoRadio">A4 Logo</label>
											<input id="a4LogoRadio" type='radio' name='radioLogo'  value="radioLogoA4" /></div><div class='cclear'></div>
								</div>
							
							
						<input type="hidden" name="bildImputForm" />	
						Datei auswählen:
						<input type="file" name="fileToUploadImg" id="fileToUploadImg" />
						
					<!--	<input type="submit" id="uploadSubmitBut" value="Datei importieren" name="submit" />	-->
						<button class="button button_groß orange ipSubmitBut" type="submit" id="uploadSubmiImgtBut" value="Datei importieren" name="submit" >Bilddatei importieren</button>
					</form>
					
					<h4 class="adminTxtHeaderH4">A4 Rechnung/Lieferschein Ausdruck Funktion importieren</h4>
					<p class="adminTxt adminTxtUpload" >Die Datei muss eine sql Datei sein.</p>
					
					<form id="uploadFormA4Template" action="daten_import.php" method="post" enctype="multipart/form-data" 
							onSubmit="document.getElementById('uploadSubmitTemplateBut').setAttribute('disabled','disabled');">
						
						<input type="hidden" name="a4TemplImputForm" />
						Datei Auswählen:
						<input type="file" name="fileToUploadSqlTempl" id="fileToUploadSqlTempl" />
						<button class="button button_groß orange ipSubmitBut" type="submit" id="uploadSubmitTemplateBut" value="Datei importieren" name="submit" >Funktion importieren</button>
						
					</form>
										
					<h4 class="adminTxtHeaderH4">CSB Daten importieren</h4>
					<p class="adminTxt adminTxtUpload" >Die Datei muss eine sql Datei sein.</p>
					
					<form id="uploadFormCSB" action="daten_import.php" method="post" enctype="multipart/form-data" 
							onSubmit="document.getElementById('uploadSubmitCSB_But').setAttribute('disabled','disabled');">
						<input type="hidden" name="csbDatenFormForm" />
						Datei Auswählen:
						<input type="file" name="fileToUploadCsbSql" id="fileToUploadCsbSql" />
						<label for="csbBruttoSwitch" >Brutto</label><input type="checkbox" id='csbBruttoSwitch' name='csbBruttoSwitch' checked />
						<button class="configInfoBut" type="button"
							onclick="openGeneralDialog('configInfo', 'Import Info, Brutto Button', '<p class=\'configDialogContent\' ><?php echo $csbImportInfoTyt; ?></p>', 'wrapper_admin');">i</button>
						<button class="button button_groß orange ipSubmitBut" type="submit" id="uploadSubmitCSB_But" 
							value="Datei importieren" name="submit" >CSB importieren</button>
					</form>

					<h4 class="adminTxtHeaderH4">Artikelstamm exportieren</h4>
					<p class="adminTxt adminTxtUpload" >Es wird eine CSV Datei erstellt.</p>

					<form id="exportCSVform" method="post" enctype="multipart/form-data" onsubmit="return false;" >
						<input type="hidden" name="exportCSV" />
						<input type="file" name="fileToUploadCsbSql" id="fileToUploadCsbSql" style="visibility: hidden;"  />
						<button class="button button_groß orange ipSubmitBut" id="exportCSVbutton" 
							value="Daten exportieren" name="submit"  >Daten exportieren</button>
						
					</form>
					
					<div id="uploadMessage">
						<?php echo $message; ?>
					</div> 
				
				
				</div>
			</div>
		</div>

	</body>
</html>