<?php

	/**
	 * Klasse die die Zahlungsart Billsafe erlaubt
	 * @author daniel
	 */
	class wpsg_mod_billsafe extends wpsg_mod_basic 
	{
		
		var $lizenz = 2;
		var $id = 815; 
		
		var $version = "9.9.9";
		var $hilfeURL = 'http://wpshopgermany.de/?p=1575';
		
		var $gatewayURL = 'https://payment.billsafe.de/V200';
		var $gatewayURL_sandbox = 'https://sandbox-payment.billsafe.de/V200';
		var $applicationSignature = '5073f9680c1a742df6ef798892c60d1b';
		
		var $free = true;
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Billsafe', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlungsart Billsafe.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{

			$this->shop->checkDefault('wpsg_mod_billsafe_bezeichnung', $this->name, false, true);
			$this->shop->checkDefault('wpsg_mod_billsafe_aktiv', '1');
			$this->shop->checkDefault('wpsg_mod_billsafe_hint', __('Zahlen Sie mit der Zahlungsart "Billsafe"', 'wpsg'), false, true);
			$this->shop->checkDefault('wpsg_mod_billsafe_logo', '');
			
			$this->shop->checkDefault('wpsg_mod_billsafe_vendorID', '<!-- Erhalten Sie von Billsafe --!>');
			$this->shop->checkDefault('wpsg_mod_billsafe_licence', '<!-- Erhalten Sie von Billsafe --!>');
						
			$this->shop->checkDefault('wpsg_mod_billsafe_sandbox', '1');
			$this->shop->checkDefault('wpsg_mod_billsafe_licencesandbox', '<!-- Erhalten Sie von Billsafe --!>');
			
			$this->shop->checkDefault('wpsg_mod_billsafe_gebuehr', '0');
			$this->shop->checkDefault('wpsg_mod_billsafe_mwst', '0');
			$this->shop->checkDefault('wpsg_mod_billsafe_mwstland', '0');
			
			$this->shop->checkDefault('wpsg_mod_billsafe_currency', 'EUR');
			$this->shop->checkDefault('wpsg_mod_billsafe_autorun', '0'); 
			$this->shop->checkDefault('wpsg_mod_billsafe_precheck', '0');
			 
		  	// Bestelltabelle erweitern
		  	require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			$sql = "CREATE TABLE ".WPSG_TBL_ORDER." (
		   		mod_billsafe_token varchar(255) NOT NULL ,
		   		mod_billsafe_transaction_id varchar(255) NOT NULL
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
		} // public function install()
		
		public function settings_edit() 
		{
			 			
			$pages = get_pages();
			
			$arPages = array(
				'-1' => __('Neu anlegen und zuordnen', 'wpsg')
			);
			
			foreach ($pages as $k => $v)
			{
				$arPages[$v->ID] = $v->post_title.' (ID:'.$v->ID.')';
			}
			
			$this->shop->view['pages'] = $arPages;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_billsafe/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_billsafe_bezeichnung', $_REQUEST['wpsg_mod_billsafe_bezeichnung']);
			$this->shop->update_option('wpsg_mod_billsafe_aktiv', $_REQUEST['wpsg_mod_billsafe_aktiv']);
			$this->shop->update_option('wpsg_mod_billsafe_aktiv_from', $_REQUEST['wpsg_mod_billsafe_aktiv_from']);
			$this->shop->update_option('wpsg_mod_billsafe_aktiv_to', $_REQUEST['wpsg_mod_billsafe_aktiv_to']);
			$this->shop->update_option('wpsg_mod_billsafe_hint', $_REQUEST['wpsg_mod_billsafe_hint']);
			$this->shop->update_option('wpsg_mod_billsafe_logo', $_REQUEST['wpsg_mod_billsafe_logo']);
			
			$this->shop->update_option('wpsg_mod_billsafe_vendorID', $_REQUEST['wpsg_mod_billsafe_vendorID']);
			$this->shop->update_option('wpsg_mod_billsafe_licence', $_REQUEST['wpsg_mod_billsafe_licence']);
						
			$this->shop->update_option('wpsg_mod_billsafe_sandbox', $_REQUEST['wpsg_mod_billsafe_sandbox']);
			$this->shop->update_option('wpsg_mod_billsafe_licencesandbox', $_REQUEST['wpsg_mod_billsafe_licencesandbox']);
			
			$this->shop->update_option('wpsg_mod_billsafe_gebuehr', $_REQUEST['wpsg_mod_billsafe_gebuehr']);
			$this->shop->update_option('wpsg_mod_billsafe_mwst', $_REQUEST['wpsg_mod_billsafe_mwst']);
			$this->shop->update_option('wpsg_mod_billsafe_mwstland', $_REQUEST['wpsg_mod_billsafe_mwstland']);
			
			$this->shop->update_option('wpsg_mod_billsafe_currency', $_REQUEST['wpsg_mod_billsafe_currency']);
			$this->shop->update_option('wpsg_mod_billsafe_autorun', $_REQUEST['wpsg_mod_billsafe_autorun']);
			$this->shop->update_option('wpsg_mod_billsafe_precheck', $_REQUEST['wpsg_mod_billsafe_precheck']);
			$this->shop->update_option('wpsg_mod_billsafe_success', $_REQUEST['wpsg_mod_billsafe_success']);
			$this->shop->update_option('wpsg_mod_billsafe_error', $_REQUEST['wpsg_mod_billsafe_error']);
			
			$this->shop->createPage(__('Ergebnis Ihrer Billsafe Zahlung', 'wpsg'), 'wpsg_mod_billsafe_success', $_REQUEST['wpsg_mod_billsafe_success']);
			$this->shop->createPage(__('Fehlgeschlagene Billsafe Zahlung', 'wpsg'), 'wpsg_mod_billsafe_error', $_REQUEST['wpsg_mod_billsafe_error']);
			
			$this->shop->addTranslationString('wpsg_mod_billsafe_bezeichnung', $_REQUEST['wpsg_mod_billsafe_bezeichnung']);
			$this->shop->addTranslationString('wpsg_mod_billsafe_aktiv', $_REQUEST['wpsg_mod_billsafe_aktiv']);
			
		} // public function settings_save()
		 
		public function addPayment(&$arPayment) 
		{
		
			if (!is_admin() && $this->shop->get_option('wpsg_mod_billsafe_aktiv') != '1');
			 
			$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_billsafe_mwst'), $this->shop->getDefaultCountry());
						
			$arPayment[$this->id] = array(
				'id' => $this->id,
				'name' => __($this->shop->get_option('wpsg_mod_billsafe_bezeichnung'), 'wpsg'),
				'preis' => $this->shop->get_option('wpsg_mod_billsafe_gebuehr'),
				'mwst_key' => $this->shop->get_option('wpsg_mod_billsafe_mwst'),
				'mwst_value' => $mwst_value,
				'mwst_null' => $this->shop->get_option('wpsg_mod_billsafe_mwstland'),
				'hint' => __($this->shop->get_option('wpsg_mod_billsafe_hint')),
				'logo' => WPSG_URL_CONTENT.'plugins/wpshopgermany/views/gfx/billsafe.png',
				'logo_100x25' => $this->shop->getRessourceURL('mods/mod_billsafe/gfx/logo_100x25.png')
			);
			
			if (isset($_REQUEST['wpsg_checkout2']))
			{

				$arBasket = $this->shop->basket->toArray();
				
				/*
				 * Vorabprüfung ob Zahlungsart möglich ist (Wenn Option "Vorabprüfung" aktiviert ist)
				 */
				if ($this->shop->get_option('wpsg_mod_billsafe_precheck') == '1')
				{
										
					require_once dirname(__FILE__).'/mod_billsafe/Billsafe/Sdk.php';
					 
					$strLand = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($arBasket['checkout']['land'])."'");
					
					$shipping_firma = $arBasket['checkout']['firma']; 
					$shipping_firstname = $arBasket['checkout']['vname'];
					$shipping_lastname = $arBasket['checkout']['name'];
					$shipping_street = $arBasket['checkout']['strasse']; 
					$shipping_postcode = $arBasket['checkout']['plz'];
					$shipping_city = $arBasket['checkout']['ort'];
					$shipping_country = $strLand;
					 
					if 
						(	
							$this->shop->hasMod('wpsg_mod_shippingadress') && 
							(	
								$_SESSION['wpsg']['checkout']['shipping_firma'] != '' && $_SESSION['wpsg']['checkout']['shipping_firma'] != $shipping_firma && 
								$_SESSION['wpsg']['checkout']['shipping_name'] != '' && $_SESSION['wpsg']['checkout']['shipping_name'] != $shipping_lastname && 
								$_SESSION['wpsg']['checkout']['shipping_vname'] != '' && $_SESSION['wpsg']['checkout']['shipping_vname'] != $shipping_firstname
							)
						)
					{
  
						$shipping_firma = $_SESSION['wpsg']['checkout']['shipping_firma'];
						$shipping_firstname = $_SESSION['wpsg']['checkout']['shipping_name'];
						$shipping_lastname = $_SESSION['wpsg']['checkout']['shipping_vname'];
						$shipping_street = $_SESSION['wpsg']['checkout']['shipping_strasse'];
						$shipping_postcode = $_SESSION['wpsg']['checkout']['shipping_plz'];
						$shipping_city = $_SESSION['wpsg']['checkout']['shipping_ort'];
						
						if ($_SESSION['wpsg']['checkout']['shipping_land'] > 0)
							$shipping_country = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($_SESSION['wpsg']['checkout']['shipping_land'])."'"); 
						
					}
					
					$arParam = array(   
						'isLiveMode' => (($this->shop->get_option('wpsg_mod_billsafe_sandbox') == 1)?false:true),
						'isUtf8Mode' => true,
						'apiVersion' => '206',
						'gatewayVersion' => '200',
					
						'order_amount' => wpsg_round($arBasket['sum']['preis_gesamt_brutto'], 2),
						'order_currencyCode' => 'EUR',
						'customer_company' => $arBasket['checkout']['firma'],
						'customer_firstname' =>	$arBasket['checkout']['vname'],
						'customer_lastname' => $arBasket['checkout']['name'],
						'customer_street' => $arBasket['checkout']['strasse'], 
						'customer_postcode'	=> $arBasket['checkout']['plz'],
						'customer_city' => $arBasket['checkout']['ort'], 
						'customer_email' => $arBasket['checkout']['email'],
						'customer_phone' => $arBasket['checkout']['tel'],
						'customer_country' => $strLand,
					
						'deliveryAddress_company' => $shipping_firma,
						'deliveryAddress_firstname' => $shipping_firstname,
						'deliveryAddress_lastname' => $shipping_lastname,
						'deliveryAddress_street' => $shipping_street,
						'deliveryAddress_postcode' => $shipping_postcode,
						'deliveryAddress_city' => $shipping_city,
						'deliveryAddress_country' => $shipping_country
					); 
					 
					$bs = new Billsafe_Sdk();
		
					$bs->setCredentials(
						array(
				    		'merchantId' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
				    		'merchantLicenseSandbox' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
				    		'merchantLicenseLive' => $this->shop->get_option('wpsg_mod_billsafe_licence'),
				    		'applicationSignature' => $this->applicationSignature,
							'applicationVersion' => 'wpShopGermany Versio '.WPSG_VERSION
						)
					);
					
					$bs->setUtf8Mode(true);
					$bs->setMode(((get_option('wpsg_mod_billsafe_sandbox') == 1)?false:Billsafe_Sdk::LIVE));
					
					$response = $bs->callMethod('prevalidateOrder', $arParam);
				 
					if ($response->invoice->isAvailable != "TRUE") 
					{
						
						unset($arPayment[$this->id]);
						
						return false;
						
					}
					
				}
				 
				if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO || $arBasket['noMwSt'])
				{
						
					$payment_netto = $this->getPreis($this->shop->get_option('wpsg_mod_billsafe_gebuehr'), $arBasket['sum']['preis']);
					$payment_brutto = wpsg_calculatePreis($payment_netto, WPSG_BRUTTO, $mwst_value);
						
				}
				else
				{
												
					$payment_brutto = $this->getPreis($this->shop->get_option('wpsg_mod_billsafe_gebuehr'), $arBasket['sum']['preis']);																								
					$payment_netto = wpsg_calculatePreis($payment_brutto, WPSG_NETTO, $mwst_value);						
						
				}
				
				// Entsprechenden Preis anzeigen
				if ($this->shop->getFrontendTaxview() == WPSG_NETTO)
				{
					
					$arPayment[$this->id]['price'] = $payment_netto;
					
				}
				else 
				{
					
					$arPayment[$this->id]['price'] = $payment_brutto;
					
				}
				
			}
						
		} // public function addPayment(&$arPayment)
		
		public function checkPaymentAvailable(&$arPayment, &$arBasket) 
		{ 
			
			$from = wpsg_tf($this->shop->get_option('wpsg_mod_billsafe_aktiv_from'));
			$to = wpsg_tf($this->shop->get_option('wpsg_mod_billsafe_aktiv_to'));
			$value = $arBasket['sum']['preis_gesamt'];
			
			// Min Wert prüfen wenn gesetzt
			if ($from >= 0)
			{
				
				if ($value < $from) unset($arPayment[$this->id]);	
				
			}
			
			if ($to > 0)
			{
				
				if ($value > $to) unset($arPayment[$this->id]);
				
			}
						
		} // public function checkPaymentAvailable(&$arPayment, &$arBasket)		 
		
		public function calcPayment(&$arBasket) 
		{ 
			
			if ($arBasket['checkout']['payment'] == $this->id)
			{
			 
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_billsafe_gebuehr'), $arBasket['sum']['preis']);
				
				if ($this->shop->get_option('wpsg_mod_billsafe_mwstland') == '1' && $arBasket['noMwSt'])
				{
					
					// Keine MwSt. berechnen !
					$arBasket['sum']['preis_payment'] = $payment_price;
					$arBasket['sum']['preis_payment_brutto'] = $payment_price;
					$arBasket['sum']['preis_payment_netto'] = $payment_price;
					
					$arBasket['payment']['mwst'] = 0;
					$this->shop->arPayment[$arBasket['checkout']['payment']]['mwst_value'] = 0;
					
					$arBasket['payment']['tax_rata'] = false;
					
				}
				else
				{
					
					// MwSt berechnen (Angaben im Backend sind immer Brutto)
					$this->setPaymentKosten($arBasket, $payment_price, $this->shop->get_option('wpsg_mod_billsafe_mwst'));

				}
								
			}
			
		} // public function calcPayment(&$arBasket) 
	
		public function order_ajax() 
		{ 
			
			if ($_REQUEST['do'] == 'getInvoice')
			{
				
				$strFileName = $this->getFilePath($_REQUEST['edit_id']).'/billsafe_rechnung.pdf';
				
				header('Content-Disposition: attachment; filename="billsafe_rechnung_'.$_REQUEST['edit_id'].'.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($strFileName));
				
			}
			
		} // public function order_ajax()
		
		public function order_view_sidebar(&$order_id) 
		{

			$order_data = $this->shop->cache->loadOrder($order_id);
			
			if ($order_data['type_payment'] != $this->id) return;
			
			$this->shop->view['wpsg_mod_billsafe']['data'] = $order_data;		 
	 
			if (file_exists($this->getFilePath($order_id).'/billsafe_rechnung.pdf'))
			{	
				$this->shop->view['wpsg_mod_billsafe']['rechnung_url'] = WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=ajax&mod=wpsg_mod_billsafe&edit_id='.$order_id.'&noheader=1&do=getInvoice';
			}
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_billsafe/order_view_sidebar.phtml');
			
		}
		
		public function order_done(&$order_id, &$done_view) 
		{ 

			// Bestellungen mit 0 geben nix aus
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;
			
			if ($this->shop->view['basket']['checkout']['payment'] == $this->id)
			{
			
				$order_data = $this->shop->cache->loadOrder($order_id);
				
				if (wpsg_isSizedString($order_data['mod_billsafe_token']))
				{
					
					$strToken = $order_data['mod_billsafe_token'];
					
				}
				else
				{

					$strToken = $this->genTokenForOrder($order_id, $this->shop->view['basket']);
										
				}
				
				if (wpsg_isSizedString($strToken))
				{
				
					if (get_option('wpsg_mod_billsafe_sandbox') == '1')
					{
						$url = $this->gatewayURL_sandbox;
					}
					else
					{
						$url = $this->gatewayURL;
					}
					
					$url .= '?token='.$strToken;
					 
					$this->shop->view['wpsg_mod_billsafe']['url'] = $url;
					
					$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_billsafe/order_done.phtml');
					
				}
				else
				{
					
					echo __('Es gab Probleme bei der Übermittelung an Billsafe. Bitte kontaktieren Sie den Shopbetreiber.', 'wpsg');
					
				}

			}
						
		} // public function order_done(&$order_id)

		public function content_filter(&$content) 
		{ 
			
			if (get_the_id() <= 0) return;
			
			if ($this->shop->get_option('wpsg_mod_billsafe_success') == get_the_id() && isset($_REQUEST['token']))
			{
 
				$order = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_ORDER."` WHERE `mod_billsafe_token` = '".wpsg_q($_REQUEST['token'])."'");
				
				if ($order['id'] <= 0)
				{
						
					$content .= __('Keine Bestellung für diesen Token gefunden', 'wpsg');
					return;
						
				}
				
				$oOrder = wpsg_order::getInstance($order['id']);
				
				if ($oOrder->getMeta('wpsg_mod_billsafe_handled') == $_REQUEST['token'])
				{
										
					$content .= __('Bestellung bereits verarbeitet', 'wpsg');
					return;
					
				}
				
				$oOrder->setMeta('wpsg_mod_billsafe_handled', $_REQUEST['token']);
				
				require_once dirname(__FILE__).'/mod_billsafe/Billsafe/Sdk.php';
									
				$bs = new Billsafe_Sdk();
				
				$bs->setCredentials(
					array(
			    		'merchantId' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
			    		'merchantLicenseSandbox' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
			    		'merchantLicenseLive' => $this->shop->get_option('wpsg_mod_billsafe_licence'),
			    		'applicationSignature' => $this->applicationSignature,
						'applicationVersion' => 'wpShopGermany Versio '.WPSG_VERSION
					)
				);
				
				$bs->setUtf8Mode(true);
				$bs->setMode((($this->shop->get_option('wpsg_mod_billsafe_sandbox') == 1)?false:Billsafe_Sdk::LIVE));
				
				$arParam = array(
					'token' => $_REQUEST['token'],
					'merchant_id' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
					'merchant_license' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
					'application_signature' => $this->shop->get_option('wpsg_mod_billsafe_appkey')
				);
				
				$response = $bs->callMethod('getTransactionResult', $arParam);
				 
				if ($response->status != 'ACCEPTED')
				{
					 
					// Eintrag im Protokoll anlegen
					$this->db->ImportQuery(WPSG_TBL_OL, array(
						"o_id" => wpsg_q($order['id']),
						"cdate" => "NOW()",	
						"title" => __('Zahlung konnte durch Billsafe nicht bestätigt werden.', 'wpsg'),
						"mailtext" => ((isset($response->declineReason->message))?$response->declineReason->message:print_r($response->errorList, 1))
					));
					
					$this->shop->setOrderStatus($order['id'], 200, true);
										
					$content = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_billsafe/zahlung_ablehnung.phtml', false);
					
				}
				else
				{
					
					// Transaktions ID speichern
					$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
						'mod_billsafe_transaction_id' => $response->transactionId
					), "`id` = '".wpsg_q($order['id'])."'");
					
					// Eintrag im Protokoll anlegen
					$this->db->ImportQuery(WPSG_TBL_OL, array(
						"o_id" => wpsg_q($order['id']),
						"cdate" => "NOW()",	
						"title" => __('Erfolgreiche Bestätigung durch Billsafe.', 'wpsg'),
						"mailtext" => ''
					));
					
					$this->shop->setOrderStatus($order['id'], 100, true); 
					
					// Rechnung von Billsafe holen und ablegen
					$strFileName = $this->getFilePath($order['id']).'/billsafe_rechnung.pdf';
					
					$bs = new Billsafe_Sdk();
					
					$bs->setCredentials(
						array(
				    		'merchantId' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
				    		'merchantLicenseSandbox' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
				    		'merchantLicenseLive' => $this->shop->get_option('wpsg_mod_billsafe_licence'),
				    		'applicationSignature' => $this->applicationSignature,
							'applicationVersion' => 'wpShopGermany Versio '.WPSG_VERSION
						)
					);
					
					$bs->setUtf8Mode(true);
					$bs->setMode(((get_option('wpsg_mod_billsafe_sandbox') == 1)?false:Billsafe_Sdk::LIVE));
					
					$arParam = array(
						'transactionId' => $response->transactionId,
						'outputType' => 'PDF'
					);
					
					$response = $bs->callMethod('getPaymentInstruction', $arParam);
		
					file_put_contents($strFileName, base64_decode($response->data));
					
					if (file_exists($strFileName)) $arFiles[] = $strFileName;
					
					$content = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_billsafe/zahlung_erfolg.phtml', false); 
										
				}

				return -2;
				
			}
			
		} // public function wp_loaded()

		public function setOrderStatus($order_id, $status_id, $inform) 
		{
			 
			$order = $this->shop->cache->loadOrder($order_id);
			
			if ($order['type_payment'] != $this->id || !in_array($status_id, array(250, 500))) return;
			
			require_once dirname(__FILE__).'/mod_billsafe/Billsafe/Sdk.php';
			
			$bs = new Billsafe_Sdk();
			
			$bs->setCredentials(
				array(
		    		'merchantId' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
		    		'merchantLicenseSandbox' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
		    		'merchantLicenseLive' => $this->shop->get_option('wpsg_mod_billsafe_licence'),
		    		'applicationSignature' => $this->applicationSignature,
					'applicationVersion' => 'wpShopGermany Versio '.WPSG_VERSION
				)
			);
			
			$bs->setUtf8Mode(true);
			$bs->setMode(((get_option('wpsg_mod_billsafe_sandbox') == 1)?false:Billsafe_Sdk::LIVE));
			
			if ($status_id == 250)
			{
				
				// Ware versendet = 250								
				$arParam = array(
					'transactionId' => $order['mod_billsafe_transaction_id'] 
				);
				
				$response = $bs->callMethod('reportShipment', $arParam);

				$strBetreff = __('Versandbenachrichtung an Billsafe.de', 'wpsg');
				
			}
			else if ($status_id == 500)
			{
				
				// Storniert = 500
				$arParam = array(
					'transactionId' => $order['mod_billsafe_transaction_id'],
					'order_amount' => '0.00',
					'order_taxAmount' => '0.00',
					'order_currencyCode' => 'EUR'
				);		
				
				$response = $bs->callMethod('updateArticleList', $arParam);

				$strBetreff = __('Stornierungsmitteilung an Billsafe.de', 'wpsg');
				
			}
			
			ob_start();
			var_dump($response);
			$strMailtext = ob_get_contents();
			ob_end_clean();
			
			// Eintrag ins Protokoll
			$this->db->ImportQuery(WPSG_TBL_OL, array(
				'o_id' => $order_id,
				'cdate' => 'NOW()',
				'title' => $strBetreff,
				'mailtext' => $strMailtext
			)); 
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		/** Modulfunktionen */
		
		/**
		 * Wird nach dem Bestellabschluß aufgerufen um den Token zu generieren
		 */
		public function genTokenForOrder($order_id, $arBasket)
		{
			
			$order_data = $this->shop->cache->loadOrder($order_id);
			$customer_data = $this->shop->cache->loadKunden($order_data['k_id']); 

			// Hausnummer aus Straße extrahieren da wir nur ein Feld verwenden
			$strStrasse = preg_replace("/(\d|\040)*$/", "", $customer_data['strasse']);
			$strNummer = str_replace($strStrasse, "", $customer_data['strasse']);
			
			// Land auflösen
			$strLand = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($customer_data['land'])."'");
			
			// Land ist Pflichtfeld sollte es nicht definiert sein setze ich es auf DE müsste eventuell in die Konf 
			if ($strLand == '') $strLand = "DE";

			$shipping_firma = $customer_data['firma']; 
			$shipping_firstname = $customer_data['vname'];
			$shipping_lastname = $customer_data['name'];
			$shipping_street = $strStrasse;
			$shipping_houseNumber = $strNummer;
			$shipping_postcode = $customer_data['plz'];
			$shipping_city = $customer_data['ort'];
			$shipping_country = $strLand;
			
			if 
				(	
					$this->shop->hasMod('wpsg_mod_shippingadress') && 
					(	
						$order_data['shipping_firma'] != '' && $order_data['shipping_firma'] != $shipping_firma && 
						$order_data['shipping_name'] != '' && $order_data['shipping_name'] != $shipping_lastname && 
						$order_data['shipping_vname'] != '' && $order_data['shipping_vname'] != $shipping_firstname
					)
				)
			{
  
				// Hausnummer aus Straße extrahieren da wir nur ein Feld verwenden
				$strShippingStrasse = preg_replace("/(\d|\040)*$/", "", $order_data['shipping_strasse']);
				$strShippingNummer = str_replace($strStrasse, "", $order_data['shipping_strasse']);
				
				$shipping_firma = $order_data['shipping_firma'];
				$shipping_firstname = $order_data['shipping_name'];
				$shipping_lastname = $order_data['shipping_vname'];
				$shipping_street = $strShippingStrasse;
				$shipping_houseNumber = $strShippingNummer;
				$shipping_postcode = $order_data['shipping_plz'];
				$shipping_city = $order_data['shipping_ort'];
				
				if ($order_data['shipping_land'] > 0)
					$shipping_country = $this->db->fetchOne("SELECT L.`kuerzel` FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($order_data['shipping_land'])."'"); 
				
			}
			
			require_once dirname(__FILE__).'/mod_billsafe/Billsafe/Sdk.php';
				
			$arParam = array( 
				'isLiveMode' => (($this->shop->get_option('wpsg_mod_billsafe_sandbox') == 1)?false:true),
				'isUtf8Mode' => true,
				'apiVersion' => '206',
				'gatewayVersion' => '200',

				'order_number'              => $order_data['onr'],
			    'order_amount'              => wpsg_round(wpsg_tf($arBasket['sum']['preis_gesamt_brutto']), 2), // Summe aller Artikel, Umsatzsteuer und Versandkosten
			    'order_taxAmount'           => wpsg_round(wpsg_tf($arBasket['sum']['mwst']), 2), // Summe aller Umsatzsteuerbeträge
			    'order_currencyCode'        => $this->shop->get_option('wpsg_mod_billsafe_currency'),
			
			    'customer_id'               => $kunde_id,
			    'customer_gender'           => 'm', // Geschlecht m/w  
					'customer_company'			=> $customer_data['firma'],
			    'customer_firstname'        => $customer_data['vname'],
			    'customer_lastname'         => $customer_data['name'],
			    'customer_street'           => $strStrasse,
			    'customer_houseNumber'      => $strNummer,
			    'customer_postcode'         => substr($customer_data['plz'], 0, 5),
			    'customer_city'             => $customer_data['ort'],
			    'customer_country'          => $strLand,
			    'customer_dateOfBirth'      => ((strtotime($customer_data['geb']) > 0)?$customer_data['geb']:''),
			    'customer_email'            => $customer_data['email'],
			    'customer_phone'            => $customer_data['tel'],
			
					'deliveryAddress_gender'		=> 'm',
					'deliveryAddress_company' 	=> $shipping_firma,
					'deliveryAddress_firstname' => $shipping_firstname,
					'deliveryAddress_lastname' 	=> $shipping_lastname,
					'deliveryAddress_street' 	=> $shipping_street,
					'deliveryAddress_houseNumber' => $shipping_houseNumber,
					'deliveryAddress_postcode' 	=> $shipping_postcode,
					'deliveryAddress_city' 		=> $shipping_city,
					'deliveryAddress_country' 	=> $shipping_country,
			
			    'product'                   => 'invoice',
			    'url_return'                => get_permalink($this->shop->get_option('wpsg_mod_billsafe_success')),
			    'url_cancel'                => get_permalink($this->shop->get_option('wpsg_mod_billsafe_error')),
			    'url_image'                 => $this->shop->get_option('wpsg_mod_billsafe_logo')
			);
			
			$index = 0;
			foreach ($arBasket['produkte'] as $op)
			{
				
				if (preg_match('/^vp_(.*)/', $op['id']))
				{
					$produkt_id = preg_replace('/(^vp_)|(\/(.*)$)/', '', $op['id']);
				}
				else
				{
					$produkt_id = $op['id'];
				}
				
				$produkt_data = $this->shop->cache->loadProduct($produkt_id);
				
				$product_name = $produkt_data['name'];
				$product_description = $produkt_data['beschreibung'];
				
				// Übersetzung checken
				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)
					{
						
						$product_name = $produkt_trans['name'];
						$product_description = $produkt_trans['beschreibung'];
						
					}
					
				}
				
				$arParam = wpsg_array_merge($arParam, array(
					'articleList_'.$index.'_number' => $index,
					'articleList_'.$index.'_name' => $product_name,
					'articleList_'.$index.'_description' => $product_description,
					'articleList_'.$index.'_type' => 'goods',
					'articleList_'.$index.'_quantity' => $op['menge'],
					'articleList_'.$index.'_netPrice' => wpsg_round($op['preis_netto'], 2),
					'articleList_'.$index.'_tax' => wpsg_round($op['mwst_value'], 2) // an diese Stelle gehört der mwst Satz Bsp '19.00' = 19%
				));
				
				$index ++;
				
			}
			
			// Versandkosten
			if ($arBasket['sum']['preis_shipping_brutto'] > 0)
			{
									
				if (isset($arBasket['shipping']['mwst'])) 
				{
					// diese IF Abfrage wird nie erreicht, das Array "$arBasket['shipping']" gibt es nicht -> Vermutung: es muss "$arBasket['mwst']" heißen...
					
					// Fixer Satz 
					$arParam = wpsg_array_merge($arParam, array(
						'articleList_'.$index.'_number' => $index,
						'articleList_'.$index.'_name' => __('Versandkosten', 'wpsg'),
						'articleList_'.$index.'_description' => __('Versandkosten', 'wpsg'),
						'articleList_'.$index.'_type' => 'shipment',
						'articleList_'.$index.'_quantity' => 1,
						'articleList_'.$index.'_netPrice' => wpsg_round($arBasket['sum']['preis_shipping_netto'], 2),
						'articleList_'.$index.'_tax' =>wpsg_round($arBasket['shipping']['mwst'], 2) // an diese Stelle gehört der mwst Satz Bsp '19.00' = 19%
					));
					$index ++;
					
				}
				else
				{
					
					// TODO: Anteilig
					
				}
									
			}
			
			// Zahlungskosten
			if ($arBasket['sum']['preis_payment_brutto'] > 0)
			{

				if (isset($arBasket['payment']['mwst']))
				{
				
					// Fixer Satz
					$arParam = wpsg_array_merge($arParam, array(
						'articleList_'.$index.'_number' => $index,
						'articleList_'.$index.'_name' => __('Zahlungsaufschlag', 'wpsg'),
						'articleList_'.$index.'_description' => __('Zahlungsaufschlag', 'wpsg'),
						'articleList_'.$index.'_type' => 'handling',
						'articleList_'.$index.'_quantity' => 1,
						'articleList_'.$index.'_netPrice' => wpsg_round($arBasket['sum']['preis_payment_netto'], 2),
						'articleList_'.$index.'_tax' => wpsg_round($arBasket['payment']['mwst'], 2)
					));					
					$index ++;
					
				}
				else
				{
					
					// TODO: Anteilig
					
				}
									
			}
			
			if (wpsg_isSizedArray($arBasket['gs']) && $arBasket['gs']['value'] > 0)
			{
				
				$arParam = wpsg_array_merge($arParam, array(
					'articleList_'.$index.'_number' => $index,
					'articleList_'.$index.'_name' => __('Gutschein/Rabatt', 'wpsg'),
					'articleList_'.$index.'_description' => __('Gutschein/Rabatt', 'wpsg'),
					'articleList_'.$index.'_type' => 'voucher',
					'articleList_'.$index.'_quantity' => 1,
					'articleList_'.$index.'_netPrice' => wpsg_round($arBasket['gs']['value'], 2),
					'articleList_'.$index.'_tax' => 0
				));
				$index ++;
				
			}
			
			$arParam = wpsg_array_merge($arParam, array(
				'custom_0' => $order_data['id'],
				'custom_1' => $customer_data['k_id'],
				'custom_2' => ''
			));
			  
			$bs = new Billsafe_Sdk();

			$arParam['merchant_id'] = $this->shop->get_option('wpsg_mod_billsafe_vendorID');
			$arParam['merchant_license'] = $this->shop->get_option('wpsg_mod_billsafe_licencesandbox');
			$arParam['application_signature'] = $this->shop->get_option('wpsg_mod_billsafe_appkey');
								
			$bs->setCredentials(
				array(
		    		'merchantId' => $this->shop->get_option('wpsg_mod_billsafe_vendorID'),
		    		'merchantLicenseSandbox' => $this->shop->get_option('wpsg_mod_billsafe_licencesandbox'),
		    		'merchantLicenseLive' => $this->shop->get_option('wpsg_mod_billsafe_licence'),
		    		'applicationSignature' => $this->applicationSignature,
					'applicationVersion' => 'wpShopGermany Versio '.WPSG_VERSION
				)
			);
			 
			$bs->setUtf8Mode(true);
			$bs->setMode((($this->shop->get_option('wpsg_mod_billsafe_sandbox') == 1)?false:Billsafe_Sdk::LIVE));
		 			 
			$response = $bs->callMethod('prepareOrder', $arParam);
 
			if ($response->ack != "OK")
			{
				 
				ob_start();
				var_dump($response);
				$errortext = ob_get_contents();
				ob_end_clean();
				
				$this->db->ImportQuery(WPSG_TBL_OL, array(
					"o_id" => wpsg_q($order_id),
					"cdate" => "NOW()",	
					"title" => __('Fehler in Übermittelung an Billsafe', 'wpsg'),
					"mailtext" => $errortext.print_r($arParam, 1)
				) );
				
				return false;
				
			}
			else
			{
				
				$strToken = $response->token;
				
				// Token in die Datenbank schreiben
				$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
					'mod_billsafe_token' => wpsg_q($strToken)
				), "`id` = '".wpsg_q($order_id)."'");

				return $strToken;
				
			}
			
		} // public function genTokenForOrder($order_id, $arBasket)

		/*
 		 * Gibt den Absoluten Pfad zurück wo die Billsafe 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())
			{

				$htaccess = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_billsafe/.htaccess';
				$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_billsafe/'.$order_id.'/'; 
				if (!file_exists($path)) mkdir($path, 0777, true); 
				
				if ($url)
				{
					
					$url = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_billsafe/'.$order_id.'/';
					 
				} 
				 
			}
			else
			{
				
				$htaccess = WP_CONTENT_DIR.'/uploads/wpsg_billsafe/.htaccess';
				$path = WP_CONTENT_DIR.'/uploads/wpsg_billsafe/'.$order_id.'/';
				if (!file_exists($path)) mkdir($path, 0777, true);
				
				if ($url) 
				{
					
					$url = WPSG_URL_CONTENT.'uploads/wpsg_billsafe/'.$order_id.'/';
					
				}
				
			} 
			 
 			if (!file_exists($htaccess))
			{
				
				$handle = fopen($htaccess, "w+");
				
				$content = 'Deny from all';
							
				fwrite($handle, $content, strlen($content));
				fclose($handle);
				
			}
			
			if ($url !== false)
			{
				
				return $url;
				
			}
			
			return $path;
			 
 		} // private function getFilePath($produkt_id, $url = false)
		
	} // class wpsg_mod_billsafe extends wpsg_mod_basic

?>