<?php

$log_object = Logger::get_instance();

$row = 0;
if (($handle = fopen(ROOT_DIR.'tmp/import/'.basename($_FILES['Filedata']['name']), "r")) !== FALSE) {
	$navids = array();
	while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
		$row++;
		if ($row != 1) {
			// löschen mit navisionid und orginal-nr
			if (strlen($data[4]) == 0) {
				$sql = "DELETE FROM passendwie where bestellcode='".$data[3]."' AND navisionid=".$data[0];
			} else if (strlen($data[4]) == 1) { // datensatz hinzufügen
				$sql = "INSERT INTO passendwie (navisionid, vertreiber, bestellcode) VALUES ('".$data[0]."', '".utf8_encode($data[2])."', '".$data[3]."')";
				//$sql = "REPLACE INTO passendwie (navisionid, vertreiber, bestellcode) VALUES ('".$data[0]."', '".utf8_encode($data[2])."', '".$data[3]."')";
			} else if (strlen($data[4]) == 2) { // alle löschen mit navisionid
				$sql = "DELETE FROM passendwie where navisionid=".$data[0];
			}

			$this->db->query($sql);
			if ($this->db->error) {
				$log_object->info('Error in /core/imports/inseher_passendwie.inc.php', $this->db->error.', sql:'.$sql);
			}
			$navids[$data[0]] = 1;
		}
	}
	fclose($handle);
}

// update items
if ($navids) {
	foreach ($navids as $navid => $value) {
		// delete old data in item
		$sql = "UPDATE items set attribute_1='' WHERE attribute_7='".$navid."'";
		$this->db->query($sql);
		if ($this->db->error) {
			$log_object->info('Error in /core/imports/inseher_passendwie.inc.php', $this->db->error.', sql:'.$sql);
		}

		// get data for item
		$sql = "SELECT * FROM passendwie WHERE navisionid='".$navid."'";
		$result = $this->db->query($sql);
		if ($this->db->error) {
			$log_object->info('Error in /core/imports/inseher_passendwie.inc.php', $this->db->error.', sql:'.$sql);
		}
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}
		// write data to tiem
		foreach ($data as $object) {
			$content ='<p>';
			$content .= '<b>'.$object->vertreiber.'</b>';
			if ($object->bestellcode) {
				$content .= '<br>'.$object->bestellcode;
			}
			$content .='</p>';
			$sql = "
				UPDATE items
				SET
					attribute_1=CONCAT_WS('', attribute_1, '".$this->db->real_escape_string($content)."')
				WHERE attribute_7='".$navid."'
			";
			$this->db->query($sql);
			if ($this->db->error) {
				$log_object->info('Error in /core/imports/inseher_passendwie.inc.php', $this->db->error.', sql:'.$sql);
			}
		}
	}
}

?>			