<?php

	/**
	 * Klasse die die Zahlungsart Click&Buy ermöglicht
	 * @author daniel
	 */
	class wpsg_mod_cab extends wpsg_mod_basic 
	{
		
		var $lizenz = 2;
		var $id = 810; 
		
		var $version = "9.9.9";
		var $hilfeURL = 'http://wpshopgermany.de/?p=969';		 
		var $free = true;
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Click & Buy', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlungsart ClickandBuy.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{
			
			$this->shop->checkDefault('wpsg_mod_cab_bezeichnung', $this->name, false, true);
			$this->shop->checkDefault('wpsg_mod_cab_bezeichnung', '', false, true);
			$this->shop->checkDefault('wpsg_mod_cab_aktiv', '1');
			$this->shop->checkDefault('wpsg_mod_cab_sandbox', '1');
			$this->shop->checkDefault('wpsg_mod_cab_hint', __('Wickeln Sie ihre Bestellung über Click&Buy ab.', 'wpsg'), false, true);
			
			$this->shop->checkDefault('wpsg_mod_cab_merchantID', '<!-- Erhalten Sie von Click&Buy --!>');
			$this->shop->checkDefault('wpsg_mod_cab_projectID', '<!-- Erhalten Sie von Click&Buy --!>');
			$this->shop->checkDefault('wpsg_mod_cab_kryptkey', '<!-- Erhalten Sie von Click&Buy --!>');
			
			$this->shop->checkDefault('wpsg_mod_cab_mmskryptkey', '<!-- Erhalten Sie von Click&Buy --!>');
			$this->shop->checkDefault('wpsg_mod_cab_mmsstatusmail', '');
			
			$this->shop->checkDefault('wpsg_mod_cab_mmskryptkey', '');
			$this->shop->checkDefault('wpsg_mod_cab_mmsstatusmail', '');
			
			$this->shop->checkDefault('wpsg_mod_cab_gebuehr', '0');
			$this->shop->checkDefault('wpsg_mod_cab_mwst', '0');
			$this->shop->checkDefault('wpsg_mod_cab_mwstland', '0');
			
			$this->shop->checkDefault('wpsg_mod_cab_currency', 'EUR');
			$this->shop->checkDefault('wpsg_mod_cab_autorun', '0');
			
			// Bestelltabelle erweitern
		  	require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			$sql = "CREATE TABLE ".WPSG_TBL_ORDER." (
		   		cab_externalid varchar(255) NOT NULL,
   				cab_requestTrackingID varchar(255) NOT NULL,
   				cab_transactionID varchar(255) NOT NULL,
			   	cab_transactionStatus varchar(255) NOT NULL,
		   		cab_started datetime NOT NULL,
   				cab_lastupdate datetime NOT NULL,
		   		cab_paylink varchar(5000) NOT NULL,
   				cab_repayed double(10,2) NOT NULL
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			 
			dbDelta($sql);
			 
			// Tabelle für Click&Buy Log 			
			$sql = "CREATE TABLE ".WPSG_TBL_CABLOG." (
		   		id mediumint(9) NOT NULL AUTO_INCREMENT,
			  	cdate datetime NOT NULL,
			  	extID varchar(255) NOT NULL,
			  	transID varchar(255) NOT NULL,
			  	eventID int(11) NOT NULL,
			  	oldState varchar(255) NOT NULL,
			  	newState varchar(255) NOT NULL,
			  	PRIMARY KEY  (id)	  
		   	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
		} // public function install()
		
		public function delOrder(&$order_id) { } // public function delOrder(&$order_id)
		
		public function settings_edit()
		{
						
			$pages = get_pages();
			 
			foreach ($pages as $k => $v)
			{
				
				$this->shop->view['pages'][$v->ID] = $v->post_title.' (ID:'.$v->ID.')';
				$this->shop->view['pageURLs'][$v->ID] = get_permalink($v->ID);
				
			}
			
			$basket_link = get_permalink(get_option('wpsg_page_basket'));
			
			if (strpos($basket_link, "?") > 0)
			{
				$mmsURL = $basket_link."&wpsg_plugin=wpsg_mod_cab&confirm=mms&no_head=1";
			}
			else
			{
				$mmsURL = $basket_link."?wpsg_plugin=wpsg_mod_cab&confirm=mms&no_head=1";
			}
			
			$this->shop->view['wpsg_mod_cab_mmspushurl'] = preg_replace("/^http:/", "https:", $mmsURL);
						
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_cab_bezeichnung', $_REQUEST['wpsg_mod_cab_bezeichnung']);
			$this->shop->update_option('wpsg_mod_cab_auftragsbezeichnung', $_REQUEST['wpsg_mod_cab_auftragsbezeichnung']);
			$this->shop->update_option('wpsg_mod_cab_aktiv', $_REQUEST['wpsg_mod_cab_aktiv']);
			$this->shop->update_option('wpsg_mod_cab_sandbox', $_REQUEST['wpsg_mod_cab_sandbox']);
			$this->shop->update_option('wpsg_mod_cab_hint', $_REQUEST['wpsg_mod_cab_hint']);
			
			$this->shop->update_option('wpsg_mod_cab_merchantID', $_REQUEST['wpsg_mod_cab_merchantID']);
			$this->shop->update_option('wpsg_mod_cab_projectID', $_REQUEST['wpsg_mod_cab_projectID']);
			$this->shop->update_option('wpsg_mod_cab_kryptkey', $_REQUEST['wpsg_mod_cab_kryptkey']);
			
			$this->shop->update_option('wpsg_mod_cab_mmskryptkey', $_REQUEST['wpsg_mod_cab_mmskryptkey']);
			$this->shop->update_option('wpsg_mod_cab_mmsstatusmail', $_REQUEST['wpsg_mod_cab_mmsstatusmail']);
			
			$this->shop->update_option('wpsg_mod_cab_success', $_REQUEST['wpsg_mod_cab_success']);
			$this->shop->update_option('wpsg_mod_cab_error', $_REQUEST['wpsg_mod_cab_error']);
			
			$this->shop->update_option('wpsg_mod_cab_gebuehr', $_REQUEST['wpsg_mod_cab_gebuehr']);
			$this->shop->update_option('wpsg_mod_cab_mwst', $_REQUEST['wpsg_mod_cab_mwst']);
			$this->shop->update_option('wpsg_mod_cab_mwstland', $_REQUEST['wpsg_mod_cab_mwstland']);
			
			$this->shop->update_option('wpsg_mod_cab_currency', $_REQUEST['wpsg_mod_cab_currency']);
			$this->shop->update_option('wpsg_mod_cab_autorun', $_REQUEST['wpsg_mod_cab_autorun']);
			
			$this->shop->addTranslationString('wpsg_mod_cab_bezeichnung', $_REQUEST['wpsg_mod_cab_bezeichnung']);
			$this->shop->addTranslationString('wpsg_mod_cab_auftragsbezeichnung', $_REQUEST['wpsg_mod_cab_auftragsbezeichnung']);
			$this->shop->addTranslationString('wpsg_mod_cab_hint', $_REQUEST['wpsg_mod_cab_hint']);
			
		} // public function settings_save()
		
		public function addPayment(&$arPayment) 
		{
		
			if (!is_admin() && $this->shop->get_option('wpsg_mod_cab_aktiv') != '1') return;
			
			$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_cab_mwst'), $this->shop->getDefaultCountry());
			
			$arPayment[$this->id] = array(
				'id' => $this->id,
				'name' => __($this->shop->get_option('wpsg_mod_cab_bezeichnung'), 'wpsg'),
				'preis' => $this->shop->get_option('wpsg_mod_cab_gebuehr'),
				'mwst' => $this->shop->get_option('wpsg_mod_cabmwst'),
				'mwst_value' => $mwst_value,
				'mwst_null' => $this->shop->get_option('wpsg_mod_cab_mwstland'),
				'hint' => __($this->shop->get_option('wpsg_mod_cab_hint')),
				'logo' => WPSG_URL_CONTENT.'plugins/wpshopgermany/views/gfx/cab.png' 
			);
			
			if (isset($_REQUEST['wpsg_checkout2']))
			{

				$arBasket = $this->shop->basket->toArray();
				 
				if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO || $arBasket['noMwSt'])
				{
						
					$payment_netto = $this->getPreis($this->shop->get_option('wpsg_mod_cab_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_cab_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 order_view_content($order_id)
		{
			
			$order_data = $this->shop->cache->LoadOrder($order_id);
			
			if ($order_data['type_payment'] != $this->id) return false;
			
			$this->shop->view['wpsg_mod_cab']['order'] = $order_data;
			$this->shop->view['wpsg_mod_cab']['content'] = $this->order_view_content_inner($order_id); 
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/order_view_content.phtml');
			
		} // public function order_view_content($order_id)

		public function order_ajax()
		{
			
			 if ($_REQUEST['cmd'] == 'refresh')
			 {
			 	 
				$this->getPaymentStatus($_REQUEST['edit_id']);
				$this->shop->cache->clearOrderCache($_REQUEST['edit_id']);
				
				die($this->order_view_content_inner($_REQUEST['edit_id']));
			 	
			 }
			 else if ($_REQUEST['cmd'] == 'rebuild')
			 {
			 	
			 	$order_data = $this->shop->cache->loadOrder($_REQUEST['edit_id']);			 	
			 	$customer_data = $this->shop->cache->loadKunden($order_data['k_id']);
			 	
			 	$arBasket = $this->shop->cache->loadBasketArray($_REQUEST['edit_id']);
			 	
			 	$this->shop->view['wpsg_mod_cab']['payLink'] = $this->startPayment($arBasket, $order_data['id'], $order_data['k_id']);
				 
			 	$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
			 		'cab_paylink' => $this->shop->view['wpsg_mod_cab']['payLink']
			 	), "`id` = '".wpsg_q($_REQUEST['edit_id'])."'");
			 	
			 	$this->shop->cache->clearOrderCache($_REQUEST['edit_id']);
			 	
			 	$this->shop->view['wpsg_mod_cab']['order'] = $order_data;
			 	$this->shop->view['wpsg_mod_cab']['customer'] = $customer_data;
			 	
				$tpl = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/mail_resend.phtml', false);
				
				$empfaenger = $customer_data['email'];
				$betreff = __("Neuer ClickandBuy Bezahl Link", "wpsg");
				
				mail($empfaenger, $betreff, $tpl);
				
				$this->db->ImportQuery(WPSG_TBL_OL, array(
					"cdate" => "NOW()",
					"o_id" => wpsg_q($_REQUEST['edit_id']),
					"title" => $betreff,				
					"mailtext" => $tpl
				));
				
				die($this->order_view_content_inner($_REQUEST['edit_id']));
			 	
			 }
			 else if ($_REQUEST['cmd'] == 'repay')
			 {
			 	
			 	$repay = wpsg_tf($_REQUEST['value']);
				
			 	$order_data = $this->shop->cache->loadOrder($_REQUEST['edit_id']);
			 	
				// Value checken
				if ($repay > ($order_data['price_gesamt'] - $order_data['cab_repayed']))
				{				
					$this->strError = __("Der angefragte Rückzahlungsbetrag ist größer als der noch nicht zurückgezahlte Betrag!", "wpsg");
				}
				else if ($repay <= 0 || $repay == "")
				{
					$this->strError = __("Der angefragte Rückzahlungsbetrag muss größer als 0 sein!", "wpsg");
				}
				else 
				{
					
					$bReturn = $this->refundPayment($_REQUEST['edit_id'], $repay);
					
					if (!$bReturn)
					{
						$this->strError = __("Es gab technische Probleme, die Rückzahlung konnte nicht ausgeführt werden.", "wpsg");
					}
					else
					{
						
						$this->db->UpdateQuery(WPSG_TBL_OL, array(
							"cab_repayed" => ($order_data['cab_repayed'] + $repay)
						), "`id` = '".wpsg_q($_REQUEST['edit_id'])."'");
						
					}
					
				}
				
				die($this->order_view_content_inner($_REQUEST['edit_id']));
			 	
			 }
			
		} // public function order_ajax()
		
		public function wp_loaded() 
		{ 
				   
			if ($_REQUEST['wpsg_plugin'] == 'wpsg_mod_cab' && $_REQUEST['cab'] == 'success')
			{

				$this->shop->redirect(get_permalink($this->shop->get_option('wpsg_mod_cab_success')));
				
			}
			else if ($_REQUEST['wpsg_plugin'] == 'wpsg_mod_cab' && $_REQUEST['cab'] == 'error')
			{
				
				$this->shop->redirect(get_permalink($this->shop->get_option('wpsg_mod_cab_error')));
				
			}
			else if ($_REQUEST['wpsg_plugin'] == 'wpsg_mod_cab' && $_REQUEST['confirm'] == 'mms')			
			{
				
				$_REQUEST['xml'] = stripslashes($_REQUEST['xml']);
				$xml = simplexml_load_string($_REQUEST['xml']);
				
				$signature = $xml->signature;
				$npayEvents = sizeof($xml->{payEvent});

				// Hash überprüfen
				$bOK = $this->makeMMSHash($_REQUEST['xml'], get_option('wpsg_mod_cab_mmskryptkey'));
				
				if ($bOK && isset($_REQUEST['xml']))
				{
				
					$nUpdated = 0;
					foreach ($xml->{payEvent} as $payEvent)
					{
				
						$creationDateTime = strtotime($payEvent->{"creationDateTime"});
						 
						$order = $this->db->fetchRow("
							SELECT 
								*,
								UNIX_TIMESTAMP(`cab_lastupdate`)
							FROM
								`".WPSG_TBL_ORDER."`
							WHERE
								`cab_externalid` = '".wpsg_q($payEvent->{"externalID"})."' AND
								`cab_transactionID` = '".wpsg_q($payEvent->{"transactionID"})."' AND
								UNIX_TIMESTAMP(`cab_lastupdate`) < '".wpsg_q($creationDateTime)."' 
						"); 
						
						if (is_array($order) && $order['id'] > 0)
						{
								
							// Ins Protokoll eintragen wenn noch nicht drin
							$bExists = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_OL."` WHERE `extID` = '".wpsg_q_($order['cab_externalid'])."' AND `eventID` = '".wpsg_q($payEvent->{"eventID"})."'");
							
							if ($bExists <= 0)
							{
								
								$this->db->updateQuery(
									WPSG_TBL_OL,
									array(
										"cab_lastupdate" => "NOW()",
										"cab_transactionStatus" => wpsg_q($payEvent->{"newState"})
									)
								);
								
								$this->db->ImportQuery(
									WPSG_TBL_CABLOG,
									array(
										"cdate" => "NOW()",
										"extID" => wpsg_q($payEvent->{"externalID"}),
										"transID" => wpsg_q($payEvent->{"transactionID"}),
										"eventID" => wpsg_q($payEvent->{"eventID"}),
										"oldState" => wpsg_q($payEvent->{"oldState"}),
										"newState" => wpsg_q($payEvent->{"newState"})
									)
								);							
								
							}
							
							$nUpdated ++;
							
						}
						
					}
					
					if (get_option("wpsg_mod_cab_mmsstatusmail") != "")
					{
						
						// Hinweismail an angegebene Mail Adresse senden 
						$this->view['wpsg_mod_cab']['nUpdated'] = $nUpdated;
						$this->view['wpsg_mod_cab']['xml'] = $_REQUEST['xml'];
						
						$tpl = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/mail_mms.phtml', false);
						  
						mail(get_option("wpsg_mod_cab_mmsstatusmail"), __("Neue MMS Statusänderungen ERFOLG", "wpsg"), $tpl, $header);
												
					}
					
					die("OK");
					
				}
				else
				{

					if (get_option("wpsg_mod_cab_mmsstatusmail") != "")
					{
						
						$this->view['wpsg_mod_cab']['hash'] = $hash;
						$this->view['wpsg_mod_cab']['xml'] = $_REQUEST['xml'];
						
						$tpl = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/mail_mms_error.phtml', false);
						  
						mail(get_option("wpsg_mod_cab_mmsstatusmail"), __("Neue MMS Statusänderungen FEHLER", "wpsg"), $tpl, $header);
						
					}
					
				}
				
			}
			
		} // public function wp_loaded() 
		
		public function calcPayment(&$arBasket) 
		{ 
			
			if ($arBasket['checkout']['payment'] == $this->id)
			{
			 
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_cab_gebuehr'), $arBasket['sum']['preis']);
				
				if ($this->shop->get_option('wpsg_mod_cab_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_cab_mwst'));

				}
								
			}
			
		} // public function calcPayment(&$arBasket) 
 		
		public function basket_save_done_array(&$order_id, &$kunde_id, &$arBasket) 
		{ 
			 	 
			if ($arBasket['checkout']['payment'] == $this->id)
			{
			
				$this->startPayment($arBasket, $order_id, $kunde_id);
				
			}
			 
		} // public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
				
		public function order_done(&$order_id, &$done_view) 
		{
			
			// Bestellungen mit 0 geben nix aus
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;
			
			$order_data = $this->shop->cache->loadOrder($order_id);
			 			
			if ($order_data['type_payment'] != $this->id) return;
			
			$this->shop->view['wpsg_mod_cab']['url'] = $order_data['cab_paylink'];
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/order_done.phtml');
			
		}  // public function order_done($order_id)
		 		
		/** Modufunctionen */
		
		/**
		 * Zeichnet den inneren Teil, der mit Ajax nachgeladen wird
		 */
		public function order_view_content_inner($order_id)
		{

			$order_data = $this->shop->cache->LoadOrder($order_id);
			
			if ($order_data['type_payment'] != $this->id) return false;
			
			$this->shop->view['wpsg_mod_cab']['order'] = $order_data;
			
			if (isset($this->strError)) $this->shop->view['wpsg_mod_cab']['strError'] = $this->strError;
			 
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_cab/order_view_content_inner.phtml', false);
			
		} // public function order_view_content_inner($order_id)
				
		/**
		 * Startet einen Bezahlvorgang und gibt den Link zum bezahlen zurück
		 * @param unknown_type $order
		 */
		private function startPayment($arBasket, $order_id, $kunde_id)
		{
 
			$basket_link = get_permalink($this->shop->get_option('wpsg_page_basket'));
			
			if (strpos($basket_link, "?") > 0)
			{
				$successURL = $basket_link."&wpsg_plugin=wpsg_mod_cab&cab=success&order_id=".$order_id;
			}
			else
			{
				$successURL = $basket_link."?wpsg_plugin=wpsg_mod_cab&cab=success&order_id=".$order_id;
			}
			
			if (strpos($basket_link, "?") > 0)
			{
				$failureURL = $basket_link."&wpsg_plugin=wpsg_mod_cab&cab=error&order_id=".$order_id;
			}
			else
			{
				$failureURL = $basket_link."?wpsg_plugin=wpsg_mod_cab&cab=error&order_id=".$order_id;
			}
			
			//wpsg_debug("SUCCESSLINK:".$successURL);
			//wpsg_debug("FAILURELINK:".$failureURL);
			
			$externalID = time().":".$order_id;
					
			// ClickandBuy Authentifizierung
			$authentication = array();
			$authentication['merchantID'] = $this->shop->get_option("wpsg_mod_cab_merchantID");
			$authentication['projectID'] = $this->shop->get_option("wpsg_mod_cab_projectID");
			$authentication['secretKey'] = $this->shop->get_option("wpsg_mod_cab_kryptkey");
			$authentication['token'] = $this->generateToken($authentication['projectID'], $authentication['secretKey']);
			
			foreach ($arBasket['produkte'] as $p)
			{
				
				if (preg_match('/^vp_(.*)/', $p['id']))
				{
					
					$produkt_id = preg_replace('/(^vp_)|(\/(.*)$)/', '', $op['id']);
					
				}
				else
				{
					
					$produkt_id = $p['id'];
					
				}
				
				$produkt_db = $this->shop->cache->loadProduct($produkt_id);
				
				$product_name = $produkt_db['name']; 
				
				// Ü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']; 
						
					}
					
				}
				
				$item = array();
				$item['description'] = $product_name;	
				$item['itemType'] = "ITEM";		
				$item['quantity'] = $p['menge'];
				$item['unitPrice']['amount'] = number_format($p['preis_brutto'], 2, '.', '');
				$item['unitPrice']['currency'] = $this->shop->get_option("wpsg_mod_cab_currency");
				$item['totalPrice']['amount'] = number_format($p['menge'] * $p['preis_brutto'], 2, '.', '');
				$item['totalPrice']['currency'] = $this->shop->get_option("wpsg_mod_cab_currency");
 
				$arItems[] = $item; 

				$itemPrice += $p['menge'] * $p['preis_brutto'];
				
			}
			
			$plus = $arBasket['sum']['preis_gesamt_brutto'] - $itemPrice;
			
			if ($plus > 0)
			{
				
				$item = array();				
				$item['description'] = __("Versandkosten und Aufschläge", "wpsg");
				$item['itemType'] = "ITEM";
				$item['quantity'] = "1";
				$item['unitPrice']['amount'] = number_format($plus, 2, '.', '');
				$item['unitPrice']['currency'] = get_option("wpsg_mod_cab_currency");
				$item['totalPrice']['amount'] = number_format($plus, 2, '.', '');
				$item['totalPrice']['currency'] = get_option("wpsg_mod_cab_currency");
				 
				$arItems[] = $item;
				
			}
			
			$details = array();
			$details['consumerLanguage'] = "de";
						
			$details['amount'] = array();
			$details['amount']['amount'] = number_format($arBasket['sum']['preis_gesamt_brutto'], 2, '.', '');
			$details['amount']['currency'] = get_option("wpsg_mod_cab_currency");	
			
			$details['successURL'] = $successURL;
			$details['failureURL'] = $failureURL;
			
			$details['externalID'] = $externalID;
			
			$details['orderDetails'] = array();
			$details['orderDetails']['itemList'] = $arItems;
			$details['orderDetails']['text'] = $this->shop->replaceUniversalPlatzhalter($this->shop->get_option("wpsg_mod_cab_auftragsbezeichnung"), $order_id);
 			
			$kunde = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_KU."` WHERE `id` = '".wpsg_q($kunde_id)."'");
			
			$details['shipping']['consumer'] = array(
				'firstName' => $kunde['shipping_vname'],
				'lastName' => $kunde['shipping_name'],
				'address' => array(
					'street' => $kunde['shipping_strasse'],
					'zip' => $kunde['shipping_plz'],
					'city' => $kunde['shipping_ort'],
					'country' => $this->db->fetchOne("SELECT `kuerzel` FROM `".WPSG_TBL_LAND."` WHERE `id` = '".wpsg_q($kunde['shipping_land'])."'")				
				)			
			);
			
			$details['billing']['consumer'] = array(
				'firstName' => $kunde['vname'],
				'lastName' => $kunde['name'],
				'address' => array(
					'street' => $kunde['strasse'],
					'zip' => $kunde['plz'],
					'city' => $kunde['ort'],
					'country' => $this->db->fetchOne("SELECT `kuerzel` FROM `".WPSG_TBL_LAND."` WHERE `id` = '".wpsg_q($kunde['land'])."'")			
				)
			);
			
			// Wenn kein Name und Vorname bei der Lieferanschrift gesetzt gehe ich davon aus, das die Lieferanschrift gleich der Rechnugsanschrift ist
			if ($kunde['shipping_vname'] == "" && $kunde['shipping_name'] == "")
			{
				
				$details['shipping']['consumer'] = array(
					'firstName' => $kunde['vname'],
					'lastName' => $kunde['name'],
					'address' => array(
						'street' => $kunde['strasse'],
						'zip' => $kunde['plz'],
						'city' => $kunde['ort'],
						'country' => $this->db->fetchOne("SELECT `kuerzel` FROM `".WPSG_TBL_LAND."` WHERE `id` = '".wpsg_q($kunde['land'])."'")			
					)
				);
				
			}
			
			$soap_data = array(
				"authentication" => $authentication,
				"details" => $details
			); 
		
			$client = $this->getClient(); 
			$result = $client->payRequest($soap_data);
						
			// Daten in Bestellung eintragen
			$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
				"cab_externalid" => $result->transaction->externalID,
				"cab_requestTrackingID" => $result->requestTrackingID,
				"cab_transactionID" => $result->transaction->transactionID,
				"cab_transactionStatus" => $result->transaction->transactionStatus,
				"cab_started" => "NOW()",
				"cab_lastupdate" => "NOW()",
				"cab_paylink" => $result->transaction->redirectURL
			), "`id` = '".wpsg_q($order_id)."'");
			 
			return $result->transaction->redirectURL;
						
		} // private function startPayment($order)
		
		/**
		 * Fragt den PaymentStatus einer Bestellung ab und aktualisiert ihn in der Bestellung
		 * Enter description here ...
		 * @param unknown_type $order_id
		 */
		private function getPaymentStatus($order_id)
		{
			
			$order = $this->shop->cache->LoadOrder($order_id);
			
			// ClickandBuy Authentifizierung
			$authentication = array();
			$authentication['merchantID'] = get_option("wpsg_mod_cab_merchantID");
			$authentication['projectID'] = get_option("wpsg_mod_cab_projectID");
			$authentication['secretKey'] = get_option("wpsg_mod_cab_kryptkey");
			$authentication['token'] = $this->generateToken($authentication['projectID'], $authentication['secretKey']);			
			
			$details = array();
			$details['transactionIDList'] = array();
			$details['transactionIDList']['transactionID'] = $order['cab_transactionID'];
			
			$soap_data = array(
				"authentication" => $authentication,
				"details" => $details
			);  
			 
			$client = $this->getClient();				
			$result = $client->statusRequest($soap_data);		
			
			if ($result->transactionList->transaction->transactionID != $order['cab_transactionID'] || $result->transactionList->transaction->externalID != $order['cab_externalid'])
			{
				
				return false;
				
			}
			
			$this->db->UpdateQuery(WPSG_TBL_ORDER, array(
				"cab_transactionStatus" => $result->transactionList->transaction->transactionStatus,
				"cab_lastupdate" => "NOW()"
			), "`id` = '".wpsg_q($order['id'])."'");
			
			return $result->transactionList->transaction->transactionStatus;
			
		} // private function getPaymentStatus($order_id)
		
		/**
		 * Gibt das Clientobjekt für die SOAP Anfragen zurück
		 */
		private function getClient()
		{
			
			if (get_option("wpsg_mod_cab_sandbox") == "1")
			{
				
				$client = new SoapClient('https://api.clickandbuy.com/webservices/soap/pay_1_0_0.wsdl');
				$client->__setLocation('https://api.clickandbuy-s1.com/webservices/soap/pay_1_0_0');
				
			}
			else
			{
				
				$client = new SoapClient('https://api.clickandbuy.com/webservices/pay_1_0_0.wsdl');
				
			} 
			
			return $client;
			
		} // private function getClient()
		
		function generateToken($projectID, $secretKey) 
		{
			
			$timestamp = gmdate("YmdHis");	
			$hashStr = $projectID."::".$secretKey."::".$timestamp;
			$toBeHashed = strtoupper(sha1($hashStr));	
			$token = $timestamp.'::'.$toBeHashed; 	
			
			return $token;	
			
		} // function generateToken($projectID, $secretKey)

		/**
		 * Generiert den Hash (Signatur) für die MMS Verfikation
		 * @param $xml
		 */
		private function makeMMSHash($xml)
		{
			
			$xml = preg_replace("/\<signature\>(.*)\<\/signature\>/", "<signature />", $xml);
			 
			return sha1(get_option("wpsg_cab_mmskey").$xml);
			
		} // private function makeMMSHash($xml)
				
	} // class wpsg_mod_cab extends wpsg_mod_basic

?>