<?php

	/**
	 * Modul welches das Schreiben von Rechnungen ermöglicht
	 */
	class wpsg_mod_rechnungen extends wpsg_mod_basic
	{
		
		var $lizenz = 1;
		var $id = 1400;		
		var $version = "9.9.9";
		var $hilfeURL = 'http://wpshopgermany.de/?p=718';
		var $free = false;
		
		var $data = array(); 
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Rechnungen', 'wpsg');
			$this->group = __('Bestellung', 'wpsg');
			$this->desc = __('Ermöglicht es PDF Rechnungen zu Bestellungen zu generieren.', 'wpsg');
						
			$this->fields = array(
				'firma' => __('Firmenname', 'wpsg'),
				'name' => __('Name', 'wpsg'),
				'strasse' => __('Strasse', 'wpsg'),
				'plzort' => __('PLZ/Ort', 'wpsg'),	
				'land' => __('Land', 'wpsg'),
				'tel' => __('Tel', 'wpsg'),
				'fax' => __('Fax', 'wpsg'),
				'mail' => __('E-Mail', 'wpsg'),
				'web' => __('Web', 'wpsg'),
				'strnr' => __('Steuer-Nr', 'wpsg'),
				'ustidnr' => __('UStIdNr.', 'wpsg'),
				'knr' => __('Kontonummer', 'wpsg'),
				'blz' => __('BLZ', 'wpsg'),
				'bank' => __('Bank', 'wpsg'),
				'user1' => __('Benutzer 1', 'wpsg'),
				'user2' => __('Benutzer 2', 'wpsg'),
				'user3' => __('Benutzer 3', 'wpsg'),
				'user4' => __('Benutzer 4', 'wpsg'),
				'user5' => __('Benutzer 5', 'wpsg')	
			);
						
		} // public function __construct()
		
		public function install() 
		{ 
			 
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/**
			 * Tabelle für die Lieferanten
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_RECHNUNGEN." (
				id int(25) NOT NULL AUTO_INCREMENT,
				o_id int(25) NOT NULL ,
				datum DATETIME NOT NULL ,
				storno DATETIME NOT NULL,
				storno_fee DOUBLE(10,2) NOT NULL,
				rnr VARCHAR(255) NOT NULL,
				gnr VARCHAR(255) NOT NULL,
				PRIMARY KEY  (id),
				KEY o_id (o_id)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
		   	dbDelta($sql);
		   	
		   	$this->shop->checkDefault('wpsg_rechnungen_pdfperpage', '10');
			$this->shop->checkDefault('wpsg_mod_rechnungen_gutschrifttax', 'c');
		   	
		} // public function install()
		
		public function delOrder(&$order_id) 
		{ 
			
			// Rechnungen in der Datenbank löschen
			$this->db->Query("DELETE FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."'");
			
			// Rechnungen im Dateisystem löschen
			$path = $this->getFilePath($order_id); wpsg_rrmdir($path);
			
		} // public function delOrder(&$order_id)
		
		public function wp_loaded() 
		{ 
			
			if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'wpsg_mod_rechnungen_download'))
			{
				
				$hash = md5($this->shop->get_option('wpsg_salt').'wpsg'.$_REQUEST['r_id'].'wpsg'.$this->shop->get_option('wpsg_salt'));
				
				if ($hash != $_REQUEST['hash'])
				{
					
					die(__('Kein Zugriff', 'wpsg'));
					
				}
				
				$this->doDownload($_REQUEST['r_id']);
				
			}	
			
		} // public function wp_loaded()
		
		public function init()
		{
			
//			wpsg_debug($this->shop->arLizenz);
//			wpsg_debug(date('d.m.Y', $this->shop->get_option(get_class($this))));
			
		} // public function init()
		
		public function be_ajax()
		{
			
			if ($_REQUEST['do'] == 'reset')
			{
				
				$this->resetAction();
				$this->shop->addBackendMessage(__('Grundeinstellungen wieder hergestellt', 'wpsg'));			
	
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Admin&action=module&modul='.$_REQUEST['modul']); 
				
			}
			else if ($_REQUEST['do'] == 'inlinedit')
			{
				
				$foot_text = $this->shop->get_option("wpsg_rechnungen_footer");
				if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
				if (!is_array($foot_text)) $foot_text = array();
				
				$foot_text[$_REQUEST['field_id']][$_REQUEST['field']] = $_REQUEST['value'];
				
				$this->shop->update_option('wpsg_rechnungen_footer', $foot_text);
				
				die($_REQUEST['value']);
				
			}
			else if ($_REQUEST['do'] == 'add')
			{
				 
				$foot_text = $this->shop->get_option("wpsg_rechnungen_footer");
				if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
				if (!is_array($foot_text)) $foot_text = array();
				
				$new_krzl = __('Zum Bearbeiten anklicken', 'wpsg');
				$new_name = __('Zum Bearbeiten anklicken', 'wpsg');
				
				$foot_text[] = array($new_krzl, $new_name);
				
				$this->shop->update_option('wpsg_rechnungen_footer', $foot_text);
				
				die($this->foottext_list());
				
			}
			else if ($_REQUEST['do'] == 'removeFooter')
			{
				
				$foot_text = $this->shop->get_option('wpsg_rechnungen_footer');
				if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
				if (!is_array($foot_text)) $foot_text = array();
				
				unset($foot_text[$_REQUEST['foot_id']]);
				
				$this->shop->update_option('wpsg_rechnungen_footer', $foot_text);
				
				die($this->foottext_list());
				
			}
			
		} // public function be_ajax()
		
		public function settings_save()
		{
			
			if (file_exists($_FILES['wpsg_rechnungen_bp']['tmp_name']))
			{
				
				$ending = strtolower(preg_replace("/(.*)\./", "", $_FILES['wpsg_rechnungen_bp']['name']));
				
				if ($ending != "jpg" && $ending != "jpeg" && $ending != "pdf")
				{
					$this->shop->addBackendError(__("Ungültiger Dateityp (Briefpapier) ! Es sind nur JPG und PDF Dateien erlaubt!", "wpsg"));
				}
				else if ($ending == "jpg" || $ending == "jpeg")
				{					
					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_bp.jpg');					
				} 
				else if ($ending == "pdf")
				{
					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_bp.pdf');
				}
					
			}
			else if ($_REQUEST['wpsg_rechnungen_bp_del'] == "1")
			{

				@unlink($this->getFilePath('').'wpsg_rechnungen_bp.jpg');
				@unlink($this->getFilePath('').'wpsg_rechnungen_bp.pdf');
				
				$this->shop->addBackendMessage(__('Briefpapier wurde erfolgreich gelöscht.', 'wpsg'));
				
			}
			
			if (file_exists($_FILES['wpsg_rechnungen_logo']['tmp_name']))
			{
				
				$ending = strtolower(preg_replace("/(.*)\./", "", $_FILES['wpsg_rechnungen_logo']['name']));
				
				if ($ending != "jpg" && $ending != "jpeg")
				{
					$this->shop->addBackendError(__("Ungültiger Dateityp (Logo) ! Es sind nur JPG und PDF Dateien erlaubt!", "wpsg"));
				}
				else if ($ending == "jpg" || $ending == "jpeg")
				{					
					move_uploaded_file($_FILES['wpsg_rechnungen_logo']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_logo.jpg');					
				}  
					
			}
			else if ($_REQUEST['wpsg_rechnungen_logo_del'] == "1")
			{

				@unlink($this->getFilePath('').'wpsg_rechnungen_logo.jpg'); 
				
				$this->shop->addBackendMessage(__('Logo wurde erfolgreich gelöscht.', 'wpsg'));
				
			}
			
			$this->shop->update_option("wpsg_mod_rechnungen_texte", $_REQUEST['text']);
			
			$this->shop->update_option("wpsg_rechnungen_url", $_REQUEST['wpsg_rechnungen_url']);
			$this->shop->update_option("wpsg_mod_rechnungen_auto", $_REQUEST['wpsg_mod_rechnungen_auto']);
			$this->shop->update_option("wpsg_rechnungen_faelligkeit", $_REQUEST['wpsg_rechnungen_faelligkeit']);
			$this->shop->update_option('wpsg_rechnungen_pdfperpage', $_REQUEST['wpsg_rechnungen_pdfperpage']);
			$this->shop->update_option("wpsg_rechnungen_pbeschreibung", $_REQUEST['wpsg_rechnungen_pbeschreibung']);
			$this->shop->update_option("wpsg_mod_rechnungen_showgutschriftrechnung", $_REQUEST['wpsg_mod_rechnungen_showgutschriftrechnung']);
			$this->shop->update_option('wpsg_mod_rechnungen_showanr', $_REQUEST['wpsg_mod_rechnungen_showanr']);
			$this->shop->update_option("wpsg_mod_rechnungen_showpv", $_REQUEST['wpsg_mod_rechnungen_showpv']);
			$this->shop->update_option("wpsg_mod_rechnungen_showov", $_REQUEST['wpsg_mod_rechnungen_showov']);
			$this->shop->update_option("wpsg_rechnungen_start", $_REQUEST['wpsg_rechnungen_start']);
			$this->shop->update_option("wpsg_gutschrift_start", $_REQUEST['wpsg_gutschrift_start']);
			$this->shop->update_option('wpsg_mod_rechnungen_gutschrifttax', $_REQUEST['wpsg_mod_rechnungen_gutschrifttax']);
			$this->shop->update_option("wpsg_rechnungen_format", $_REQUEST['wpsg_rechnungen_format']);
			$this->shop->update_option("wpsg_gutschrift_format", $_REQUEST['wpsg_gutschrift_format']);
			$this->shop->update_option('wpsg_rechnungen_adresszeile', $_REQUEST['wpsg_rechnungen_adresszeile']);
			$this->shop->update_option('wpsg_rechnungen_foottext_standard', $_REQUEST['wpsg_rechnungen_foottext_standard']);
			$this->shop->update_option('wpsg_mod_rechnungen_hideCountry', $_REQUEST['wpsg_mod_rechnungen_hideCountry']);
			
		}
		
		public function settings_edit()
		{
						
			if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.jpg'))
			{
				$this->shop->view['bp'] = $this->getFilePath('', true).'wpsg_rechnungen_bp.jpg';
			}
			else if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.pdf'))
			{
				$this->shop->view['bp'] = $this->getFilePath('', true).'wpsg_rechnungen_bp.pdf';
			}
			else
			{
				$this->shop->view['bp'] = false;
			}
			
			if (file_exists($this->getFilePath('').'wpsg_rechnungen_logo.jpg'))
			{
				$this->shop->view['logo'] = $this->getFilePath('', true).'wpsg_rechnungen_logo.jpg';
			}
			else
			{
				$this->shop->view['logo'] = false;
			}

			$this->shop->view['fields'] = $this->fields;
			$this->shop->view['foottext_list'] = $this->foottext_list();			
			$this->shop->view['arTexte'] = $this->shop->get_option('wpsg_mod_rechnungen_texte');
			
			/**
			 * Hiermit sollte sich das Problem der doppelten Serialisierung lösen, als Notfalllösung setze ich einen leeren Array damit das Programm nicht abkackt
			 */
			if (!is_array($this->shop->view['arTexte']))
			{
				
				$this->shop->view['arTexte'] = array();
				
			} 
						
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/settings_edit.phtml');			
			
		} // public function settings_edit()
		
		public function order_view_content($order_id) 
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			// Keine Rechnungen für unvollständige Bestellungen
			if ($oOrder->status == wpsg_ShopController::STATUS_UNVOLLSTAENDIG) return;
			
			$this->shop->view['mod_rechnungen']['arRechnungen'] = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `storno` = '0000-00-00 00:00:00' AND `gnr` = '' ORDER BY `rnr` DESC");
			$this->shop->view['mod_rechnungen']['arRechnungen_storno'] = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `storno` != '0000-00-00 00:00:00' AND `gnr` = '' ORDER BY `rnr` DESC");
 
			$this->shop->view['mod_rechnungen']['arRechnungen_gesamt'] = $this->db->fetchAssoc("
				SELECT 
					*, 
					UNIX_TIMESTAMP(`datum`) AS ts_datum,
					UNIX_TIMESTAMP(`storno`) AS ts_storno
				FROM 
					`".WPSG_TBL_RECHNUNGEN."` 
				WHERE 
					`o_id` = '".wpsg_q($order_id)."' 
				ORDER BY 
					`id` ASC
			");
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/order_view.phtml');
			
		} // public function order_view_content($order_id) { }
		
		public function order_ajax() 
		{ 
			
			if (isset($_REQUEST['wpsg_rechnungen_preview']))
			{
				
				// Vorschau einer Rechnung aus der Bestellverwaltung
				$this->writeRechnung($_REQUEST['edit_id'], true);
				
				die();
				
			}
			else if (isset($_REQUEST['wpsg_rechnungen_write']))
			{
				
				$this->writeRechnung($_REQUEST['edit_id'], false);
				
				die();
				
			}
			else if (isset($_REQUEST['do']) && $_REQUEST['do'] == 'getRechnung')
			{
				
			 	$this->doDownload($_REQUEST['r_id']);
								
			}
			else if (isset($_REQUEST['do']) && $_REQUEST['do'] == 'storno')
			{
				
				$this->stornoAction();
				
			}
			else if (isset($_REQUEST['do']) && $_REQUEST['do'] == 'copy')
			{
				
				$rechnung = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($_REQUEST['r_id'])."'");
				
				if ($rechnung['id'] != $_REQUEST['r_id'] || $_REQUEST['edit_id'] != $rechnung['o_id']) die(__("Rechnung existiert nicht oder passt nicht zur Bestellung!", "wpsg"));
				
				$this->shop->view['order'] = $this->shop->cache->loadOrder($rechnung['o_id']); 
				
				// Wurde die Bestellung in einer anderen Sprache ausgeführt
				if (trim($this->shop->view['order']['language']) != '') $this->shop->setTempLocale($this->shop->view['order']['language']);
				
				$this->shop->view['kunde'] = $this->db->fetchRow("
					SELECT
						K.*
					FROM
						`".WPSG_TBL_KU."` AS K
					WHERE
						K.`id` = '".wpsg_q($this->shop->view['order']['k_id'])."'
				");
				
				$email = $this->shop->view['kunde']['email'];

				// Nun schauen ob die Original Rechnung existiert				
				if ($rechnung['gnr'] != "")
				{
					
					if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf'))
					{
						
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['id'].'.pdf';
						
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['gnr'].'.pdf'))
					{
					
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['gnr'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_G'.$rechnung['id'].'.pdf';
						
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['id'].'.pdf'))
					{
						
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['id'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_G'.$rechnung['id'].'.pdf';
						
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['gnr'].'.pdf'))
					{
						
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['gnr'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['gnr'].'.pdf';
						
					}
					
					
					$strTitle = wpsg_translate(__('Zusendung einer Kopie für Rechnungskorrektur #1# an #2#', 'wpsg'), $rechnung['gnr'], $email);
					$this->shop->view['gnr'] = $rechnung['gnr'];

					$nr = $rechnung['gnr'];
					
				}
				else
				{
					
					if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf'))
					{
					
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['id'].'.pdf';
					
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['rnr'].'.pdf'))
					{
					
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['rnr'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_R'.$rechnung['id'].'.pdf';
						
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['id'].'.pdf'))
					{
						
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['id'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_R'.$rechnung['id'].'.pdf';
						
					}
					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['rnr'].'.pdf'))					
					{
						
						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['rnr'].'.pdf';
						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['rnr'].'.pdf';
						
					}
					
					$strTitle = wpsg_translate(__('Zusendung einer Kopie für Rechnung #1# an #2#', 'wpsg'), $rechnung['rnr'], $email);
					$this->shop->view['rnr'] = $rechnung['rnr'];

					$nr = $rechnung['rnr'];
					
				}
				
				if (!file_exists($rn_file)) die(__("Die Originalrechnung existiert nicht im Dateisystem.", 'wpsg'));

				/*
				if (file_exists($rn_file_copy)) 
				{
					
					header("Cache-Control: no-cache, must-revalidate");
					header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
					header('Content-type: application/pdf'); 
						
					die(file_get_contents($rn_file_copy));

				}
				*/
				
				include WPSG_PATH_LIB.'fpdf/fpdf.php';
				include WPSG_PATH_LIB.'fpdf/fpdi.php';
				include WPSG_PATH_MOD.'/mod_rechnungen/wpsg_fpdf.class.php';
				
				$pdf = new wpsg_fpdf(); 
				$pagecount = $pdf->setSourceFile($rn_file);

				for ($i = 1; $i <= $pagecount; $i ++)
				{

					$tplidx = $pdf->importPage($i, '/MediaBox');
					$pdf->addPage(); 
					$pdf->useTemplate($tplidx, 0, 0);

					$pdf->SetTextColor(125, 125, 125); 
					$pdf->SetFont('Arial', '', 200);
					
					$pdf->SetAlpha(0.25);
					$pdf->TextWithRotation(45, 225, "KOPIE", 45, 0);
					$pdf->SetAlpha(0);					
					
				}
				 
				$pdf->Output($rn_file_copy, 'F');
 
				$rn_file_copy = $this->copyTemp($rn_file_copy, $nr);
								
				// Bestellung in anderer Sprache ?
				if (trim($this->shop->view['order']['language']) != '') $this->shop->setTempLocale($this->shop->view['order']['language']);				
				
				// Mail versenden
				$mail_text = $this->shop->render(WPSG_PATH_VIEW."/mods/mod_rechnungen/copymail.phtml", false);
 
				if ($this->shop->get_option('wpsg_htmlmail') === '1')
				{
					
					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/copymail_html.phtml', false);
					
				}
				else
				{
					
					$mail_html = false;
					
				}
				
				$arFiles = array($rn_file_copy);
 				
				if ($this->shop->get_option('wpsg_widerrufsformular_invoice') === '1' && wpsg_isSizedString($this->shop->get_option('wpsg_revocationform')))
				{
						
					$revocationFile = WPSG_PATH_UPLOADS.'wpsg_revocation/'.$this->shop->get_option('wpsg_revocationform');
						
					if (file_exists($revocationFile) && is_file($revocationFile))
					{
				
						$arFiles[] = $revocationFile;
				
					}
						
				}
				
				$this->shop->sendMail($mail_text, $email, 'rechnungscopy', $arFiles, false, false, $mail_html);
				
				// Temporäre Rechnung löschen
				@unlink($rn_file_copy);
				
				$this->shop->restoreTempLocale();
				
				// In Bestelllog eintragen
				$this->db->ImportQuery(WPSG_TBL_OL, array(
					"o_id" => $rechnung['o_id'],
					"cdate" => "NOW()",
					"title" => $strTitle,
					"mailtext" => $mail_text
				));
				
				$pdf->Output(basename($rn_file_copy), 'I');
				die();
				
			}
			
		} // public function order_ajax() 
		
		public function admin_emailconf_save()
		{
			
			wpsg_saveEMailConfig("rechnungsmail");
			wpsg_saveEMailConfig("gutschriftmail");
			wpsg_saveEMailConfig("rechnungscopy");
			 
		} // public function admin_emailconf_save()
		
		public function admin_emailconf() 
		{ 
			
			echo wpsg_drawEMailConfig(
				'rechnungsmail',
				__('E-Mail bei neuer Rechnung an den Kunden', 'wpsg'),
				__('Diese Mail bekommt der Kunde wenn die Rechnung geschrieben wird.', 'wpsg')); 
		
			echo wpsg_drawEMailConfig(
				'gutschriftmail',
				__('E-Mail bei neuer Rechnungskorrektur', 'wpsg'),
				__('Diese Mail bekommt der Kunde wenn eine neue Rechnungskorrektur geschrieben wird.', 'wpsg'));
			
			echo wpsg_drawEMailConfig(
				'rechnungscopy',
				__('E-Mail bei Rechnungskopie', 'wpsg'),
				__('Diese Mail bekommt der Kunde wenn ihm eine Rechnungskopie gesendet wird.', 'wpsg'));
			
		} // public function admin_emailconf()
		
		public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
		{

			if ($this->shop->get_option('wpsg_mod_rechnungen_auto') != '1') return;
			
			$this->writeAutoRechnung($order_id);

		} // public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
		
		private function writeGutschrift($order_id, $gnr_id, $storno_fee, $bPreview)
		{
					
			$this->shop->view['invoice'] = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($gnr_id)."' ");
			
			$this->shop->view['data'] = $this->db->fetchRow("
				SELECT
					O.*
				FROM
					`".WPSG_TBL_ORDER."` AS O
				WHERE
					O.`id` = '".wpsg_q($order_id)."'
			");			

			if (trim($this->shop->view['data']['language']) != '') $this->shop->setTempLocale($this->shop->view['data']['language']);
			
			$this->shop->view['kunde'] = $this->db->fetchRow("
				SELECT
					K.*
				FROM
					`".WPSG_TBL_KU."` AS K
				WHERE
					K.`id` = '".wpsg_q($this->shop->view['data']['k_id'])."'
			");
			
			$custom_data = @unserialize($this->shop->view['data']['custom_data']);
			$this->shop->view['basket'] = $custom_data['basket'];
		 
			$this->shop->view['storno_fee'] = $storno_fee;
			
			if (wpsg_tf($storno_fee) > 0)
			{
			
				if (strpos($storno_fee, '%') !== false)
				{
					
					// % Betrag
					if ($this->shop->getBackendTaxview() == WPSG_NETTO) $storno_fee_value_netto = $this->shop->view['basket']['sum']['preis_gesamt_netto'] / 100 * wpsg_tf($storno_fee);
					else $storno_fee_value_brutto = $this->shop->view['basket']['sum']['preis_gesamt_brutto'] / 100 * wpsg_tf($storno_fee);
					
				}
				else
				{
					
					// Absoluter Betrag
					if ($this->shop->getBackendTaxview() == WPSG_NETTO) $storno_fee_value_netto = wpsg_tf($storno_fee);
					else $storno_fee_value_brutto = wpsg_tf($storno_fee); 
					
				}
				
				$storno_tax_key = $this->shop->get_option('wpsg_mod_rechnungen_gutschrifttax'); 
				
				if (in_array($storno_tax_key, array('a', 'b', 'c', 'd', 'e')))
				{
					
					$defaultCountry = $this->shop->getDefaultCountry();
					$storno_fee_tax_value = $defaultCountry->getTax($storno_tax_key);
									
					if ($this->shop->getBackendTaxview() === WPSG_NETTO) $storno_fee_value_brutto = wpsg_calculatePreis($storno_fee_value_netto, WPSG_BRUTTO, $storno_fee_tax_value);
					else $storno_fee_value_netto = wpsg_calculatePreis($storno_fee_value_brutto, WPSG_NETTO, $storno_fee_tax_value);				
					
					$storno_fee_tax = $storno_fee_value_brutto - $storno_fee_value_netto;
	
					// In den Mehrwertsteuer Array einbauen
					$bFound = false;
					foreach ($this->shop->view['basket']['mwst'] as $tax_key_country => $tax)
					{
						
						if ($tax['value'] == $storno_fee_tax_value)
						{
							
							$bFound = true;
							$this->shop->view['basket']['mwst'][$tax_key_country]['base_value'] -= $storno_fee_value_brutto;
							$this->shop->view['basket']['mwst'][$tax_key_country]['sum'] -= $storno_fee_tax;
							break;
							
						}
						
					}
					
					if ($bFound === false)
					{
						 
						$this->shop->view['basket']['mwst'][$storno_tax_key.'_'.$this->shop->getDefaultCountry(true)] = array(
							'country' => $this->shop->getDefaultCountry(true),
							'tax_key' => $storno_tax_key,
							'sum' => -1 * $storno_fee_tax,
							'name' => wpsg_ff($storno_fee_tax_value, '%'),
							'value' => $storno_fee_tax_value,
							'base_value' => $storno_fee_value_brutto							 							
						);
						
					}
					
				}		
				else 
				{
	
					// TODO: Anteilig
					
				}		

				// Jetzt von den Preisen abziehen
				$this->shop->view['basket']['sum']['preis_netto'] -= $storno_fee_value_netto;
				$this->shop->view['basket']['sum']['preis_gesamt_netto'] -= $storno_fee_value_netto;
				$this->shop->view['basket']['sum']['preis_brutto'] -= $storno_fee_value_brutto;
				$this->shop->view['basket']['sum']['preis_gesamt_brutto'] -= $storno_fee_value_brutto;
				$this->shop->view['basket']['sum']['mwst'] -= $storno_fee_tax;
					
				if ($this->shop->getFrontendTaxview() === WPSG_NETTO)
				{
				
					$this->shop->view['basket']['sum']['preis'] = $this->shop->view['basket']['sum']['preis_netto'];
					$this->shop->view['basket']['sum']['preis_gesamt'] = $this->shop->view['basket']['sum']['preis_gesamt_netto'];
					$this->shop->view['storno_fee_value'] = $storno_fee_value_netto;
				
				}
				else
				{
				
					$this->shop->view['basket']['sum']['preis'] = $this->shop->view['basket']['sum']['preis_brutto'];
					$this->shop->view['basket']['sum']['preis_gesamt'] = $this->shop->view['basket']['sum']['preis_gesamt_brutto'];
					$this->shop->view['storno_fee_value'] = $storno_fee_value_brutto;
				
				}
				
				$this->shop->view['storno_fee_tax_value'] = $storno_fee_tax_value;
				$this->shop->view['storno_fee_tax'] = $storno_fee_tax;
				$this->shop->view['storno_fee_value_netto'] = $storno_fee_value_netto;
				$this->shop->view['storno_fee_value_brutto'] = $storno_fee_value_brutto;
					
				/*
				 wpsg_debug($this->shop->view['basket']['mwst']);
					
				wpsg_debug("Gebühr Steuer (Satz): ".$storno_fee_tax_value);
				wpsg_debug("Gebühr Steuer: ".$storno_fee_tax);
				wpsg_debug("Gebühr Netto: ".$storno_fee_value_netto);
				wpsg_debug("Gebühr Brutto: ".$storno_fee_value_brutto);
				die();
				*/
				
			}
									
			$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['kunde']['land'])."'");
			$this->shop->view['data']['shipping_land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['data']['shipping_land'])."'");
			$this->shop->view['rDatum'] = date('d.m.Y');
			$this->shop->view['title'] = __('Rechnungskorrektur', 'wpsg');			

			$this->shop->view['payment'] = $this->shop->getPaymentName($this->shop->view['data']['type_payment'], $order_id);
			
			$this->shop->view['fussText'] = false;
						
			// Beschreibung dazuladen
			foreach ($this->shop->view['basket']['produkte'] as $k => $v)
			{
				
				$produkt_id = $this->shop->getProduktID($v['id']);
				
				$this->shop->view['basket']['produkte'][$k]['beschreibung'] = $this->db->fetchOne("
					SELECT
						P.`beschreibung`
					FROM
						`".WPSG_TBL_PRODUCTS."` AS P
					WHERE
						P.`id` = '".wpsg_q($produkt_id)."'
				");
				
			}
						
			$this->shop->view['preview'] = false;
			$this->shop->view['rnr'] = $this->shop->view['invoice']['gnr'];	

			if ($bPreview) $this->shop->view['rnr'] .= __(' - Vorschau', 'wpsg');
			
			$this->shop->view['filename'] = $gnr_id;
			$this->shop->view['filename_out'] = $this->shop->view['invoice']['gnr'].'.pdf';
			
			$this->shop->view['output'] = true;			
			$this->shop->view['preview'] = $bPreview;
			
			// Wenn Rechnungskorrektur und Option aktiviert dann die Rechnungsnummer hinter die Rechnungskorrektursnummer
			if ($this->shop->get_option("wpsg_mod_rechnungen_showgutschriftrechnung") == "1")
			{
				
				// Letzt Rechnungsnummer finden
				$last_rnr = $this->db->fetchOne("SELECT `rnr` FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `gnr` = '' ORDER BY `datum` DESC LIMIT 1");
			
				$this->shop->view['rnr'] .= ' ('.__("RNr.", "wpsg").' '.$last_rnr.')';
				
			}
						
			$this->shop->view['oOrder'] = $this->shop->cache->loadOrderObject($order_id);
			$this->shop->view['storno'] = true;
			$this->shop->view['invoice'] = false;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/rechnung_pdf.phtml');
			
			$this->shop->restoreTempLocale();
						
		} // private function writeGutschrift($order_id)
		 
		public function writeRechnung($order_id, $preview, $bOutput = true)
		{
			
			$this->shop->view['output'] = $bOutput;
			
			$this->shop->view['data'] = $this->db->fetchRow("
				SELECT
					O.*
				FROM
					`".WPSG_TBL_ORDER."` AS O
				WHERE
					O.`id` = '".wpsg_q($order_id)."'
			");			
						
			// Wurde die Bestellung in einer anderen Sprache gemacht
			if (trim($this->shop->view['data']['language']) != '') $this->shop->setTempLocale($this->shop->view['data']['language']);
			
			$this->shop->view['kunde'] = $this->db->fetchRow("
				SELECT
					K.*
				FROM
					`".WPSG_TBL_KU."` AS K
				WHERE
					K.`id` = '".wpsg_q($this->shop->view['data']['k_id'])."'
			");
			
			$custom_data = @unserialize($this->shop->view['data']['custom_data']);
			$this->shop->view['basket'] = $custom_data['basket'];
			
			if (!is_array($custom_data['basket']))
			{
				
				$basket = new wpsg_basket();
				$basket->initFromDB($order_id);
				$this->shop->view['basket'] = $basket->toArray();
				
			}
			
			//wpsg_debug($this->shop->view['basket']);die();
			
			$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['kunde']['land'])."'");
			$this->shop->view['data']['shipping_land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['data']['shipping_land'])."'");
			$this->shop->view['rDatum'] = $_REQUEST['wpsg_rechnungen_datum'];
			$this->shop->view['title'] = __('Rechnung', 'wpsg');			
				
			$this->shop->view['payment'] = $this->shop->getPaymentName($this->shop->view['data']['type_payment'], $order_id);
			$this->shop->view['fussText'] = $this->shop->replaceUniversalPlatzhalter($_REQUEST['wpsg_rechnungen_fusstext'], $order_id);
			
			if ($_REQUEST['wpsg_rechnungen_faelligkeit'] == '1')
			{
				$this->shop->view['faelligkeitdatum'] = $_REQUEST['wpsg_rechnungen_faelligkeitsdatum'];
			}
									
			// Beschreibung dazuladen
			foreach ($this->shop->view['basket']['produkte'] as $k => $v)
			{
				
				$produkt_id = $this->shop->getProduktID($v['id']);
				
				$this->shop->view['basket']['produkte'][$k]['beschreibung'] = $this->db->fetchOne("
					SELECT
						P.`beschreibung`
					FROM
						`".WPSG_TBL_PRODUCTS."` AS P
					WHERE
						P.`id` = '".wpsg_q($produkt_id)."'
				");
				
				// Übersetzung
				if ($this->shop->isOtherLang())
				{
				
					$produkt_trans = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PRODUCTS."` WHERE `lang_parent` = '".wpsg_q($produkt_id)."' AND `lang_locale` = '".wpsg_q($this->shop->getCurrentLanguage())."'");
				
					if ($produkt_trans['id'] > 0)
					{
							
						$this->shop->view['basket']['produkte'][$k]['name'] = $produkt_trans['name'];
						$this->shop->view['basket']['produkte'][$k]['beschreibung'] = $produkt_trans['beschreibung'];
						$this->shop->view['basket']['produkte'][$k]['detailname'] = $produkt_trans['detailname'];
				
					}
				
				}
								
			}
			
			// Rechnungsnummer bilden
			$rnr_format = $this->shop->get_option("wpsg_rechnungen_format");
			if ($rnr_format == "") $rnr_format = "%nr%";
				
			// Neue Fortlaufende Nummer				
			$rnr_nr = intval($this->shop->get_option("wpsg_rechnungen_start"));
			if ($rnr_nr <= 0) $rnr_nr = 1;
				
			// Ersetzungen
			$rnr = preg_replace("/\%nr\%/i", $rnr_nr, $rnr_format);
			$rnr = preg_replace("/\%Jahr\%/i", date("Y"), $rnr);
			$rnr = preg_replace("/\%Monat\%/i", date("m"), $rnr);
			$rnr = preg_replace("/\%Tag\%/i", date("d"), $rnr);
							
			if ($preview)
			{
				
				$this->shop->view['preview'] = true;
				$this->shop->view['rnr'] = $rnr.' - '.__('Vorschau', 'wpsg');
				$r_id = "Vorschau";
												
			}
			else
			{
				 
				$this->shop->view['preview'] = false;
				$this->shop->view['rnr'] = $rnr;
				
				$this->shop->update_option("wpsg_rechnungen_start", ($rnr_nr + 1));
				
				// Status ändern
				if ($_REQUEST['wpsg_rechnungen_status'] == "1")
				{
						
					$this->shop->setOrderStatus($order_id, $_REQUEST['wpsg_rechnungen_status_neu'], false);
											
				}
 
				$r_id = $this->db->importQuery(
					WPSG_TBL_RECHNUNGEN,
					array(
						"rnr" => $rnr,
						"o_id" => $order_id,
						"datum" => "NOW()"
					)
				);
				
			}
			
			$this->shop->view['filename'] = $r_id;
			$this->shop->view['filename_out'] = $rnr.'.pdf';
			
			$this->shop->view['oOrder'] = $this->shop->cache->loadOrderObject($order_id);
			$this->shop->view['storno'] = false;
			$this->shop->view['invoice'] = true;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/rechnung_pdf.phtml');	
 
			if (!$preview)
			{
				 
				if (@$_REQUEST['wpsg_rechnungen_sendmail'] == "1")
				{
					
					//Mail versenden
					
					/**
					 * Damit alte Rechnungen noch versändet werden
					 */
					if (file_exists($this->getFilePath($order_id).$r_id.'.pdf'))
					{
					
						$file = $this->getFilePath($order_id).$r_id.'.pdf';
					
					}
					else if (file_exists($this->getFilePath($order_id).$rnr.'.pdf'))
					{
						
						$file = $this->getFilePath($order_id).$rnr.'.pdf';				
						
					}
					else if (file_exists($this->getFilePath($order_id).'R'.$r_id.'.pdf'))
					{
						
						$file = $this->getFilePath($order_id).'R'.$r_id.'.pdf';
						
					}
					else
					{
						
						$file = $this->getFilePath($order_id).'R'.$rnr.'.pdf'; 
						
					}  
 
					$file = $this->copyTemp($file, $rnr);
					
					$mail_text = $this->shop->render(WPSG_PATH_VIEW."/mods/mod_rechnungen/rechnungsmail.phtml", false);

					if ($this->shop->get_option('wpsg_htmlmail') === '1')
					{
						
						$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/rechnungsmail_html.phtml', false);
						
					}
					else
					{
						
						$mail_html = false;
						
					}
					
					$to = $_REQUEST['wpsg_rechnungen_email'];
													 
					$header = "";
					$arFiles = array($file);
	 
					if ($this->shop->get_option('wpsg_widerrufsformular_invoice') === '1' && wpsg_isSizedString($this->shop->get_option('wpsg_revocationform')))
					{
					
						$revocationFile = WPSG_PATH_UPLOADS.'wpsg_revocation/'.$this->shop->get_option('wpsg_revocationform');
					
						if (file_exists($revocationFile) && is_file($revocationFile))
						{
								
							$arFiles[] = $revocationFile;
								
						}
					
					}
					
					$this->shop->sendMail($mail_text, $to, 'rechnungsmail', $arFiles, $order_id, false, $mail_html);

					// Temporäre Rechnung löschen
					@unlink($file);
					
					$this->shop->restoreTempLocale();
					
					// In Log eintragen
					$this->db->importQuery(WPSG_TBL_OL, array(
						"cdate" => "NOW()",
						"o_id" => wpsg_q($this->shop->view['data']['id']),
						"title" => wpsg_q(wpsg_translate(__('Rechnungsmail an #1#', 'wpsg'), $to)),				
						"mailtext" => wpsg_q($mail_text)
					));						
									
				}
								
				// Url Benachrichtigung
				if ($_REQUEST['wpsg_rechnungen_url'] == '1')
				{
					
					$this->shop->notifyURL(
						$this->shop->get_option('wpsg_rechnungen_url'), 
						false, 
						false, 
						$this->shop->view['data']['id'], 
						2						
					);
					
				}
				
			}
			
			$this->shop->restoreTempLocale();
			
		} // private function writeRechnung($order_id)

		public function setOrderStatus($order_id, $status_id, $inform)
		{
			
			if ($this->shop->get_option('wpsg_mod_rechnungen_auto') != '2' || $status_id != 100) return;
			
			$this->writeAutoRechnung($order_id);
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		public function stornoAction()
		{

			$order_data = $this->shop->cache->loadOrder($_REQUEST['edit_id']);
			
			// Wurde die Bestellung in einer anderen Sprache gemacht
			if (trim($order_data['language']) != '') $this->shop->setTempLocale($order_data['language']);
			
			$custom_data = @unserialize($this->shop->view['data']['custom_data']);
			$this->shop->view['basket'] = $custom_data['basket'];
			
			// Rechnung laden die storniert werden soll
			$rechnung = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($_REQUEST['edit_id'])."' AND `storno` = '0000-00-00 00:00:00'");

			// Letzte Rechnungsnummer
			$last_rnr = $this->db->fetchOne("
				SELECT
					`rnr`
				FROM
					`".WPSG_TBL_RECHNUNGEN."`
				WHERE
					`storno` = '0000-00-00 00:00:00' AND 
					`rnr` != '' AND
					`o_id` = '".wpsg_q($_REQUEST['edit_id'])."'
			"); 
						
			if (isset($_REQUEST['form_submit_preview'])) $bPreview = true;
			else $bPreview = false;
			
			if (!$bPreview)
			{
			
				$this->db->UpdateQuery(
					WPSG_TBL_RECHNUNGEN,
					array(
						"storno" => "NOW()"					
					),
					"`o_id` = '".wpsg_q($_REQUEST['edit_id'])."' AND `gnr` = ''"
				);
							
				if ($_REQUEST['wpsg_rechnungen_gutschrift'] == "0")
				{
				
					// Status der Bestellung auf storniert ändern
					$this->shop->setOrderStatus($_REQUEST['edit_id'], 500, false);
					
				}
				
			}
			
			if ($_REQUEST['wpsg_rechnungen_gutschrift'] == "1" || $_REQUEST['wpsg_rechnungen_gutschrift'] == "2")
			{
 									
				// Gutschriftnummer bilden
				$gnr_format = $this->shop->get_option("wpsg_gutschrift_format");
				if ($gnr_format == "") $gnr_format = "%nr%";
					
				// Neue Fortlaufende Nummer				
				$gnr_nr = intval($this->shop->get_option("wpsg_gutschrift_start"));
				if ($gnr_nr <= 0) $gnr_nr = 1;
					
				// Stornierungsgebühr
				$storno_fee = $_REQUEST['wpsg_mod_rechnungen_fee'];
				
				// Ersetzungen
				$gnr = preg_replace("/\%nr\%/i", $gnr_nr, $gnr_format);
				$gnr = preg_replace("/\%Jahr\%/i", date("Y"), $gnr);
				$gnr = preg_replace("/\%Monat\%/i", date("m"), $gnr);
				$gnr = preg_replace("/\%Tag\%/i", date("d"), $gnr);

				if (!$bPreview)
				{
				
					$g_id = $this->db->ImportQuery(WPSG_TBL_RECHNUNGEN, array(
						"o_id" => $_REQUEST['edit_id'],
						"datum" => "NOW()",
						"rnr" => "",
						"gnr" => $gnr,
						"storno_fee" => wpsg_q($storno_fee)
					));
					
					$this->shop->update_option("wpsg_gutschrift_start", ($gnr_nr + 1));
					
				}
				else
				{
									
					$g_id = $gnr_nr;
				
				}
 			
				$this->writeGutschrift($_REQUEST['edit_id'], $g_id, $storno_fee, $bPreview);
				
				if ($_REQUEST['wpsg_rechnungen_gutschrift'] == "2")
				{
												
					// Mail an Kunden senden
					//public function mail($e_mail, $subject, $message, $headers, $anhang = array())
					$this->shop->view['storno_fee'] = $storno_fee;
					
					$mail_text = $this->shop->render(WPSG_PATH_VIEW."/mods/mod_rechnungen/gutschriftmail.phtml", false);

					if ($this->shop->get_option('wpsg_htmlmail') == '1')
					{
						
						$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/gutschriftmail_html.phtml', false);
						
					}
					else
					{
						
						$mail_html = false;
						
					}
					
					if (!$bPreview) 
					{

						$file = $this->getFilePath($_REQUEST['edit_id']).'/'.$g_id.'.pdf';						
						$file = $this->copyTemp($file, $gnr);
					
						$arFiles = array($file);						
						$this->shop->sendMail($mail_text, $this->shop->view['kunde']['email'], 'gutschriftmail', $arFiles, false, false, $mail_html);
					
						// Temporäre Rechnung löschen
						@unlink($file);
						
					}
					
					$this->shop->restoreTempLocale();
					
					if ($bPreview) $subject = wpsg_translate(__('Rechnungskorrekturmail an #1# (Vorschau)', 'wpsg'), $this->shop->view['kunde']['email']);
					else $subject = wpsg_translate(__('Rechnungskorrekturmail an #1#', 'wpsg'), $this->shop->view['kunde']['email']);
										
					// In Bestelllog eintragen
					$this->db->ImportQuery(WPSG_TBL_OL, array(
						"o_id" => $_REQUEST['edit_id'],
						"cdate" => "NOW()",
						"title" => wpsg_q($subject),
						"mailtext" => $mail_text
					));
  
				} 
									
				die();
				
			} // gutschrift 
			
			$this->shop->restoreTempLocale();
			
			$this->shop->addBackendMessage(__('Rechnung wurde erfolgreich storniert', 'wpsg'));
						
			$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']); 
			
		}
		
		/**
		 * Kopiert eine Datei temporär und benennt sie anhand der Rechnugnsnummer um
		 */
		private function copyTemp($file, $rnr)
		{
			
			$path = $this->shop->getTempDir();
			
			wpsg_copy($file, $path.'/'.$rnr.'.pdf');

			return $path.'/'.$rnr.'.pdf';
			
		} // private function copyTemp($file, $r_id)
		
		/**
		 * Startet den Download einer Rechnung wird im Frontend wie im Backend verwendet
		 */
		private function doDownload($r_id)
		{
			
			$rechnung = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($r_id)."'");
			
			if ($rechnung['gnr'] != "")
			{
				
				/**
				 * Damit alte Rechnungskorrekturen noch angezeigt werden
				 */
				if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf'))
				{
					
					$file = $this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
					
				}
				else if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['gnr'].'.pdf'))
				{
					
					$file = $this->getFilePath($rechnung['o_id']).$rechnung['gnr'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
				
				}
				else if (file_exists($this->getFilePath($rechnung['o_id']).'G'.$rechnung['id'].'.pdf'))
				{
					
					$file = $this->getFilePath($rechnung['o_id']).'G'.$rechnung['id'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
					
				}
				else
				{	
									
					$file = $this->getFilePath($rechnung['o_id']).'G'.$rechnung['gnr'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
					
				}
				
			}
			else 
			{
				
				/**
				 * Damit alte Rechnungen noch angezeigt werden
				 */
				if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf'))
				{
						
					$file = $this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
						
				}
				else if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['rnr'].'.pdf'))
				{
					
					$file = $this->getFilePath($rechnung['o_id']).$rechnung['rnr'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');						
					
				}
				else if (file_exists($this->getFilePath($rechnung['o_id']).'R'.$rechnung['id'].'.pdf'))
				{
					
					$file = $this->getFilePath($rechnung['o_id']).'R'.$rechnung['id'].'.pdf';
					header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
					
				}
				else
				{
					
					$file = $this->getFilePath($rechnung['o_id']).'R'.$rechnung['rnr'].'.pdf'; 
					header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
					
				}
				
			}
			
			header("Cache-Control: no-cache, must-revalidate");
			header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
			header('Content-type: application/pdf'); 
				
			die(file_get_contents($file));
			
		} // private function doDownload($r_id)
		
		/**
		 * Gibt einen Downloadlink für die Rechnung für die Verwendung im Frontend zurück
		 */
		public function getFrontendLink($r_id)
		{
			 
			$hash = md5($this->shop->get_option('wpsg_salt').'wpsg'.$r_id.'wpsg'.$this->shop->get_option('wpsg_salt'));
			
			$url = $this->shop->getURL(wpsg_ShopController::URL_BASKET);
			$url .= ((strpos($url, '?') === false)?'?wpsg_action=wpsg_mod_rechnungen_download':'&wpsg_action=wpsg_mod_rechnungen_download');
			$url .= '&hash='.$hash.'&r_id='.$r_id;
			
			return $url;
			 
		} // public function getFrontendLink($r_id)
		
		/**
		 * Gibt false (Wenn keine Rechnung aktiv) oder den Datensatz der aktuellen Rechnung zurück
		 */
		public function getOrderInvoice($order_id)
		{
			
			$invoice_db = $this->db->fetchRow("
				SELECT
					R.*
				FROM
					`".WPSG_TBL_RECHNUNGEN."` AS R
				WHERE
					R.`o_id` = '".wpsg_q($order_id)."' AND
					R.`storno` = '0000-00-00 00:00:00' AND
					R.`gnr` = ''
				ORDER BY
					R.`datum` DESC
				LIMIT
					1
			");
			
			if ($invoice_db['id'] > 0)
			{
				
				return $invoice_db;
				
			}
			
			return false;
			
		} // public function getOrderInvoice($order_id)
		
		/**
		 * Gibt false zurück (Wenn keine Rechnungskorrektur geschrieben ist, oder eine aktuelle Rechnung vorhanden ist) 
		 * Ansonsten den Satz aus der Datenbank
		 */
		public function getOrderCredit($order_id)
		{
			
			if ($this->getOrderInvoice($order_id) === false)
			{
				
				$credit_db = $this->db->fetchRow("
					SELECT
						R.* 
					FROM 
						`".WPSG_TBL_RECHNUNGEN."` AS R
					WHERE
						R.`o_id` = '".wpsg_q($order_id)."' AND
						R.`rnr` = '' AND
						R.`gnr` != ''
					ORDER BY
						R.`datum` DESC
					LIMIT
						1
				");
				
				if ($credit_db['id'] > 0)
				{
					
					return $credit_db;
					
				}
				
			}
			
			return false;			
			
		} // public function getOrderCredit($order_id)
		
		/**
		 * Gibt die Rechnungstexte in der korrekten Sprache und mit übersetzen Platzhaltern zurück
		 */
		public function getRechnungstexte($order_id)
		{
									
			$arTexte = $this->shop->get_option("wpsg_mod_rechnungen_texte");
			
			if (wpsg_isSizedArray($arTexte))
			{
						
				foreach ($arTexte as $k => $v)
				{
					
					$arTexte[$k]['text'] = $this->shop->replaceUniversalPlatzhalter(__($arTexte[$k]['text'], 'wpsg'), $order_id);
					
				}

				return $arTexte;
				
			}
			else
			{
				
				return array();
				
			}
			
		} // public function getRechnungstexte($order_id)
		
		/**
		 * Setzt das Rechnungsmodul auf die Standardeinstellungen zurück
		 */
		public function resetAction()
		{
			
			$arData = array(
				"firma" => array("aktiv" => "1", "x" => "24", "y" => "10", "fontsize" => 8, "text" => "%shopinfo_name%", "color" => "#000000"),
				"name" => array("aktiv" => "1", "x" => "24", "y" => "13", "fontsize" => 8, "text" => "Inh. %shopinfo_owner%", "color" => "#000000"),
				"strasse" => array("aktiv" => "1", "x" => "24", "y" => "16", "fontsize" => 8, "text" => "%shopinfo_street%", "color" => "#000000"),
				"plzort" => array("aktiv" => "1", "x" => "24", "y" => "19", "fontsize" => 8, "text" => "%shopinfo_zip% %shopinfo_city%", "color" => "#000000"),
				"land" => array("aktiv" => "1", "x" => "24", "y" => "22", "fontsize" => 8, "text" => "DEUTSCHLAND", "color" => "#000000"),
				"tel" => array("aktiv" => "1", "x" => "75", "y" => "10", "fontsize" => 8, "text" => "Tel. %shopinfo_tel%", "color" => "#000000"),
				"fax" => array("aktiv" => "1", "x" => "75", "y" => "13", "fontsize" => 8, "text" => "Fax. %shopinfo_fax%", "color" => "#000000"),
				"mail" => array("aktiv" => "1", "x" => "75", "y" => "16", "fontsize" => 8, "text" => "Mail: %shopinfo_email%", "color" => "#000000"),
				"web" => array("aktiv" => "1", "x" => "75", "y" => "19", "fontsize" => 8, "text" => "Web: ".site_url(), "color" => "#000000"),
				"strnr" => array("aktiv" => "1", "x" => "24", "y" => "270", "fontsize" => 8, "text" => "Steuer-Nr.: %shopinfo_taxnr%", "color" => "#000000"),
				"ustidnr" => array("aktiv" => "1", "x" => "24", "y" => "273", "fontsize" => 8, "text" => "USt-IdNr.: %shopinfo_ustidnr%", "color" => "#000000"),
				"knr" => array("aktiv" => "1", "x" => "24", "y" => "276", "fontsize" => 8, "text" => "IBAN: %shopinfo_iban%", "color" => "#000000"),
				"blz" => array("aktiv" => "1", "x" => "24", "y" => "279", "fontsize" => 8, "text" => "BIC: %shopinfo_bic%", "color" => "#000000"),
				"bank" => array("aktiv" => "1", "x" => "24", "y" => "282", "fontsize" => 8, "text" => "Bank: %shopinfo_bankname%", "color" => "#000000"),
			);
			
			$this->shop->update_option("wpsg_rechnungen_adresszeile", "Absender: %shopinfo_name% %shopinfo_street% %shopinfo_zip% %shopinfo_city%");
			$this->shop->update_option("wpsg_mod_rechnungen_texte", $arData);
			
		} // public function resetAction()
		
		/**
		 * Zeichnet die Liste der angelegten Fußtexte
		 */
		public function foottext_list()
		{
			
			$foot_text = $this->shop->get_option("wpsg_rechnungen_footer");
			if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
			if (!is_array($foot_text)) $foot_text = array();
			
			$this->shop->view['data'] = $foot_text;
			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/foottext_list.phtml', false);
			
		} // function foottext_list()
		
		/*
		 * Gibt den Absoluten Pfad zurück wo die Rechnungen gespeichert sind
 		 * Ist der Parameter $url auf true so wird der relative Pfad für die Ausgabe in URLs zurückgegeben
 		 */
 		public function getFilePath($order_id, $url = false)
 		{
 		  			
 			if ($this->shop->isMultiBlog())
			{

				$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
				$htaccess = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/.htaccess';
				 
				$url_content = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
				
				if ($url) $strReturn = $url_content.'/'.$order_id.'/';
				else $strReturn = $path.'/'.$order_id.'/';
								 
			}
			else
			{
				
				$path = WPSG_PATH_CONTENT.'uploads/wpsg_rechnungen/';				
				$htaccess = WPSG_PATH_CONTENT.'uploads/wpsg_rechnungen/.htaccess';
				
				if ($url) $strReturn = WPSG_URL_CONTENT.'uploads/wpsg_rechnungen/'.$order_id.'/';
				else $strReturn = $path.$order_id.'/';
				 
			}
			
			if (!file_exists($path)) 
			{
				mkdir($path, 0777, true);
			}
			
			/*
 			 * Zur Sicherheit überprüfe ich immer ob die .htaccess existiert
 			 */
			
			if (!file_exists($htaccess))
			{
				
				$handle = fopen($htaccess, "w+");
				
				$content = '
				
Deny from all

<Files wpsg_rechnungen_logo.jpg>
allow from all
</Files>

<Files wpsg_rechnungen_bp.jpg>
allow from all
</Files>

<Files wpsg_rechnungen_bp.pdf>
allow from all
</Files>

				';
							
				fwrite($handle, $content, strlen($content));
				fclose($handle);
				
			}
			
			return $strReturn;
			 
 		} // private function getFilePath($produkt_id, $url = false)

 		/**
 		 * Wird beim schreiben der Rechnung nach der Bestellung bzw. Bezahlung aufgerufen
 		 */
 		private function writeAutoRechnung($order_id)
 		{
 			
 			$order_data = $this->shop->cache->loadOrder($order_id);
 			$customer_data = $this->shop->cache->loadKunden($order_data['k_id']);
 			
 			$_REQUEST['wpsg_rechnungen_sendmail'] = '1';
 			$_REQUEST['wpsg_rechnungen_email'] = wpsg_q($customer_data['email']);
 			$_REQUEST['wpsg_rechnungen_fusstext'] = '';
 			$_REQUEST['wpsg_rechnungen_faelligkeit'] = '0';
 			$_REQUEST['wpsg_rechnungen_datum'] = date('d.m.Y');
 				 
 			// Fälligkeit anzeigen wenn ein Wert im Backend für die Tage gesetzt ist.
 			if (intval($this->shop->get_option('wpsg_rechnungen_faelligkeit')) > 0)
 			{
 			
 				$_REQUEST['wpsg_rechnungen_faelligkeit'] = '1';
 				$_REQUEST['wpsg_rechnungen_faelligkeitsdatum'] = date('d.m.Y', time() + intval($this->shop->get_option('wpsg_rechnungen_faelligkeit')) * 86400);
 			
 			}
 				
 			// Standardfußtext setzen, sollte er definiert sein
 			if ($this->shop->get_option('wpsg_rechnungen_foottext_standard') !== false)
 			{
 			
 				$foot_text = $this->shop->get_option("wpsg_rechnungen_footer");
 				if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
 				if (!is_array($foot_text)) $foot_text = array();
 			
 				if (isset($foot_text[$this->shop->get_option('wpsg_rechnungen_foottext_standard')]))
 				{
 						
 					$_REQUEST['wpsg_rechnungen_fusstext'] = $foot_text[$this->shop->get_option('wpsg_rechnungen_foottext_standard')][1];
 						
 				}
 			
 			}
 			
 			$this->writeRechnung($order_id, $preview = false, $bOutput = false);
 			
 		} // private function writeAutoRechnung()
 		
	} // class wpsg_mod_rechnungen extends wpsg_mod_basic

?>