<?php

	/**
	 * Modul zur Generierung von Lieferscheinen
	 * @author Daschmi
	 */
	class wpsg_mod_deliverynote extends wpsg_mod_basic
	{
		
		var $lizenz = 1;
		var $id = 2000;
		var $hilfeURL = 'http://wpshopgermany.maennchen1.de/?p=3667';
		var $version = "9.9.9";
		var $free = false;
		
		public function __construct()
		{
			
			parent::__construct();
				
			$this->name = __('Lieferschein', 'wpsg');
			$this->group = __('Bestellung', 'wpsg');
			$this->desc = __('Ermöglicht die Erstellung von Lieferscheinen.', 'wpsg');
						
		} // public function __construct()
		
		public function init()
		{
			
			require_once(dirname(__FILE__).'/mod_deliverynote/wpsg_deliverynote.class.php');
			
			$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 init()
		
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
				
			/**
			 * Tabelle für die Lieferanten
			*/
			$sql = "CREATE TABLE ".WPSG_TBL_DELIVERYNOTE." (
				id int(25) NOT NULL AUTO_INCREMENT,
				order_id int(25) NOT NULL ,
				cdate DATETIME NOT NULL ,
				lnr VARCHAR(255) NOT NULL ,
				delivery_date DATETIME NOT NULL ,
				note TEXT NOT NULL,
				cancel int(1) NOT NULL,		
				product_indexes TEXT NOT NULL,
				PRIMARY KEY  (id) 
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
							
			// Früher gab es "product_keys" welches aber nicht eindeutig war, da es aktuell mehrmals den gleichen Schlüssel im Warenkorb geben kann
			
			dbDelta($sql); 
			
			$this->shop->checkDefault('wpsg_mod_deliverynote_nrformat', '%lnr%');
			$this->shop->checkDefault('wpsg_mod_deliverynote_nr', '1');
						
			if ($this->shop->get_option('wpsg_mod_deliverynote_texte') === false) $this->resetAction();				
			
		} // public function install()
		
		public function settings_edit()
		{
			
			$this->shop->view['wpsg_mod_deliverynote']['fields'] = $this->fields;
			$this->shop->view['wpsg_mod_deliverynote']['arTexte'] = $this->shop->get_option('wpsg_mod_deliverynote_texte');
			if (!is_array($this->shop->view['wpsg_mod_deliverynote']['arTexte'])) $this->shop->view['wpsg_mod_deliverynote']['arTexte'] = array();
			
			$this->shop->view['foottext_list'] = $this->foottext_list();
			
			if (file_exists($this->getFilePath('').'wpsg_deliverynote_bp.jpg'))
			{
				$this->shop->view['wpsg_mod_deliverynote']['bp'] = $this->getFilePath('', true).'wpsg_deliverynote_bp.jpg';
			}
			else if (file_exists($this->getFilePath('').'wpsg_deliverynote_bp.pdf'))
			{
				$this->shop->view['wpsg_mod_deliverynote']['bp'] = $this->getFilePath('', true).'wpsg_deliverynote_bp.pdf';
			}
			else
			{
				$this->shop->view['wpsg_mod_deliverynote']['bp'] = false;
			}
				
			if (file_exists($this->getFilePath('').'wpsg_deliverynote_logo.jpg'))
			{
				$this->shop->view['wpsg_mod_deliverynote']['logo'] = $this->getFilePath('', true).'wpsg_deliverynote_logo.jpg';
			}
			else
			{
				$this->shop->view['wpsg_mod_deliverynote']['logo'] = false;
			}
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_deliverynote_nrformat', $_REQUEST['wpsg_mod_deliverynote_nrformat']);
			$this->shop->update_option('wpsg_mod_deliverynote_nr', $_REQUEST['wpsg_mod_deliverynote_nr']);
			$this->shop->update_option('wpsg_mod_deliverynote_foottext_standard', $_REQUEST['wpsg_mod_deliverynote_foottext_standard']);
			$this->shop->update_option("wpsg_mod_deliverynote_texte", $_REQUEST['text']);
			$this->shop->update_option('wpsg_mod_deliverynote_url', $_REQUEST['wpsg_mod_deliverynote_url']);
			$this->shop->update_option('wpsg_mod_deliverynote_url_standard', $_REQUEST['wpsg_mod_deliverynote_url_standard']);
			$this->shop->update_option('wpsg_mod_deliverynote_adressrow', $_REQUEST['wpsg_mod_deliverynote_adressrow']);			
			$this->shop->update_option('wpsg_mod_deliverynote_hideCountry', $_REQUEST['wpsg_mod_deliverynote_hideCountry']);
			$this->shop->update_option('wpsg_mod_deliverynote_anr', $_REQUEST['wpsg_mod_deliverynote_anr']);
			
			if (file_exists($_FILES['wpsg_mod_deliverynote_bp']['tmp_name']))
			{
			
				$ending = strtolower(preg_replace("/(.*)\./", "", $_FILES['wpsg_mod_deliverynote_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_mod_deliverynote_bp']['tmp_name'], $this->getFilePath('').'wpsg_deliverynote_bp.jpg');
				}
				else if ($ending == "pdf")
				{
					move_uploaded_file($_FILES['wpsg_mod_deliverynote_bp']['tmp_name'], $this->getFilePath('').'wpsg_deliverynote_bp.pdf');
				}
					
			}
			else if ($_REQUEST['wpsg_mod_deliverynote_bp_del'] == "1")
			{
			
				@unlink($this->getFilePath('').'wpsg_deliverynote_bp.jpg');
				@unlink($this->getFilePath('').'wpsg_deliverynote_bp.pdf');
			
				$this->shop->addBackendMessage(__('Briefpapier wurde erfolgreich gelöscht.', 'wpsg'));
			
			}
				
			if (file_exists($_FILES['wpsg_mod_deliverynote_logo']['tmp_name']))
			{
			
				$ending = strtolower(preg_replace("/(.*)\./", "", $_FILES['wpsg_mod_deliverynote_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_mod_deliverynote_logo']['tmp_name'], $this->getFilePath('').'wpsg_deliverynote_logo.jpg');
				}
					
			}
			else if ($_REQUEST['wpsg_mod_deliverynote_logo_del'] == "1")
			{
			
				@unlink($this->getFilePath('').'wpsg_deliverynote_logo.jpg');
			
				$this->shop->addBackendMessage(__('Logo wurde erfolgreich gelöscht.', 'wpsg'));
			
			}
			
		} // public function settings_save()

		public function admin_presentation() 
		{
			
			echo wpsg_drawForm_Checkbox('wpsg_mod_deliverynote_pdf_beschreibung', __('Produktbeschreibung auf Lieferschein anzeigen', 'wpsg'), $this->shop->get_option('wpsg_mod_deliverynote_pdf_beschreibung'));
			if ($this->shop->hasMod('wpsg_mod_varianten')) echo wpsg_drawForm_Checkbox('wpsg_mod_deliverynote_pdf_varianten', __('Varianten auf Lieferschein anzeigen', 'wpsg'), $this->shop->get_option('wpsg_mod_deliverynote_pdf_varianten'));
			
		} // public function admin_presentation()
		
		public function admin_presentation_submit() 
		{ 
			
			$this->shop->update_option('wpsg_mod_deliverynote_pdf_beschreibung', $_REQUEST['wpsg_mod_deliverynote_pdf_beschreibung']);
			if ($this->shop->hasMod('wpsg_mod_varianten')) $this->shop->update_option('wpsg_mod_deliverynote_pdf_varianten', $_REQUEST['wpsg_mod_deliverynote_pdf_varianten']);
			
		} // public function admin_presentation_submit()
		
		public function order_ajax()
		{
			
			if (isset($_REQUEST['wpsg_mod_deliverynote_preview']))
			{
				 
				// Vorschau einer Rechnung aus der Bestellverwaltung
				$this->writeDeliverynote(
					$_REQUEST['edit_id'], 
					explode(',', $_REQUEST['wpsg_mod_deliverynote_productindexes']), 
					$_REQUEST['wpsg_mod_deliverynote_fusstext'], 
					strtotime($_REQUEST['wpsg_mod_deliverynote_date']), 
					true
				);
			
				die();
			
			}
			else if ($_REQUEST['do'] == 'get')
			{
				
				$dn = new wpsg_deliverynote();
				$dn->load($_REQUEST['dn_id']);
				
				if ($dn->order_id != $_REQUEST['edit_id']) $this->shop->throwErrorCode('2000_7');
				
				$filename = 'deliverynote_'.$dn->id.'.pdf';
				$file = $this->getFilePath($_REQUEST['edit_id']).$filename;
				
				wpsg_header::PDFPlugin($file);
				
			}
			else if (isset($_REQUEST['wpsg_mod_deliverynote_write']))
			{
				
				if ($_REQUEST['edit_id'] <= 0) $this->shop->throwErrorCode('2000_3');
				
				$lnr = $this->buildLnr($_REQUEST['edit_id']);
				
				$arProductIndexes = explode(',', $_REQUEST['wpsg_mod_deliverynote_productindexes']);
				
				foreach ($arProductIndexes as $product_key)
				{
			 
					if (!wpsg_deliverynote::checkProductKey($product_key, $_REQUEST['edit_id']))
					{
						
						$this->shop->throwErrorCode('2000_6');
						
					}
					
				} 
				
				// In Datenbank eintragen
				$dn_id = $this->db->ImportQuery(WPSG_TBL_DELIVERYNOTE, array(
					'order_id' => wpsg_q($_REQUEST['edit_id']),
					'cdate' => "NOW()",
					'delivery_date' => date('Y-m-d', strtotime($_REQUEST['wpsg_mod_deliverynote_date'])),
					'lnr' => wpsg_q($lnr),
					'note' => wpsg_q($_REQUEST['wpsg_mod_deliverynote_fusstext']),
					'cancel' => '0',
					'product_indexes' => wpsg_q($_REQUEST['wpsg_mod_deliverynote_productindexes'])
				));
				
				$filename = 'deliverynote_'.$dn_id.'.pdf';
								
				// Lieferschein erstellen
				$bOK = $this->writeDeliverynote(
					$_REQUEST['edit_id'], 
					explode(',', $_REQUEST['wpsg_mod_deliverynote_productindexes']), 
					$_REQUEST['wpsg_mod_deliverynote_fusstext'], 
					strtotime($_REQUEST['wpsg_mod_deliverynote_date']),
					false,
					$lnr,
					$filename
				);
				
				if ($bOK === true)
				{
				
					$file = $this->getFilePath($_REQUEST['edit_id']).'/'.$filename;
					 
					if (!file_exists($file) || !is_file($file))
					{
						
						$this->db->Query("DELETE FROM `".WPSG_TBL_DELIVERYNOTE."` WHERE `id` = '".wpsg_q($dn_id)."'");
						$this->shop->throwErrorCode('2000_4');
						
					}
					 					
					// Nummer hochzählen
					$this->shop->update_option('wpsg_mod_deliverynote_nr', $this->shop->get_option('wpsg_mod_deliverynote_nr') + 1);
					
					// E-Mail senden
					if ($_REQUEST['wpsg_mod_deliverynote_showmail'] == '1')
					{
						
						$this->sendDeliveryMail($_REQUEST['edit_id'], $dn_id, $_REQUEST['wpsg_mod_deliverynote_email']);
						
					}
					
					// Url Benachrichtigung
					if ($_REQUEST['wpsg_mod_deliverynote_noticeurl'] == '1')
					{
							 
						$this->shop->notifyURL(
							$this->shop->get_option('wpsg_mod_deliverynote_url'),
							false,
							false,
							$_REQUEST['edit_id'],
							3,
							'deliverynote'
						);
							
					}
					
					// Status setzen
					$this->shop->setOrderStatus($_REQUEST['edit_id'], $_REQUEST['wpsg_mod_deliverynote_status'], 0);
					
					wpsg_header::PDFPlugin($file);					
										
				}
				else
				{
					
					$this->db->Query("DELETE FROM `".WPSG_TBL_DELIVERYNOTE."` WHERE `id` = '".wpsg_q($dn_id)."'");
					$this->shop->throwErrorCode('2000_2');
					
				}
				
			}
			
		} // public function order_ajax()
		
		public function order_view_row(&$p, $i) 
		{ 
						
			if (wpsg_deliverynote::checkProductKey($p['product_index'], $_REQUEST['edit_id']))
			{
			
				$this->shop->view['wpsg_mod_deliverynote']['product'] = $p;
				$this->shop->view['wpsg_mod_deliverynote']['i'] = $i;
			
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/order_view_row.phtml');

			}
			
		} // public function order_view_row(&$p, $i)
		
		public function delOrder(&$order_id)
		{
				
			// Lieferscheine in der Datenbank löschen
			$this->db->Query("DELETE FROM `".WPSG_TBL_DELIVERYNOTE."` WHERE `order_id` = '".wpsg_q($order_id)."'");
				
			// Lieferscheine im Dateisystem löschen
			$path = $this->getFilePath($order_id); wpsg_rrmdir($path);
				
		} // public function delOrder(&$order_id)
		
		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['wpsg_mod_deliverynote']['arDeliverynotes'] = $this->loadDeliveryNotesFromOrder($order_id);
			$this->shop->view['wpsg_mod_deliverynote']['arNoDeliveredProducts'] = $this->getNoDeliveredProducts($order_id);
			 
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/order_view_content.phtml');
			
		} // public function order_view_content($order_id)
		
		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'] == 'addFoottext')
			{
		
				$foot_text = $this->shop->get_option("wpsg_mod_deliverynote_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_mod_deliverynote_footer', $foot_text);
				
				die($this->foottext_list());
				 
			}
			else if ($_REQUEST['do'] == 'removeFoottext')
			{
				
				$foot_text = $this->shop->get_option('wpsg_mod_deliverynote_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_mod_deliverynote_footer', $foot_text);
				
				die($this->foottext_list());
				
			}
			else if ($_REQUEST['do'] == 'inlineEdit')
			{
				
				$foot_text = $this->shop->get_option("wpsg_mod_deliverynote_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_mod_deliverynote_footer', $foot_text);
				
				die($_REQUEST['value']);
				
			}
			
			
		} // public function be_ajax()
		
		/** Modulfunktionen */
		
		/**
		 * Gibt das Datum der letzten Lieferung einer Bestellung zurück wenn alle Produkte ausgeliefert wurden
		 * Sonst false
		 */
		public function getDeliveryTime($order_id)
		{
			
			$arDN_order = $this->loadDeliveryNotesFromOrder($order_id);
			
			// Abbruch wenn keine Lieferscheine zu der Bestellung existieren
			if (!wpsg_isSizedArray($arDN_order)) return false;
			
			$arNoDeliveredProducts = $this->getNoDeliveredProducts($order_id);
			
			// Abbruch wenn es noch nicht ausgelieferte Produkte gibt
			if (wpsg_isSizedArray($arNoDeliveredProducts)) return false;
			
			$lastDN = array_shift(wpsg_deliverynote::find(array(
				'order_id' => $order_id,
				'cancel' => '0',
				'order' => 'DN.cdate',
				'order_direction' => 'DESC'
			)));
			
			return $lastDN->getDeliveryTimestamp();
			
		} // public function getDeliveryTime($order_id)
		
		public function getProductDeliveryTime($order_id, $product_index)
		{
			
			$lastDN = array_shift(wpsg_deliverynote::find(array(
				'order_id' => $order_id,
				'cancel' => '0',
				'product_index' => $product_index,
				'order' => 'DN.cdate',
				'order_direction' => 'DESC'
			)));
			
			if (is_object($lastDN)) return $lastDN->getDeliveryTimestamp();
			else return false;
			
		} // public function getProductDeliveryTime($order_id, $product_index)
		
		/**
		 * Sendet die Mail an den Kunden mit dem Lieferschein
		 */
		public function sendDeliveryMail($order_id, $dn_id, $email = false)
		{
			
			$filename = 'deliverynote_'.$dn_id.'.pdf';
			$file = $this->getFilePath($order_id).$filename;

			if (!file_exists($file) || !is_file($file)) $this->shop->throwErrorCode('2000_5');
			
			$this->shop->view['order'] = $this->shop->cache->loadOrder($order_id);
			
			// Wurde die Bestellung in einer anderen Sprache gemacht
			if (trim($this->shop->view['order']['language']) != '') $this->shop->setTempLocale($this->shop->view['order']['language']);
			
			$this->shop->view['customer'] = $this->shop->cache->loadKunden($this->shop->view['order']['k_id']);
			
			$this->shop->view['dn'] = new wpsg_deliverynote();
			$this->shop->view['dn']->load($dn_id);
			
			$mail_text = $this->shop->render(WPSG_PATH_VIEW."/mods/mod_deliverynote/deliverymail.phtml", false);
			
			if ($this->shop->get_option('wpsg_htmlmail') === '1')
			{
				
				$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/deliverymail_html.phtml', false);
				
			}
			else
			{
				
				$mail_html = false;
				
			}
			
			$arFiles = array($file);
				
			if ($email === false) $email = $this->shop->view['customer']['email'];
			
			$this->shop->sendMail($mail_text, $email, 'deliverymail', $arFiles, $this->shop->view['order']['id'], $this->shop->view['order']['k_id'], $mail_html);
						
			$this->shop->restoreTempLocale();
			
			$strSubject = wpsg_translate(__('Lieferschein ##1#', 'wpsg'), $this->shop->view['dn']->lnr);
			
			// In Bestelllog eintragen
			$this->db->ImportQuery(WPSG_TBL_OL, array(
				"o_id" => wpsg_q($order_id),
				"cdate" => "NOW()",
				"title" => wpsg_q($strSubject),
				"mailtext" => wpsg_q($mail_text)
			));  
			
		} // public function sendDeliveryMail($order_id, $dn_id)
		
		/**
		 * Generiert den Lieferschein für eine Bestellung
		 */
		public function writeDeliverynote($order_id, $arProductIndexes, $fussText = '', $liefer_datum = false, $preview = false, $lnr = false, $filename = false)
		{
			
			$this->shop->view['order'] = $this->shop->cache->loadOrder($order_id);
			$this->shop->view['customer'] = $this->shop->cache->loadKunden($this->shop->view['order']['k_id']);
			$this->shop->view['data'] = array();
			$this->shop->view['fussText'] = $fussText;

			// Wurde die Bestellung in einer anderen Sprache gemacht
			if (trim($this->shop->view['order']['language']) != '') $this->shop->setTempLocale($this->shop->view['order']['language']);
			
			// Rechnungsadresse		
			$this->shop->view['data']['firma'] = $this->shop->view['customer']['firma'];
			$this->shop->view['data']['vname'] = $this->shop->view['customer']['vname'];
			$this->shop->view['data']['name'] = $this->shop->view['customer']['name'];
			$this->shop->view['data']['strasse'] = $this->shop->view['customer']['strasse'];
			$this->shop->view['data']['hausnr'] = $this->shop->view['customer']['hausnr'];
			$this->shop->view['data']['plz'] = $this->shop->view['customer']['plz'];
			$this->shop->view['data']['ort'] = $this->shop->view['customer']['ort'];
			$this->shop->view['data']['land'] = $this->shop->view['customer']['land'];
						
			// Versandadresse ?
			if ($this->shop->hasMod('wpsg_mod_shippingadress'))
			{
				
				if ($this->shop->callMod('wpsg_mod_shippingadress', 'check_different_shippingadress', array($this->shop->view['order']['k_id'], $order_id)))
				{
					
					$this->shop->view['data']['firma'] = $this->shop->view['order']['shipping_firma'];
					$this->shop->view['data']['vname'] = $this->shop->view['order']['shipping_vname'];
					$this->shop->view['data']['name'] = $this->shop->view['order']['shipping_name'];
					$this->shop->view['data']['strasse'] = $this->shop->view['order']['shipping_strasse'];
					$this->shop->view['data']['hausnr'] = $this->shop->view['order']['shipping_hausnr'];
					$this->shop->view['data']['plz'] = $this->shop->view['order']['shipping_plz'];
					$this->shop->view['data']['ort'] = $this->shop->view['order']['shipping_ort'];
					$this->shop->view['data']['land'] = $this->shop->view['order']['shipping_land'];
					
				}
								
			}
			 
			if (wpsg_isSizedInt($this->shop->view['data']['land']))
			{
				
				$this->shop->view['data']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['data']['land'])."'");
				
			}
			
			$this->shop->view['preview'] = $preview;
						
			if ($liefer_datum === false) $this->shop->view['lDatum'] = time();
			else $this->shop->view['lDatum'] = $liefer_datum;
			
			$this->shop->view['data']['products'] = array();
			
			foreach ($arProductIndexes as $product_index)
			{
				
				$product_data = $this->db->fetchRow("
					SELECT
						OP.*,
						P.`name`
					FROM
						`".WPSG_TBL_ORDERPRODUCT."` AS OP
							LEFT JOIN `".WPSG_TBL_PRODUCTS."` AS P ON (OP.`p_id` = P.`id`)
					WHERE
						OP.`product_index` = '".wpsg_q($product_index)."' AND
						OP.`o_id` = '".wpsg_q($order_id)."'
				");
				
				if ($this->shop->isOtherLang())
				{
				
					$produkt_trans = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PRODUCTS."` WHERE `lang_parent` = '".wpsg_q($product_data['p_id'])."' AND `lang_locale` = '".wpsg_q($this->shop->getCurrentLanguage())."'");
				 
					if ($produkt_trans['id'] > 0)
					{
							
						$product_data['name'] = $produkt_trans['name']; 
				
					}
				
				}
				
				$this->shop->view['data']['products'][$product_index] = $product_data;
				
			}
			
			if ($preview === true)
			{
				
				$this->shop->view['filename'] = __('LieferscheinVorschau.pdf', 'wpsg');
				$this->shop->view['title'] = __('Lieferschein Vorschau', 'wpsg');
				$this->shop->view['lnr'] = $this->buildLnr($order_id);
								
			}
			else
			{
				
				$this->shop->view['filename'] = $filename;
				$this->shop->view['title'] = __('Lieferschein', 'wpsg');
				$this->shop->view['lnr'] = $lnr;
				
			}

			$this->shop->view['oOrder'] = $this->shop->cache->loadOrderObject($order_id);
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/deliverynote_pdf.phtml');

			$this->shop->restoreTempLocale();
			
			return true;
			
		} // public function writeDeliverynote($order_id, $preview = false)
		
		/**
		 * Gibt die ProductKeys der Bestellung zurück, die noch nicht versendet wurden 
		 */
		public function getNoDeliveredProducts($order_id) 
		{

			$oOrder = &$this->shop->cache->loadOrderObject($order_id);
			$order_products = $oOrder->getProductKeys();
			 
			$arReturn = array();
			foreach ($order_products as $product_key)
			{
				
				if (wpsg_deliverynote::checkProductKey($product_key, $order_id)) $arReturn[] = $product_key;
				
			}
			
			return $arReturn;
			
		} // public function getNoDeliveredProducts($order_id) 
		
		/**
		 * Lädt die Lieferscheine einer Bestellung
		 * @param int $order_id ID der Bestellung
		 */
		public function loadDeliveryNotesFromOrder($order_id)
		{
			
			$deliverynote_ids = $this->db->fetchAssocField("SELECT DN.`id` FROM `".WPSG_TBL_DELIVERYNOTE."` AS DN WHERE `order_id` = '".wpsg_q($order_id)."' ");
			
			$arReturn = array();
			
			foreach ($deliverynote_ids as $deliverynote_id)
			{
				
				$deliverynote = new wpsg_deliverynote();
				$deliverynote->load($deliverynote_id);
				
				$arReturn[$deliverynote_id] = $deliverynote;
				
			}
			
			return $arReturn;
			
		} // public function loadDeliveryNotesFromOrder($order_id)

		/**
		 * Gibt die nächste formatierte Rechnungsnummer zurück
		 */
		public function buildLnr($order_id)
		{
			
			$onr = $this->shop->get_option('wpsg_mod_deliverynote_nr');
				
			if (trim($this->shop->get_option('wpsg_mod_deliverynote_nrformat')) == '')
			{
				
				$format = "%lid%";
				
			}
			else
			{
				
				$format = $this->shop->get_option('wpsg_mod_deliverynote_nrformat');
				
			}
						
			$liefer_id = $this->db->getNextAutoincrementValue(WPSG_TBL_DELIVERYNOTE);
			
			$strReturn = $this->shop->replaceUniversalPlatzhalter($format, $order_id, false, fase, false, array(
				'/%lid%/' => $liefer_id,
				'/%lnr%/' => $this->shop->get_option('wpsg_mod_deliverynote_nr')	
			));

			return $strReturn;
			
		} // public function buildLnr()
		
		/**
		 * Gibt die möglichen Fußtexte zurück
		 */
		public function foottext_list()
		{
			
			$foot_text = $this->shop->get_option("wpsg_mod_deliverynote_footer");
			if (!is_array($foot_text)) $foot_text = @unserialize($foot_text);
			if (!is_array($foot_text)) $foot_text = array();
				
			$this->shop->view['wpsg_mod_deliverynote']['data'] = $foot_text;
				
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_deliverynote/foottext_list.phtml', false);
			
		} // public function foottext_list()
		
		/**
		 * Gibt die Texte für das PDF in der korrekten Sprache und mit übersetzen Platzhaltern zurück
		 */
		public function getTexte($order_id)
		{
				
			$arTexte = $this->shop->get_option("wpsg_mod_deliverynote_texte");
				
			foreach ($arTexte as $k => $v)
			{
		
				$arTexte[$k]['text'] = $this->shop->replaceUniversalPlatzhalter(__($arTexte[$k]['text'], 'wpsg'), $order_id);
		
			}
				
			return $arTexte;
				
		} // public function getTexte($order_id)
		
		/**
		 * Lädt die vordefinierten Textfelder
		 */
		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_mod_deliverynote_adressrow", "Absender: %shopinfo_name% %shopinfo_street% %shopinfo_zip% %shopinfo_city%");
			$this->shop->update_option("wpsg_mod_deliverynote_texte", $arData);
			
		} // public function resetAction()
		
		/**
		 * Gibt den Absoluten Pfad zurück wo die Lieferscheine gespeichert sind
		 */
		public function getFilePath($order_id, $url = false)
		{
		
			if ($this->shop->isMultiBlog())
			{
		
				$path = WPSG_PATH_CONTENT.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_deliverynote/'.$order_id.'/';
				$htaccess = WPSG_PATH_CONTENT.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_deliverynote/.htaccess';
				$url_content = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_deliverynote/';
				
				if ($url) $strReturn = $url_content.$order_id.'/';
				else $strReturn = $path;
					
			}
			else
			{
		
				$path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_deliverynote/'.$order_id.'/';
				$htaccess = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_deliverynote/.htaccess';
		
				if ($url) $strReturn = WPSG_URL_CONTENT.'uploads/wpsg/wpsg_deliverynote/'.$order_id.'/';
				else $strReturn = $path.'/';
					
			}
				
			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_deliverynote_logo.jpg>
allow from all
</Files>
		
<Files wpsg_deliverynote_bp.jpg>
allow from all
</Files>
		
<Files wpsg_deliverynote_bp.pdf>
allow from all
</Files>
		
				';
					
				fwrite($handle, $content, strlen($content));
				fclose($handle);
		
			}
				
			return $strReturn;
		
		} // private function getFilePath($produkt_id, $url = false)
		 
	} // class wpsg_mod_deliverynote extends wpsg_mod_basic

?>