<?php

	/**
	 * Modul für die verschiedenen Export Profile
	 */
	class wpsg_mod_export extends wpsg_mod_basic 
	{
		
		var $lizenz = 1;
		var $id = 300;
		var $inline = true;
		
		/** Hier sind alle möglichen Typen drin, wird von loadFields gefüllt */
		var $fields = array();
		
		/** Array für die möglichen Format Umwandlungen */
		var $arFormats = array();
		
		var $arCache = array();
		
		/**
		 * Costructor
		 */
		public function __construct()
		{ 
			
			/*
			$data = @unserialize('a:6:{s:8:"filename";s:17:"bestellexport.csv";s:9:"separator";s:1:";";s:7:"oneline";s:1:"1";s:3:"iso";s:1:"1";s:16:"firstlinecolname";s:1:"1";s:6:"fields";a:35:{i:0;a:3:{s:4:"name";s:3:"OID";s:5:"value";s:8:"order_id";s:6:"format";s:1:"0";}i:1;a:2:{s:4:"name";s:3:"KID";s:5:"value";s:8:"kunde_id";}i:2;a:2:{s:4:"name";s:3:"RNR";s:5:"value";s:11:"rechnung_nr";}i:3;a:3:{s:4:"name";s:14:"Rechnungsdatum";s:5:"value";s:6:"rdatum";s:6:"format";s:3:"400";}i:4;a:2:{s:4:"name";s:6:"Status";s:5:"value";s:12:"order_status";}i:5;a:2:{s:4:"name";s:9:"Bezahlart";s:5:"value";s:20:"order_payment_method";}i:6;a:2:{s:4:"name";s:10:"Versandart";s:5:"value";s:21:"order_shipping_method";}i:7;a:2:{s:4:"name";s:4:"Name";s:5:"value";s:10:"kunde_name";}i:8;a:2:{s:4:"name";s:7:"Vorname";s:5:"value";s:13:"kunde_vorname";}i:9;a:3:{s:4:"name";s:12:"Bestelldatum";s:5:"value";s:11:"order_cdate";s:6:"format";s:3:"400";}i:10;a:3:{s:4:"name";s:11:"Gesamtpreis";s:5:"value";s:11:"order_price";s:6:"format";s:3:"200";}i:11;a:3:{s:4:"name";s:5:"Netto";s:5:"value";s:17:"order_price_netto";s:6:"format";s:3:"200";}i:12;a:2:{s:4:"name";s:9:"Kommentar";s:5:"value";s:15:"order_bemerkung";}i:15;a:2:{s:4:"name";s:5:"EMail";s:5:"value";s:11:"kunde_email";}i:16;a:2:{s:4:"name";s:8:"UStIdNr.";s:5:"value";s:11:"kunde_ustid";}i:17;a:2:{s:4:"name";s:5:"Firma";s:5:"value";s:11:"kunde_firma";}i:18;a:2:{s:4:"name";s:3:"Tel";s:5:"value";s:9:"kunde_tel";}i:19;a:2:{s:4:"name";s:3:"Fax";s:5:"value";s:9:"kunde_fax";}i:20;a:2:{s:4:"name";s:7:"Strasse";s:5:"value";s:13:"kunde_strasse";}i:21;a:2:{s:4:"name";s:3:"PLZ";s:5:"value";s:9:"kunde_plz";}i:22;a:2:{s:4:"name";s:3:"Ort";s:5:"value";s:9:"kunde_ort";}i:23;a:2:{s:4:"name";s:4:"Land";s:5:"value";s:10:"kunde_land";}i:24;a:2:{s:4:"name";s:20:"Versandadresse Firma";s:5:"value";s:11:"order_firma";}i:25;a:2:{s:4:"name";s:22:"Versandadresse Vorname";s:5:"value";s:13:"order_vorname";}i:26;a:2:{s:4:"name";s:19:"Versandadresse Name";s:5:"value";s:10:"order_name";}i:27;a:2:{s:4:"name";s:22:"Versandadresse Strasse";s:5:"value";s:13:"order_strasse";}i:28;a:2:{s:4:"name";s:18:"Versandadresse PLZ";s:5:"value";s:9:"order_plz";}i:29;a:2:{s:4:"name";s:18:"Versandadresse Ort";s:5:"value";s:9:"order_ort";}i:30;a:2:{s:4:"name";s:19:"Versandadresse Land";s:5:"value";s:10:"order_land";}i:31;a:2:{s:4:"name";s:26:"Name der Bank (Bankeinzug)";s:5:"value";s:11:"order_bname";}i:32;a:2:{s:4:"name";s:24:"Kontonummer (Bankeinzug)";s:5:"value";s:9:"order_bnr";}i:33;a:2:{s:4:"name";s:25:"BLZ der Bank (Bankeinzug)";s:5:"value";s:10:"order_bblz";}i:34;a:2:{s:4:"name";s:25:"Kontoinhaber (Bankeinzug)";s:5:"value";s:14:"order_binhaber";}i:35;a:2:{s:4:"name";s:2:"ip";s:5:"value";s:8:"order_ip";}i:36;a:2:{s:4:"name";s:9:"UserAgent";s:5:"value";s:15:"order_useragent";}}}');
			array_splice($data['fields'], 1, 0, array(array('name' => 'ONR', 'value' => 'order_onr', 'format' => 900)));
			array_splice($data['fields'], 3, 0, array(array('name' => 'KNR', 'value' => 'kunde_nr', 'format' => 900)));
			$data['fields'][18]['format'] = 900;
			$data['fields'][19]['format'] = 900;
			$data['fields'][21]['format'] = 900;
			$data['fields'][16]['format'] = 900;
			$data['fields'][28]['format'] = 900;
			$data['fields'][32]['format'] = 900;
			$data['fields'][33]['format'] = 900;
			$data['fields'][35]['format'] = 900;			
			wpsg_debug($data);die(serialize($data));			
			*/
			
			parent::__construct();
						
			$this->arFormats = array(
				0 => __('Unverändert', 'wpsg'),
				100 => __('Zahl (99.99)', 'wpsg'),
				200 => __('Zahl (99,99)', 'wpsg'),
				300 => __('Währung (99,99 €)', 'wpsg'),
				400 => __('Datum (TT.MM.YYYY)', 'wpsg'),
				500 => __('Zeit (hh:mm:ss)', 'wpsg'),
				600 => __('Datum und Zeit (TT.MM.YYYY hh:mm:ss)', 'wpsg'),
				700 => __('Benutzerdefiniert', 'wpsg'),
				800 => __('Text', 'wpsg'),
				900 => __('Text Excel 2007', 'wpsg')					
			);
			
			$this->name = __('Exportprofile', 'wpsg');
			$this->group = __('Sonstiges', 'wpsg');
			$this->desc = __('Ermöglicht es Produkte, Bestellungen und Kunden bezogen auf Bestellungen in verschiedene CSV Formate zu exportieren.', 'wpsg');

		} // public function __construct()
		
		public function install() 
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/*
		   	 * Tabelle für die Exportprofile
		   	 */
		   	$sql = "CREATE TABLE ".WPSG_TBL_EXPORTPROFILE." (
		   		id mediumint(9) NOT NULL AUTO_INCREMENT,
		   		name VARCHAR(255) NOT NULL,
		   		data LONGTEXT NOT NULL,
		   		PRIMARY KEY  (id)
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
		   	
		   	dbDelta($sql);
			
		   	// Standardmäßig einen Export vorgeben sollte keiner existieren
		   	$existsID1 = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '1'");
		   	
		   	if ($existsID1 <= 0)
		   	{
		   		
		   		$ins_data = array(
		   			"id" => 1,
		   			"name" => __("Bestellexport", "wpsg"),
		   			"data" => 'a:6:{s:8:"filename";s:17:"bestellexport.csv";s:9:"separator";s:1:";";s:7:"oneline";s:1:"1";s:3:"iso";s:1:"1";s:16:"firstlinecolname";s:1:"1";s:6:"fields";a:37:{i:0;a:3:{s:4:"name";s:3:"OID";s:5:"value";s:8:"order_id";s:6:"format";s:1:"0";}i:1;a:3:{s:4:"name";s:3:"ONR";s:5:"value";s:9:"order_onr";s:6:"format";i:900;}i:2;a:2:{s:4:"name";s:3:"KID";s:5:"value";s:8:"kunde_id";}i:3;a:3:{s:4:"name";s:3:"KNR";s:5:"value";s:8:"kunde_nr";s:6:"format";i:900;}i:4;a:2:{s:4:"name";s:3:"RNR";s:5:"value";s:11:"rechnung_nr";}i:5;a:3:{s:4:"name";s:14:"Rechnungsdatum";s:5:"value";s:6:"rdatum";s:6:"format";s:3:"400";}i:6;a:2:{s:4:"name";s:6:"Status";s:5:"value";s:12:"order_status";}i:7;a:2:{s:4:"name";s:9:"Bezahlart";s:5:"value";s:20:"order_payment_method";}i:8;a:2:{s:4:"name";s:10:"Versandart";s:5:"value";s:21:"order_shipping_method";}i:9;a:2:{s:4:"name";s:4:"Name";s:5:"value";s:10:"kunde_name";}i:10;a:2:{s:4:"name";s:7:"Vorname";s:5:"value";s:13:"kunde_vorname";}i:11;a:3:{s:4:"name";s:12:"Bestelldatum";s:5:"value";s:11:"order_cdate";s:6:"format";s:3:"400";}i:12;a:3:{s:4:"name";s:11:"Gesamtpreis";s:5:"value";s:11:"order_price";s:6:"format";s:3:"200";}i:13;a:3:{s:4:"name";s:5:"Netto";s:5:"value";s:17:"order_price_netto";s:6:"format";s:3:"200";}i:14;a:2:{s:4:"name";s:9:"Kommentar";s:5:"value";s:15:"order_bemerkung";}i:15;a:2:{s:4:"name";s:5:"EMail";s:5:"value";s:11:"kunde_email";}i:16;a:3:{s:4:"name";s:8:"UStIdNr.";s:5:"value";s:11:"kunde_ustid";s:6:"format";i:900;}i:17;a:2:{s:4:"name";s:5:"Firma";s:5:"value";s:11:"kunde_firma";}i:18;a:3:{s:4:"name";s:3:"Tel";s:5:"value";s:9:"kunde_tel";s:6:"format";i:900;}i:19;a:3:{s:4:"name";s:3:"Fax";s:5:"value";s:9:"kunde_fax";s:6:"format";i:900;}i:20;a:2:{s:4:"name";s:7:"Strasse";s:5:"value";s:13:"kunde_strasse";}i:21;a:3:{s:4:"name";s:3:"PLZ";s:5:"value";s:9:"kunde_plz";s:6:"format";i:900;}i:22;a:2:{s:4:"name";s:3:"Ort";s:5:"value";s:9:"kunde_ort";}i:23;a:2:{s:4:"name";s:4:"Land";s:5:"value";s:10:"kunde_land";}i:24;a:2:{s:4:"name";s:20:"Versandadresse Firma";s:5:"value";s:11:"order_firma";}i:25;a:2:{s:4:"name";s:22:"Versandadresse Vorname";s:5:"value";s:13:"order_vorname";}i:26;a:2:{s:4:"name";s:19:"Versandadresse Name";s:5:"value";s:10:"order_name";}i:27;a:2:{s:4:"name";s:22:"Versandadresse Strasse";s:5:"value";s:13:"order_strasse";}i:28;a:3:{s:4:"name";s:18:"Versandadresse PLZ";s:5:"value";s:9:"order_plz";s:6:"format";i:900;}i:29;a:2:{s:4:"name";s:18:"Versandadresse Ort";s:5:"value";s:9:"order_ort";}i:30;a:2:{s:4:"name";s:19:"Versandadresse Land";s:5:"value";s:10:"order_land";}i:31;a:2:{s:4:"name";s:26:"Name der Bank (Bankeinzug)";s:5:"value";s:11:"order_bname";}i:32;a:3:{s:4:"name";s:24:"IBAN Nummer (Bankeinzug)";s:5:"value";s:10:"order_iban";s:6:"format";i:900;}i:33;a:3:{s:4:"name";s:25:"BIC der Bank (Bankeinzug)";s:5:"value";s:9:"order_bic";s:6:"format";i:900;}i:34;a:2:{s:4:"name";s:25:"Kontoinhaber (Bankeinzug)";s:5:"value";s:14:"order_binhaber";}i:35;a:3:{s:4:"name";s:2:"ip";s:5:"value";s:8:"order_ip";s:6:"format";i:900;}i:36;a:2:{s:4:"name";s:9:"UserAgent";s:5:"value";s:15:"order_useragent";}}}'
		   		);
		   		
		   		// Standardexport anlegen
		   		$this->db->ImportQuery(WPSG_TBL_EXPORTPROFILE, $ins_data);
		   		
		   	}
		   	
		} // public function install() 
		
		public function settings_edit()
		{
									
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_export/settings_edit.phtml'); 
						
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			
		} // public function settings_save()
		
		public function profilList()
		{
		
			$this->shop->view['arProfile'] = $this->db->fetchAssoc("
				SELECT
					*
				FROM
					`".WPSG_TBL_EXPORTPROFILE."`
			");
			
			foreach ($this->shop->view['arProfile'] as $k => $v)
			{
				
				$this->shop->view['arProfile'][$k]['data'] = @unserialize($v['data']);
							
			}
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_export/profillist.phtml');
			
		} // public function profilList()
		
		public function handleExport()
		{
						
			$arProfile = explode(",", $_REQUEST['wpsg_mod_export_profile']);
			
			if (sizeof($arProfile) >= 1)
			{
				
				$this->loadFields();

				foreach ($arProfile as $profil_id)
				{
					
					$profil = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($profil_id)."'");
					$profil['data'] = @unserialize($profil['data']);
					$profil['filename'] = $profil['data']['filename'];
					
					$tmpfname = tempnam($this->getTmpFilePath(), "wpsg");
					
					$filehandler = fopen($tmpfname, 'w');
					
					// Kopf
					if ($profil['data']['firstlinecolname'] == '1')
					{
					
						$row = array();
						
						foreach ($profil['data']['fields'] as $f)
						{
							
							$row[] = $f['name'];
							
						}
						
						fputcsv($filehandler, $row, $profil['data']['separator']);
						
					}
					
					foreach ($this->shop->view['data'] as $d) 
					{
												
						$row = array();
						
						if ($profil['data']['oneline'] == '1')
						{
						
							foreach ($profil['data']['fields'] as $f) 
							{

								$row[] = $this->getValue($f, $profil['data']['separator'], $d['id']);
								
							}
							
							fputcsv($filehandler, $row, $profil['data']['separator']);
							
						}
						else 
						{
							
							$arProdukte = $this->db->fetchAssoc("
								SELECT 
									OP.`p_id`, 
									OP.`productkey`, 
									OP.`product_index`,
									OP.`id` AS `order_product_id`
								FROM 
									`".WPSG_TBL_ORDERPRODUCT."` AS OP 
								WHERE 
									OP.`o_id` = '".wpsg_q($d['id'])."'
							");
							
							foreach ($arProdukte as $p)
							{
							
								$row = array();
								
								foreach ($profil['data']['fields'] as $f)
								{

									$row[] = $this->getValue($f, $profil['data']['separator'], $d['id'], $p['p_id'], $p['product_index'], $p['productkey'], $p['order_product_id']);
																		
								}

								fputcsv($filehandler, $row, $profil['data']['separator']);
																	
							}
							
						}
	    				
					}
					
					fclose($filehandler);
					
					// In ISO wandeln
					if ($profil['data']['iso'] == '1')
					{
						
						file_put_contents($tmpfname, utf8_decode(file_get_contents($tmpfname)));
												
					}
					
					$arFiles[] = array(strval($profil['data']['filename']), $tmpfname);
					
				}
				
				if (sizeof($arFiles) == 1)
				{
					
					header("Content-Type: text/csv"); 
					header("Content-Disposition: attachment; filename=".$arFiles[0][0]); 
					header("Pragma: no-cache"); 
					header("Expires: 0"); 
					
					die(file_get_contents($arFiles[0][1]));
						
				}
				else if (sizeof($arFiles) > 1)
				{
					
					$zip = new ZipArchive();
					
					$tmpfname = tempnam($this->getTmpFilePath(), "wpsg").'.zip';			

					if ($zip->open($tmpfname, ZIPARCHIVE::CREATE) == true) 
					{
    
						foreach ($arFiles as $f)
						{
						
							$zip->addFile($f[1], $f[0]);
							
						}
						
						$zip->close();
						
						header("Content-Type: application/octet-stream"); 
						header("Content-Disposition: attachment; filename=export.zip"); 
						header("Pragma: no-cache"); 
						header("Expires: 0"); 
						
						die(file_get_contents($tmpfname));
						
					}
					else
					{
						
						die(__('Konnte Zip Archiv nicht erstellen!', 'wpsg'));
						
					}
					
				}
				
				return true;
				
			}
			
			return false;			
			
		} // public function handleExport()
		
		public function produkt_index_head()
		{

			$this->shop->view['wpsg_mod_export']['arProfile'] = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."`");
			
			if (sizeof($this->shop->view['wpsg_mod_export']['arProfile']) <= 0) return;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_export/produkt_index_head.phtml');
			
		} // public function produkt_index_head()
		 
		public function produkt_index_aftersearch()
		{
			
			$this->shop->view['wpsg_mod_export']['arProfile'] = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."`");
			
			if (sizeof($this->shop->view['wpsg_mod_export']['arProfile']) <= 0) return;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_export/produkt_index_aftersearch.phtml');
			
		} // public function produkt_index_aftersearch()
		
		public function be_ajax()
		{
			
			if ($_REQUEST['do'] == 'wpsg_mod_export_addProfil')
			{
				
				$this->db->ImportQuery(WPSG_TBL_EXPORTPROFILE, array(
					"name" => __('Neues Profil', 'wpsg'),
					"data" => serialize(array('separator' => ';')),
				));
				
				die($this->profilList());
				
			}
			else if ($_REQUEST['do'] == 'wpsg_mod_export_removeProfil')
			{
				
				$this->db->Query("DELETE FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($_REQUEST['profil'])."'");
				die($this->profilList());
				
			
			}
			else if ($_REQUEST['do'] == 'wpsg_mod_export_removeField')
			{
				
				$data = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($_REQUEST['profil'])."'");
				$data['data'] = @unserialize($data['data']);
		 
				unset($data['data']['fields'][$_REQUEST['field_key']]);
				
				$data['data'] = @serialize($data['data']);				
				$this->db->UpdateQuery(WPSG_TBL_EXPORTPROFILE, $data, "`id` = '".wpsg_q($_REQUEST['profil'])."'");
				
				die("1");
				
			}
			else if ($_REQUEST['do'] == 'wpsg_mod_export_profilSwitch')
			{
				
				$this->loadFields();
				
				$this->shop->view['profil'] = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($_REQUEST['profil'])."'");
				 
				$this->shop->view['profil']['data'] = unserialize($this->shop->view['profil']['data']);
											
				foreach ((array)$this->shop->view['profil']['data']['fields'] as $k => $v)
				{
					if (!isset($v['format'])) $this->shop->view['profil']['data']['fields'][$k]['format'] = 0;
				}
				
				$this->shop->view['arFormats'] = $this->arFormats;
				$this->shop->view['fields'] = $this->fields;
				
				die($this->shop->render(WPSG_PATH_VIEW.'/mods/mod_export/profil.phtml'));
				
			}
			else if ($_REQUEST['do'] == 'inlinedit')
			{
				
				$data = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($_REQUEST['profil_id'])."'");
				$data['data'] = @unserialize($data['data']);
				
				switch ($_REQUEST['field'])
				{
					
					case 'name': $data['name'] = wpsg_q($_REQUEST['value']); break;
					case 'filename': $data['data']['filename'] = wpsg_q($_REQUEST['value']); break;
					case 'separator': $data['data']['separator'] = wpsg_q($_REQUEST['value']); break;
					case 'oneline': $data['data']['oneline'] = wpsg_q($_REQUEST['value']); break;
					case 'firstlinecolname': $data['data']['firstlinecolname'] = wpsg_q($_REQUEST['value']); break;
					case 'iso': $data['data']['iso'] = wpsg_q($_REQUEST['value']); break;
					
				}
				
				if (preg_match('/fieldname_/', $_REQUEST['field']))				    
				{
					
					$f_id = substr($_REQUEST['field'], 10);
					$data['data']['fields'][$f_id]['name'] = $_REQUEST['value'];
					
				}
				
				if (preg_match('/fieldformat_/', $_REQUEST['field']))
				{
					
					$f_id = substr($_REQUEST['field'], 12);
					$data['data']['fields'][$f_id]['format'] = $_REQUEST['value'];
					$_REQUEST['value'] = $this->arFormats[$_REQUEST['value']];
					
				}
				
				if (preg_match('/fielduserformat_/', $_REQUEST['field']))
				{
					
					$f_id = substr($_REQUEST['field'], 16);					
					$data['data']['fields'][$f_id]['userformat'] = $_REQUEST['value'];
										
				}
				
				if (preg_match('/fieldtyp_/', $_REQUEST['field']))
				{
					
					$f_id = substr($_REQUEST['field'], 9);
					$data['data']['fields'][$f_id]['value'] = $_REQUEST['value'];
					$this->loadFields();
					$_REQUEST['value'] = $this->getFieldName($_REQUEST['value']);
					
				}
				
				$data['data'] = @serialize($data['data']);				
				$this->db->UpdateQuery(WPSG_TBL_EXPORTPROFILE, $data, "`id` = '".wpsg_q($_REQUEST['profil_id'])."'");
				
				die($_REQUEST['value']);
				
			}
			else if ($_REQUEST['do'] == 'musterupload')
			{
				
				$data = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_EXPORTPROFILE."` WHERE `id` = '".wpsg_q($_REQUEST['profil_id'])."'");
				$data['data'] = @unserialize($data['data']);
				
				if (!isset($data['data']['separator']) || strlen($data['data']['separator']) < 1) 
				{
					
					$this->shop->addBackendError(__('Ungültiges Trennzeichen angegeben!', 'wpsg'));
					die('<script type="text/javascript">parent.wpsg_mod_export_profilSwitch();</script>');
						
				}
				
				if ($data['data']['iso'] == '1')
				{

					$strFileContent = wpsg_toUtf8(file_get_contents($_FILES['wpsg_mod_export_muster']['tmp_name']));
					
				}
				else
				{
				
					$strFileContent = file_get_contents($_FILES['wpsg_mod_export_muster']['tmp_name']);
					
				}

				// Alles nach erstem Zeilenumbruch entfernen
				$strFileContent = preg_replace("/\r(.*)/s", "", $strFileContent);

				$arFields = explode($data['data']['separator'], $strFileContent);
				
				if (sizeof($arFields) > 1) 
				{
					
					// Neue Felder gefundne, verwirft die alten
					$data['data']['fields'] = array();
					
					foreach ($arFields as $f) 
					{

						if (preg_match('/^\"(.*)\"$/', $f)) $f = substr($f, 1, strlen($f) - 2);
						
						$data['data']['fields'][] = array(
							'name' => $f,
							'value' => '-1'
						);							
						
					}
				
				}
				
				$data['data'] = @serialize($data['data']);
						 
				$data = wpsg_q($data);
				 
				$this->db->UpdateQuery(WPSG_TBL_EXPORTPROFILE, $data, "`id` = '".wpsg_q($_REQUEST['profil_id'])."'");
				 
				$this->shop->addBackendMessage(__('Muster Datei erfolgreich verarbeitet.', 'wpsg'));
				
				die('<script type="text/javascript">parent.wpsg_mod_export_profilSwitch();</script>');
				
			}
		
		} // public function be_ajax()
		
		private function getFieldName($field_key)
		{
			
			foreach ($this->fields as $fieldgroup)
			{
				
				foreach ($fieldgroup['fields'] as $key => $fieldname)
				{
					
					if ($key == $field_key) return $fieldname;
					
				}
				
			}
			
		} // private function getFieldName($field_key)
		
		private function loadFields()
		{
			
			$this->fields = array(	
				5 => array(
					'name' => __('Allgemein', 'wpsg'),
					'fields' => array(
						'allgemein_empty' => __('Leer', 'wpsg'),
						//'allgemein_statisch' => __('Statisch', 'wpsg'),
						'allgemein_currency' => __('Währung', 'wpsg')
					)
				),
				10 => array(
					'name' => __('Bestellung', 'wpsg'),
					'fields' => array(
						'order_id' => __('BestellID', 'wpsg'),
						'order_cdate' => __('Erstellungsdatum', 'wpsg'),
						'order_onr' => __('Bestellnummer', 'wpsg'),
						'order_bemerkung' => __('Bemerkung Kunde', 'wpsg'),
						'order_price' => __('Bestellsumme', 'wpsg'),
						'order_price_netto' => __('Bestellsumme (Netto)', 'wpsg'),
						'order_shipping' => __('Versandkosten', 'wpsg'),
						'order_payment' => __('Kosten Bezahlmethode', 'wpsg'),
						'order_useragent' => __('UserAgent', 'wpsg'),
						'order_ip' => __('IP Adresse', 'wpsg'),						
						'order_vorname' => __('Lieferadresse Vorname', 'wpsg'),
						'order_name' => __('Lieferadresse Name', 'wpsg'),
						'order_firma' => __('Lieferadresse Firma', 'wpsg'),
						'order_strasse' => __('Lieferadresse Straße', 'wpsg'),
						'order_plz' => __('Lieferadresse PLZ', 'wpsg'),
						'order_ort' => __('Lieferadresse Ort', 'wpsg'),
						'order_land' => __('Lieferadresse Land (Name)', 'wpsg'),
						'order_land_krzl' => __('Lieferadresse Land (Kürzel)', 'wpsg'),
						//'order_hausnr' => __('Lieferadresse Hausnummer', 'wpsg'),
						'order_payment_method' => __('Name der Zahlart', 'wpsg'),
						'order_shipping_method' => __('Name der Versandart', 'wpsg'),
						'order_count' => __('Anzahl Produkte', 'wpsg'),
						'order_bname' => __('Name der Bank (Bankeinzug)', 'wpsg'),
						'order_bblz' => __('BLZ der Bank (Bankeinzug)', 'wpsg'),
						'order_bic' => __('BIC der Bank (Bankeinzug)', 'wpsg'),
						'order_binhaber' => __('Kontoinhaber (Bankeinzug)', 'wpsg'),
						'order_bnr' => __('Kontonummer (Bankeinzug)', 'wpsg'),
						'order_iban' => __('IBAN Nummer (Bankeinzug)', 'wpsg'),						
						'order_status' => __('Status der Bestellung', 'wpsg'),
						'order_menge' => __('Anzahl an Artikeln', 'wpsg')			
					)
				),
				20 => array(
					'name' => __('Produkt', 'wpsg'),
					'fields' => array(
						'produkt_id' => __('ProduktID', 'wpsg'),
						'produkt_index' => __('Position', 'wpsg'),
						'produkt_name' => __('Produktname', 'wpsg'),
						'produkt_typ' => __('Produkttyp', 'wpsg'),
						'produkt_preis' => __('Produktpreis', 'wpsg'),
						'produkt_mwst' => __('Mehrwertsteuer', 'wpsg'),
						'produkt_feinheit' => __('Füllmengeneinheit', 'wpsg'),
						'produkt_fmenge' => __('Füllmenge', 'wpsg'),
						'produkt_beschreibung' => __('Beschreibung', 'wpsg'),
						'produkt_weight' => __('Gewicht', 'wpsg'),						 
						'produkt_anr' => __('Artikelnummer', 'wpsg'),
						'produkt_menge' => __('Anzahl', 'wpsg')
					)
				),
				30 => array(
					'name' => __('Kunden', 'wpsg'),
					'fields' => array(
						'kunde_id' => __('KundenID', 'wpsg'),
						'kunde_nr' => __('Kundennummer', 'wpsg'),
						'kunde_title' => __('Titel/Anrede', 'wpsg'),
						'kunde_firma' => __('Firma', 'wpsg'),
						'kunde_vorname' => __('Vorname', 'wpsg'),
						'kunde_name' => __('Name', 'wpsg'),
						'kunde_strasse' => __('Straße', 'wpsg'),
						//'kunde_hausnr' => __('Hausnummer', 'wpsg'),
						'kunde_ort' => __('Ort', 'wpsg'),
						'kunde_plz' => __('PLZ', 'wpsg'),
						'kunde_land' => __('Land (Name)', 'wpsg'),
						'kunde_land_krzl' => __('Land (Kürzel)', 'wpsg'),
						'kunde_tel' => __('Telefon', 'wpsg'),
						'kunde_fax' => __('Faxnummer', 'wpsg'),
						'kunde_email' => __('E-Mail', 'wpsg'),
						'kunde_ustid' => __('Umsatzsteuernummer', 'wpsg'),
						'kunde_geb' => __('Geburtsdatum', 'wpsg')					
					)
				)
			);
			
			if ($this->shop->hasMod('wpsg_mod_rechnungen'))
			{
				
				$this->fields[11] = array(
					'name' => __('Rechnung', 'wpsg'),
					'fields' => array(
						'rechnung_nr' => __('Rechnungsnummer', 'wpsg'),
						'gutschrift_nr' => __('Rechnungskorrekturnummer', 'wpsg'),
						'rdatum' => __('Datum der Rechnung/Rechnungskorrektur', 'wpsg')
					) 
				);
				
			}
			
			// Gutscheinmodul
			if ($this->shop->hasMod('wpsg_mod_gutschein'))
			{
				
				$this->fields[10]['fields']['order_gutschein'] = __('Gutscheinnummer', 'wpsg');
				
			}
			
			// Bestellvariablen 
			if ($this->shop->hasMod('wpsg_mod_ordervars'))
			{
				
				$arOV = array();
				$arOrderVars = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_ORDERVARS."` WHERE `deleted` != '1' ORDER BY `name` ASC ");
				
				foreach ($arOrderVars as $ov)
				{
					
					$arOV['ov_'.$ov['id']] = $ov['name'];	
					
				}
				
				if (is_array($arOV) && sizeof($arOV) > 0)
				{
					
					$arOV = array(
						'name' => __('Bestellvariablen', 'wpsg'),
						'fields' => $arOV
					);
					
					$this->fields[12] = $arOV;
					
				}
				
			}			
			
			/* Produktvariablen */ 
			if ($this->shop->hasMod('wpsg_mod_productvars'))
			{
							
				$arPV = array();
				$arProduktVars = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_PRODUCTS_VARS."` ORDER BY `name` ");
				
				foreach ($arProduktVars as $pv)
				{
					
					$arPV['pv_'.$pv['id']] = $pv['name'];
					
				}
				
				if (is_array($arPV) && sizeof($arPV) > 0)
				{
					
					$arPV = array(
						'name' => __('Produktvariablen', 'wpsg'),
						'fields' => $arPV
					);
					
					$this->fields[21] = $arPV;
					
				}
				
			} 
			
			/* Produktattribute */
			if ($this->shop->hasMod('wpsg_mod_produktattribute'))
			{
				
				$arPA = array();
				$arProduktAttribute = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_AT."` ORDER BY `name` ");
				
				foreach ($arProduktAttribute as $pa)
				{
					
					$arPA['pa_'.$pa['id']] = $pa['name'];
					
				}
				
				if (is_array($arPA) && sizeof($arPA) > 0)
				{
					
					$arPA = array(
						'name' => __('Produktattribute', 'wpsg'),
						'fields' => $arPA
					);
					
					$this->fields[22] = $arPA;
					
				}
				
			}
								
			/* Kundenvariablen */
			$kv = $this->shop->loadPflichtFeldDaten();
			if (is_array($kv) && sizeof($kv) > 0 && sizeof($kv['custom']) > 0)
			{
				
				$arKV = array(); 
				foreach ($kv['custom'] as $kv_key => $kv)
				{
					
					$arKV['kv_'.$kv_key] = $kv['name'];
					
				}
				
				if (is_array($arKV) && sizeof($arKV) > 0)
				{
					
					$arKV = array(
						'name' => __('Kundenvariablen', 'wpsg'),
						'fields' => $arKV
					);
					
					$this->fields[31] = $arKV;
					
				}
				
			}
			
			$this->shop->callMods('wpsg_mod_export_loadFields', array(&$this->fields));
			
			ksort($this->fields);
			
		}
		
		public function getValue($f, $profil_separator, $o_id, $p_id = false, $product_index = 1, $productkey = false, $order_product_id = false)
		{
			
			$field_value = $f['value'];
			
			if (array_key_exists($o_id.'_'.$p_id, $this->arCache))
			{
				
				$order = $this->arCache[$o_id.'_'.$p_id]['order'];
				$produkt = $this->arCache[$o_id.'_'.$p_id]['produkt'];
				$kunde = $this->arCache[$o_id.'_'.$p_id]['kunde'];				
				
			}
			else
			{
			
				$order = $this->db->fetchRow("
					SELECT 
						O.*,
						L.`name` AS land,
						L.`kuerzel` AS land_krzl
					FROM
						`".WPSG_TBL_ORDER."` AS O
							LEFT JOIN `".WPSG_TBL_LAND."` AS L ON (O.`shipping_land` = L.`id`)
					WHERE
						O.`id` = '".wpsg_q($o_id)."'
				");
				
				// Anzahl an tatsächlich bestellten Artikeln
				$order['menge'] = $this->db->fetchOne("SELECT SUM(OP.`menge`) FROM `".WPSG_TBL_ORDERPRODUCT."` AS OP WHERE OP.`o_id` = '".wpsg_q($order['id'])."'");
				
				// Anzahl an Produkten in der Bestellung (Mengenunabhängig)
				$order['count'] = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_ORDERPRODUCT."` WHERE `o_id` = '".wpsg_q($order['id'])."'");
				
				$order['payment_method'] = $this->shop->arPayment[$order['type_payment']]['name'];
				$order['shipping_method'] = $this->shop->arShipping[$order['type_shipping']]['name'];
				
				$order['custom_data'] = unserialize($order['custom_data']);
				
				if ($this->shop->hasMod('wpsg_mod_rechnungen'))
				{
					
					$last_invoice = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order['id'])."' AND `rnr` != '' ORDER BY `datum` DESC LIMIT 1 ");
					$last_storno = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order['id'])."' AND `gnr` != '' ORDER BY `datum` DESC LIMIT 1 ");
					$last = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order['id'])."' ORDER BY `datum` DESC LIMIT 1 ");
					
					$order['gnr'] = '--';
					$order['rnr'] = '--';
					$order['rdatum'] = '--'; 
					
					if (wpsg_isSizedInt($last_invoice['id']))
					{
						
						$order['rnr'] = $last_invoice['rnr'];
						$order['rdatum'] = $last_invoice['datum'];
						
					}
					
					if (wpsg_isSizedInt($last_storno['id']) && $last['id'] === $last_storno['id'])
					{
						
						$order['gnr'] = $last_storno['gnr']; 
						$order['rdatum'] = $last_storno['datum'];
						
					}
										
				}
				
				/* Bestellvariablen */
				if ($this->shop->hasMod('wpsg_mod_ordervars'))
				{
					
					$order['bvars'] = @unserialize($order['bvars']);
					
				}
				
				/* Produktvariablen */
				if ($this->shop->hasMod('wpsg_mod_productvars'))
				{
					
					$order['pvars'] = @unserialize($order['pvars']);
					
				}
								
				$kunde = $this->db->fetchRow("
					SELECT
						K.*,
						L.`kuerzel` AS land_krzl,
						L.`name` AS land
					FROM
						`".WPSG_TBL_KU."` AS K
							LEFT JOIN `".WPSG_TBL_LAND."` AS L ON (K.`land` = L.`id`)
					WHERE
						K.`id` = '".wpsg_q($order['k_id'])."'
				");
				
				/* Kundenvariablen */
				$kunde['kv'] = @unserialize($kunde['custom']);
								
				if ($p_id == false)
				{
					
					$arProdukte = $this->db->fetchAssoc("
						SELECT
							P.*,
							OP.`mod_vp_varkey`,
							OP.`menge`,
							OP.`mwst_value` AS mwst_value,
							OP.`price` AS price 
						FROM
							`".WPSG_TBL_ORDERPRODUCT."` AS OP
								LEFT JOIN `".WPSG_TBL_PRODUCTS."` AS P ON (P.`id` = OP.`p_id`)
						WHERE
							OP.`o_id` = '".wpsg_q($o_id)."'
					");
					
					$produkt = array();
					
					foreach ($arProdukte as $p)
					{
					
						foreach ($p as $col_name => $col_value)
						{

							$produkt[$col_name][] = $col_value;
							
						}
						
					}

					foreach ($produkt as $col_name => $values)
					{
						
						if ($profil_separator == ',') $produkt[$col_name] = implode(";", $values);
						else $produkt[$col_name] = implode(",", $values);
						
					}
					
				}
				else
				{
					
					if (wpsg_isSizedInt($order_product_id))
					{
						
						$produkt = $this->db->fetchRow("
							SELECT
								P.*,
								OP.`mod_vp_varkey`,
								OP.`menge`,
								OP.`mwst_value` AS mwst_value,
								OP.`price` AS price
							FROM
								`".WPSG_TBL_ORDERPRODUCT."` AS OP
									LEFT JOIN `".WPSG_TBL_PRODUCTS."` AS P ON (P.`id` = OP.`p_id`)
							WHERE
								OP.`id` = '".wpsg_q($order_product_id)."'
						");
						
					}
					else
					{
						
						$produkt = $this->db->fetchRow("
							SELECT
								P.*,							
								OP.`mod_vp_varkey`,
								OP.`menge`,
								OP.`mwst_value` AS mwst_value,
								OP.`price` AS price
							FROM
								`".WPSG_TBL_PRODUCTS."` AS P
									LEFT JOIN `".WPSG_TBL_ORDERPRODUCT."` AS OP ON (P.`id` = OP.`p_id` AND OP.`o_id` = '".wpsg_q($order['id'])."')
							WHERE
								P.`id` = '".wpsg_q($p_id)."'
						");
						
					}
					
					/* Produktattribute */
					if ($this->shop->hasMod('wpsg_mod_produktattribute'))
					{
						
						$produkt['mod_attribute'] = $this->db->fetchAssocField("
							SELECT
								`a_id`, `value`
							FROM
								`".WPSG_TBL_PRODUCTS_AT."` AS PA
							WHERE
								PA.`p_id` = '".wpsg_q($produkt['id'])."'								
						", "a_id", "value");
						
					}
					
				}

				$this->arCache[$o_id.'_'.$p_id] = array(
					"order" => $order,
					"produkt" => $produkt,
					"kunde" => $kunde
				);
				
			}
			 
			switch ($field_value)
			{
				
				case 'allgemein_empty': $return = ''; break;
				case 'allgemein_statisch': $return = $f['static']; break;
				case 'allgemein_currency': $return = get_option('wpshopgermany_currency'); break; 
								
				case 'order_id': $return = $order['id']; break; 
				case 'order_cdate': 
					
					if (strtotime($order['cdate']) !== false)
					{
						$return = date('d.m.Y H:i:s', strtotime($order['cdate']));
					}
					else
					{
						$return = '--';
					}
					
					break;
				case 'order_onr': $return = $order['onr']; break;
				case 'order_bemerkung': $return = preg_replace('/\r\n|\r|\n/', ' ', $order['comment']); break;
				case 'order_price': 
					
					if (!is_array($order['custom_data']['basket']))
					{
						$return = wpsg_ff($order['price_gesamt']);	
					}
					else
					{					
						$return = wpsg_ff($order['custom_data']['basket']['sum']['preis_gesamt_brutto'], $this->shop->get_option('wpsg_currency'));
					}
					 
					break;
					
				case 'order_price_netto': 
					
					$return = wpsg_ff($order['custom_data']['basket']['sum']['preis_gesamt_netto'], $this->shop->get_option('wpsg_currency'));						
					
					break;
					
				case 'order_shipping': $return = number_format($order['price_shipping'], 2, ',', '.'); break;
				case 'order_payment': $return = number_format($order['price_payment'], 2, ',', '.'); break;	
				case 'order_useragent':	$return = $order['useragent']; break;
				case 'order_ip': $return = $order['ip']; break;	
				case 'order_vorname': $return = $order['shipping_vname']; break;
				case 'order_name': $return = $order['shipping_name']; break;
				case 'order_strasse': $return = $order['shipping_strasse']; break;
				case 'order_plz': $return = $order['shipping_plz']; break;
				case 'order_ort': $return = $order['shipping_ort']; break;
				case 'order_land': $return = $order['land']; break;
				case 'order_land_krzl': $return = $order['land_krzl']; break;
				case 'order_hausnr': $return = $order['shipping_hausnr']; break;
				case 'order_payment_method': $return = $order['payment_method']; break;
				case 'order_shipping_method': $return = $order['shipping_method']; break;				
				case 'order_count': $return = $order['count']; break;
				case 'order_firma': $return = $order['shipping_firma']; break;
				case 'order_status': $return = $this->shop->arStatus[$order['status']]; break;
				case 'order_bname': $return = $order['mod_autodebit_name']; break;
				case 'order_bblz': $return = $order['mod_autodebit_blz']; break;
				case 'order_binhaber': $return = $order['mod_autodebit_inhaber']; break;
				case 'order_menge': $return = $order['menge']; break;
				case 'order_bnr': $return = $order['mod_autodebit_knr']; break;
				case 'order_iban': $return = $order['mod_autodebit_iban']; break;
				case 'order_bic': $return = $order['mod_autodebit_bic']; break;
				case 'order_gutschein': 
					
					if ($order['gs_id'] > 0)
						$return = $this->db->fetchOne("SELECT `code` FROM `".WPSG_TBL_GUTSCHEIN."` WHERE `id` = '".wpsg_q($order['gs_id'])."'");
						
					break;
				
				case 'rechnung_nr': $return = $order['rnr']; break;
				case 'rechnungskorrektur_nr':
				case 'gutschrift_nr': 
					$return = $order['gnr']; break;
				case 'rdatum': 
					
					if (strtotime($order['rdatum']) !== false)
					{
						$return = date('d.m.Y H:i:s', strtotime($order['rdatum']));
					}
					else
					{
						$return = '--';
					} 
					
					break;				
								
				case 'produkt_id': $return = $produkt['id']; break;
				case 'produkt_index': $return = $product_index; break; 
				case 'produkt_name': $return = $produkt['name']; break;
				case 'produkt_typ': $return = $produkt['typ']; break;
				case 'produkt_preis': $return = number_format($produkt['preis'], 2, ',', '.');	break;
				case 'produkt_mwst': $return = $produkt['mwst_key']; break;
				case 'produkt_feinheit': $return = $produkt['feinheit']; break;
				case 'produkt_fmenge': $return = $produkt['fmenge']; break;
				case 'produkt_beschreibung': $return = $produkt['beschreibung']; break;
				case 'produkt_weight': $return = $produkt['weight']; break;
				case 'produkt_anr': $return = $produkt['anr']; break;
				case 'produkt_menge': $return = $produkt['menge']; break;
				
				case 'kunde_id': $return = $kunde['id']; break;
				case 'kunde_nr': $return = $kunde['knr']; break;
				case 'kunde_title': $return = $kunde['title']; break;
				case 'kunde_vorname': $return = $kunde['vname']; break;
				case 'kunde_firma': $return = $kunde['firma']; break;
				case 'kunde_name': $return = $kunde['name']; break;
				case 'kunde_strasse': $return = $kunde['strasse']; break;
				case 'kunde_hausnr': $return = $kunde['hausnr']; break;
				case 'kunde_ort': $return = $kunde['ort']; break;
				case 'kunde_plz': $return = $kunde['plz']; break;
				case 'kunde_land': $return = $kunde['land']; break;
				case 'kunde_land_krzl': $return = $kunde['land_krzl']; break;
				case 'kunde_tel': $return = $kunde['tel']; break;
				case 'kunde_fax': $return = $kunde['fax']; break;
				case 'kunde_email': $return = $kunde['email']; break;		
				case 'kunde_ustid': $return = $kunde['ustidnr']; break;
				case 'kunde_geb': 

					if (strtotime($kunde['geb']) !== false)
					{
						$return = date('d.m.Y H:i:s', strtotime($kunde['geb']));
					}
					else
					{
						$return = '--';
					} 
					
					break;			
				
				default:

					if (preg_match('/ov_\d+/', $field_value))
					{

						// Bestellvariable
						$ordervarid = substr($field_value, 3);
						$return = $order['bvars'][$ordervarid];
						
					}
					else if (preg_match('/pv_\d+/', $field_value))
					{
						 
						$produktvarid = substr($field_value, 3);
						 
						// Produktvariable (index kann auch 0 sein)
						if (isset($order['pvars'][$product_index]))
						{
							
							$return = $order['pvars'][$product_index][$produktvarid];
							
						}
						else
						{
							
							// Abwärtskompatibilität < 3.5.1 
							if ($produkt['mod_vp_varkey'] != '')
							{
								$produkt_key = $produkt['mod_vp_varkey'];
							}
							else
							{
								$produkt_key = $produkt['id'];
							}

							$return = $order['pvars'][$produkt_key][$produktvarid];
							
						}
					 
					}
					else if (preg_match('/pa_\d+/', $field_value))
					{
						
						// Produktattribute
						$paid = substr($field_value, 3);
						$return = $produkt['mod_attribute'][$paid];
						
					}
					else if (preg_match('/kv_\d+/', $field_value))
					{
						
						// Kundenvariable
						$kvid = substr($field_value, 3);
						$return = $kunde['kv'][$kvid];
						
					}
					else
					{
						
						$return = false;						
						$this->shop->callMods('wpsg_mod_export_getValue', array(&$return, $field_value, $o_id, $p_id, $productkey, $product_index, $profil_separator));
						
						if ($return === false)
						{
						
							$return = __('Nicht definiert!'.$field_value, 'wpsg');
							
						}
						
					}
				
			}  
			
			$f['size'] = 111255;
			
			if (isset($f['format']) && $f['format'] > 0 && $return != '--')
			{
				
				switch ($f['format'])
				{
					
					case 100: $return = number_format(floatval(wpsg_tf($return)), 2, '.', ''); break;
					case 200: $return = number_format(floatval(wpsg_tf($return)), 2, ',', ''); break;
					case 300: $reutrn = wpsg_ff(wpsg_tf($return), $this->shop->get_option('wpsg_currency')); break;
					case 400: $return = date('d.m.Y', strtotime($return)); break;
					case 500: $return = date('H:i:s', strtotime($return)); break;
					case 600: $return = date('d.m.Y H:i:s', strtotime($return)); break;					
					case 700: $return = strftime($this->shop->replaceUniversalPlatzhalter($f['userformat'], $order['id'], $kunde['id'], false, $p_id), strtotime($return)); break;
					case 800: $return = '"'.$return.'"'; break;
					case 900: $return = '"=""'.$return.'"""'; break;
					
				}
				
			}
						
			$return = substr($return, 0, intval($f['size'])); 
			
			return $return;
			
		} // public function getValue($field_value, $o_id, $p_id = false)
		
	} // wpsg_mod_export extends wpsg_mod_basic

?>