<?php
/**
* @version      $Id: admin_plugin_editor.php
* @package      Easyshop
* @copyright    Copyright (C) 2005 - 2011 TA-EDV
 * @license			proprietary
* @author       Richard Kammermayer <rk@ta-edv.de>
* Easyshop is a web shop system
 */

class admin_import_editor {
	private $base_object;
	private $config;
	private $layout_object;
	private $import_object;

	function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->layout_object = $layout_object;
		include './core/import.class.php';
		$this->import_object = new Import($base_object);
	}

	function run() {
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} else if (isset($_POST['action'])) {
			$action = $_POST['action'];
		} else {
			$action = false;
		}

		if (isset($_GET['id'])) {
			$id = $_GET['id'];
		} else if (isset($_POST['id'])) {
			$id = $_POST['id'];
		} else {
			$id = false;
		}

		if ($action == 'save') {
			$this->save();
		} else if ($action == 'upload_file') {
			$this->upload($id);
			$this->import_object->id = $id;
			$data = $this->import_object->get_data();
			$this->layout_object->assign('form_data', $data);
			$this->layout_object->assign('error', $this->import_object->error);
			return $this->layout_object->fetch('admin_import_editor.tpl');
		} else if ($action == 'delete') {
			$this->delete($id);
		} else if ($action == 'delete_logo') {
			$this->delete_logo($id);
		}
                else {
			// get object data
			if ($id) {
				$this->import_object->id = $id;
				$data = $this->import_object->get_data();
				$this->layout_object->assign('form_data', $data);
			}
                    $error = isset($this->import_object->error) ? $this->import_object->error : '';
                    $this->layout_object->assign('error', $error);
			return $this->layout_object->fetch('admin_import_editor.tpl');
		}
	}

	private function upload($id) {
		$log_object = Logger::get_instance();
		if (!$log_object) {
			// Fallback, wenn Logger nicht verfügbar ist
			$log_object = new class {
				public function info($type, $message) { error_log("[$type] $message"); }
				public function error($type, $message) { error_log("ERROR[$type] $message"); }
			};
		}
		$log_object->info('fileupload','Starte Upload-Prozess');
	
		header('Content-Type: application/json');
	
		try {
			if (!$id) {
				throw new Exception('Keine ID angegeben');
			}
	
			$temp_file = $_FILES['Filedata']['tmp_name'];
			if ($temp_file == '') {
				throw new Exception('Keine Datei hochgeladen');
			}
	
			// Validiere Datei
			$file_info = pathinfo($_FILES['Filedata']['name']);
			if (strtolower($file_info['extension']) !== 'csv') {
				throw new Exception('Nur CSV-Dateien sind erlaubt');
			}
	
			if ($_FILES['Filedata']['size'] > 5 * 1024 * 1024) {
				throw new Exception('Datei ist zu groß (max. 5MB)');
			}
	
			// Speichere die Datei
				$result = $this->import_object->save_file($id, $temp_file);
			if (!$result) {
				throw new Exception('Fehler beim Speichern der Datei');
			}

			// Hole Import-Konfiguration aus der DB
			$sql = "SELECT import_filter, post_process_case FROM import WHERE id = ?";
			$stmt = $this->base_object->db->prepare($sql);
			$stmt->bind_param('i', $id);
			$stmt->execute();
			
			// Initialisiere Variablen
			$import_filter = '';
			$post_process_case = '';
			
			$stmt->bind_result($import_filter, $post_process_case);
			$stmt->fetch();
			$stmt->close();
	
			// Sicherheitsprüfung
			$allowed_scripts = ['preisupdate.py', 'sdbimport.py'];
			if (!in_array($import_filter, $allowed_scripts)) {
				throw new Exception("Unbekanntes Importscript!");
				}
	
			$python_script = dirname(__FILE__) . '/import/' . $import_filter;
			$uploaded_file = './tmp/import/'.basename($_FILES['Filedata']['name']);
	
			$command = "python3 {$python_script} {$uploaded_file} 2>&1";
			$output = [];
			$return_var = 0;
	
			exec($command, $output, $return_var);
			$log_object->info('python_output', implode("\n", $output));
	
			if ($return_var !== 0) {
				throw new Exception('Fehler beim Ausführen des Python-Scripts: ' . implode("\n", $output));
			}
	
			// Post-Processing
			$updated_count = 0;
			switch ($post_process_case) {
				case 'update_prices':
					foreach ($output as $line) {
						if (strpos($line, "eindeutige Artikel verarbeitet") !== false) {
							if (preg_match('/Insgesamt (\d+) eindeutige/', $line, $matches)) {
								$updated_count = intval($matches[1]);
								break;
							}
						}
					}
					break;
	
				case 'update_sdb_count':
					$updated_count = count($output); // oder smarter
					break;
	
				default:
					$log_object->info('postprocess', "Kein Post-Processing definiert für Fall: $post_process_case");
			}
	
			// Aktualisiere Import-Datum und Anzahl
			$sql = "UPDATE import SET last_import_date = NOW(), count_imported_items = ? WHERE id = ?";
			$stmt = $this->base_object->db->prepare($sql);
			$stmt->bind_param('ii', $updated_count, $id);
			$stmt->execute();
	
			// Datei löschen
			if (file_exists($uploaded_file)) {
				unlink($uploaded_file);
			}
	
			// Erfolgreiche Antwort
			$this->layout_object->assign('info_message', 'CSV-Datei erfolgreich importiert!');
			die(json_encode([
				'status' => 'success', 
				'message' => "Import erfolgreich. {$updated_count} Datensätze verarbeitet."
			]));
	
		} catch (Exception $e) {
			$log_object->error('upload_error', $e->getMessage());
			$this->layout_object->assign('error_message', $e->getMessage());
	
			$uploaded_file = './tmp/import/'.basename($_FILES['Filedata']['name']);
			if (file_exists($uploaded_file)) {
				unlink($uploaded_file);
			}
	
			die(json_encode([
				'status' => 'error', 
				'message' => $e->getMessage()
			]));
			}
		}

	private function save() {
		// Implementierung der save-Methode
		// Hier können Sie die Logik zum Speichern der Import-Daten hinzufügen
		$this->layout_object->assign('info_message', 'Import-Daten gespeichert.');
		return $this->layout_object->fetch('admin_import_editor.tpl');
	}

	private function delete($id) {
		// Implementierung der delete-Methode
		$this->import_object->set_object_property('id', $id);
		$this->import_object->delete();
		$this->layout_object->assign('info_message', 'Import gelöscht.');
		return $this->layout_object->fetch('admin_import_editor.tpl');
	}

	private function delete_logo($id) {
		// Implementierung der delete_logo-Methode
		$this->import_object->set_object_property('id', $id);
		// Hier können Sie die Logik zum Löschen des Logos hinzufügen
		$this->layout_object->assign('info_message', 'Logo gelöscht.');
		return $this->layout_object->fetch('admin_import_editor.tpl');
	}
}

