<?php

	/**
	 * Erlaubt den Verkauf von Abos
	 * @author Daschmi 
	 */
	class wpsg_mod_abo extends wpsg_mod_basic
	{
		
		var $lizenz = 1;
		var $id = 1630;
		var $hilfeURL = 'http://wpshopgermany.de/?p=3292';
		var $version = "9.9.9";
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
								
			parent::__construct();
								
			$this->name = __('AboProdukte', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Ermöglicht den Verkauf von Abo Produkten', 'wpsg');
		
		} // public function __construct()
		
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/**
			 * Produkttabelle erweitern
			*/
			$sql = "CREATE TABLE ".WPSG_TBL_PRODUCTS." (
			  	wpsg_mod_abo_activ int(1) NOT NULL,
				wpsg_mod_abo_resell int(11) NOT NULL,
				wpsg_mod_abo_price DOUBLE(10,2) NOT NULL,
				wpsg_mod_abo_durration int(11) NOT NULL,
				wpsg_mod_abo_url varchar(500) NOT NULL
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
				
			dbDelta($sql);
			
			/**
			 * Abo Tabelle anlegen
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_ABO." (
				id mediumint(9) NOT NULL AUTO_INCREMENT,
	  			cdate datetime NOT NULL,
				order_id int(11) NOT NULL,				
				product_key varchar(255) NOT NULL,
				expiration DATETIME NOT NULL,
				inform_expiration int(1) DEFAULT '0' NOT NULL,	
				rebuy int(11) DEFAULT '0' NOT NULL,					  
				PRIMARY KEY  (id),
	  			KEY order_id (order_id),
				KEY product_key (product_key)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
			/**
			 * Bestelltabelle erweitern um bei Folgebestellungen zu wissen welche die Originalbestellung ist
			 */			
			$sql = "CREATE TABLE ".WPSG_TBL_ORDER." (
				wpsg_mod_abo_origin_order int(11) NOT NULL,
				KEY wpsg_mod_abo_origin_order (wpsg_mod_abo_origin_order)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
			$this->shop->checkDefault('wpsg_wpsgmodabofirstbuy_betreff', __('Sie haben erfolgreich ein Abo erworben', 'wpsg'));
			$this->shop->checkDefault('wpsg_wpsgmodaboexpiration_betreff', __('Ihr Abo ist ausgelaufen', 'wpsg'));
			$this->shop->checkDefault('wpsg_wpsgmodabrebuy_betreff', __('Ihr Abo ist verlängert worden', 'wpsg'));
			
			$this->shop->checkDefault('wpsg_mod_abo_wpsgmodabofirstbuy', '1');
			$this->shop->checkDefault('wpsg_mod_abo_wpsgmodaboexpiration', '1');
			$this->shop->checkDefault('wpsg_mod_abo_wpsgmodabrebuy', '1');
			
		} // public function install()
		
		public function settings_edit() 
		{
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save()
		{
						
			$this->shop->update_option('wpsg_mod_abo_url', $_REQUEST['wpsg_mod_abo_url']);
			
			$this->shop->update_option('wpsg_mod_abo_wpsgmodabofirstbuy', $_REQUEST['wpsg_mod_abo_wpsgmodabofirstbuy']);
			$this->shop->update_option('wpsg_mod_abo_wpsgmodaboexpiration', $_REQUEST['wpsg_mod_abo_wpsgmodaboexpiration']);
			$this->shop->update_option('wpsg_mod_abo_wpsgmodabrebuy', $_REQUEST['wpsg_mod_abo_wpsgmodabrebuy']);
			
		} // public function settings_save()
		
		public function produkt_edit_content(&$product_data)
		{
 
			if (isset($_REQUEST['wpsg_lang'])) return false;
			
			if ($product_data['wpsg_mod_abo_resell'] > 0)
			{
				
				$product_data['wpsg_mod_abo_resell_count'] = $product_data['wpsg_mod_abo_resell'];
				$product_data['wpsg_mod_abo_resell'] = 1;
								
			}
			else
			{
				
				$product_data['wpsg_mod_abo_resell_count'] = '1';
				$product_data['wpsg_mod_abo_resell'] = 0;
				
			}
			
			$this->shop->view['product'] = $product_data;
						
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/produkt_edit_content.phtml');
			
		} // public function produkt_edit_content(&$produkt_data)
		
		public function produkt_save_before(&$product_data)
		{
			
			if (isset($_REQUEST['wpsg_lang'])) return false;
			
			if (isset($_REQUEST['wpsg_mod_abo_activ']) && $_REQUEST['wpsg_mod_abo_activ'] == '1')
			{
				
				$product_data['wpsg_mod_abo_activ'] = '1';
				$product_data['wpsg_mod_abo_price'] = wpsg_tf($_REQUEST['wpsg_mod_abo_price']);
				$product_data['wpsg_mod_abo_durration'] = $_REQUEST['wpsg_mod_abo_durration'];
				$product_data['wpsg_mod_abo_url'] = $_REQUEST['wpsg_mod_abo_url'];
				
				if ($_REQUEST['wpsg_mod_abo_resell'] == '1')
				{
					
					if ($_REQUEST['wpsg_mod_abo_resell_count'] <= 0)
					{
						
						$this->shop->addBackendError(__('Ungültige Anzahl von zulässigen Abokäufen. Wurde auf unendlich gesetzt.', 'wpsg'));
						$product_data['wpsg_mod_abo_resell'] = '0';
						
					}
					else
					{
					
						$product_data['wpsg_mod_abo_resell'] = wpsg_q($_REQUEST['wpsg_mod_abo_resell_count']);
						
					}
					
				}
				else
				{
					
					$product_data['wpsg_mod_abo_resell'] = '0';
					
				}
				
			}
			else
			{
				
				$product_data['wpsg_mod_abo_activ'] = '0';
				
			}
						
		} // public function produkt_save(&$produkt_id)
		
		public function setOrderStatus($order_id, $status_id, $inform)
		{
			 
			if ($status_id == 100)
			{
				
				// Sind in der Bestellung Abo Produkte?				
				$arBasket = $this->shop->cache->loadBasketArray($order_id);
			  
				foreach ($arBasket['produkte'] as $product)
				{
										
					$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($product['productkey']));

					if (substr($product['productkey'], 0, 3) == 'abo')
					{
						
						// BestellID der OriginalBestellung
						$order_base_id = $this->getOrderIDFromKey($product['productkey']);
						
						// Eine Abo Verlängerung wurde gekauft
						$abo_entry = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_base_id)."' AND `product_key` = '".wpsg_q($product['productkey'])."'");
 
						if ($abo_entry['id'] <= 0) die($this->shop->throwErrorCode('1630_2'));						
						if ($product_data['wpsg_mod_abo_resell'] != 0 && $abo_entry['rebuy'] + $product['menge'] > $product_data['wpsg_mod_abo_resell']) die($this->shop->throwErrorCode('1630_3'));

						if (strtotime($abo_entry['expiration']) < time())
						{
							
							// Das Abo ist ausgelaufen
							$abo_expiration = $this->getAboExpiration($product_data['id'], $product['menge'], time());
							
						}
						else
						{
							
							// Abo wurde verlängert und der Zeitraum wird an die alte Verlängerung angehängt
							$abo_expiration = $this->getAboExpiration($product_data['id'], $product['menge'], strtotime($abo_entry['expiration']));
							
						}
						
						$this->db->UpdateQuery(WPSG_TBL_ABO, array(
							'rebuy' => wpsg_q($abo_entry['rebuy'] + $product['menge']),
							'expiration' => $abo_expiration,
							'inform_expiration' => '0'
						), "`id` = '".wpsg_q($abo_entry['id'])."'");
						
						$this->shop->notifyURL($this->getNotifyURL($product_data['id']), $product['productkey'], 1, $order_id, 3, array(
							'typ' => 'abo_rebuy',
							'abo_baseOrderID' => $order_base_id, 
							'abo_kaufdatum' => date('Y-m-d H:i:s', time()),
							'abo_expiration' => $abo_expiration,
						));

						if ($inform == true)
						{
								
							// Mail bei Erstkauf
							$this->sendAboRebuyMail($this->getOrderIDFromKey($product['productkey']), $product['productkey']);
						
						}
						
					}
					else
					{
					
						if ($product_data['wpsg_mod_abo_activ'] == '1')
						{
 						 
							// Existiert ein Eintrag in der Abotabelle schon, so wird dieser gelöscht
							$abo_id = $this->db->fetchOne("SELECT `id` FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_id)."' AND `product_key` = 'abo_".wpsg_q($order_id.'_'.$product['productkey'])."'");
							if ($abo_id > 0) { $this->db->Query("DELETE FROM `".WPSG_TBL_ABO."` WHERE `id` = '".wpsg_q($abo_id)."'"); }
							
							// Es ist ein Abo Produkt in der Bestellung
							$abo_expiration = $this->getAboExpiration($product_data['id'], $product['menge'], time());
													
							$abo_data_db = array(
								'cdate' => 'NOW()',
								'order_id' => wpsg_q($order_id),
								'product_key' => 'abo_'.$order_id.'_'.wpsg_q($product['productkey']),
								'rebuy' => '0',
								'expiration' => wpsg_q($abo_expiration),
								'inform_expiration' => '0'	
							);
							
							$this->db->ImportQuery(WPSG_TBL_ABO, $abo_data_db);
							
							$this->shop->notifyURL($this->getNotifyURL($product_data['id']), $product['productkey'], 1, $order_id, 3, array(
								'typ' => 'abo_firstbuy',
								'abo_kaufdatum' => date('Y-m-d H:i:s', time()),
								'abo_expiration' => $abo_expiration,							
							));
							
							if ($inform == true)
							{
							 
								// Mail bei Erstkauf
								$this->sendAboFirstBuyMail($order_id, $product['id']);
								
							}
							
						}
						
					}
					
				}
				
			}
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		public function basket_save_order(&$data, &$checkout, &$arBasket, $finish_order) 
		{ 
			
			if ($finish_order !== true) return;
			
			foreach ($arBasket['produkte'] as $product)
			{
				
				if (substr($product['productkey'], 0, 3) == 'abo')
				{
					
					// Ein Abo Produkt wurde gekauft
					$arAbo = explode('_', $product['productkey']);
					
					$data['wpsg_mod_abo_origin_order'] = wpsg_q($arAbo[1]);
					
				}
				
			}
			
		} // public function basket_save_order(&$data, &$checkout, &$arBasket, $finish_order)
		
		public function cron()
		{
			
			$arAboExpiration = $this->db->fetchAssoc("
				SELECT
					A.*
				FROM
					`".WPSG_TBL_ABO."` AS A
				WHERE 
					A.`expiration` < NOW() AND
					A.`inform_expiration` != '1'	
			");
			
			foreach ($arAboExpiration as $a)
			{
				
				$product_id = $this->shop->getProduktID($a['product_key']);

				// URL Benachrichtigung
				$this->shop->notifyURL($this->getNotifyURL($product_id), $a['product_key'], 1, $a['order_id'], 3, array(
					'typ' => 'abo_expiration',
					'abo_kaufdatum' => date('Y-m-d H:i:s', time()),
					'abo_expiration' => $a['expiration']
				));
				
				// Mail mit Benachrichtigung senden
				$this->sendAboExpirationMail($a['order_id'], $a['product_key']);
				
				// Damit der Cron das nicht ständig macht
				$this->db->UpdateQuery(WPSG_TBL_ABO, array(
					'inform_expiration' => '1'
				), "`id` = '".wpsg_q($a['id'])."'");
				
			}
			
		} // public function cron()
		
		public function admin_emailconf_save()
		{
				
			wpsg_saveEMailConfig("wpsgmodabofirstbuy");
			wpsg_saveEMailConfig("wpsgmodaboexpiration");
			wpsg_saveEMailConfig("wpsgmodabrebuy");
			
		} // public function admin_emailconf_save()
		
		public function admin_emailconf()
		{
				
			echo wpsg_drawEMailConfig(
				'wpsgmodabofirstbuy',
				__('E-Mail bei erstmaligem Abo Kauf', 'wpsg'),
				__('Diese Mail bekommt der Kunde beim erstmaligen Kauf eines Abos.', 'wpsg')); 
			
			echo wpsg_drawEMailConfig(
				'wpsgmodaboexpiration',
				__('E-Mail bei abgelaufenem Abo', 'wpsg'),
				__('Diese Mail bekommt der Kunde wenn ein Abo ausläuft mit der Möglichkeit es zu verlängern.', 'wpsg'));
			
			echo wpsg_drawEMailConfig(
				'wpsgmodabrebuy',
				__('E-Mail bei verlängertem Abo', 'wpsg'),
				__('Diese Mail bekommt der Kunde wenn er erfolgreich ein Abo verlängert hat.', 'wpsg'));
			 
		} // public function admin_emailconf()
				
		public function wp_loaded()
		{
			
			if (!isset($_REQUEST['mod']) || $_REQUEST['mod'] != 'wpsg_mod_abo') return false;
			
			if (!isset($_REQUEST['product_key']) || !isset($_REQUEST['order_id']))
			{

				$this->shop->throwErrorCode('1630_1');
				return false;
				
			}
			
			//$product_key = 'abo_'.$_REQUEST['order_id'].'_'.$_REQUEST['product_key'];
			$product_key = $_REQUEST['product_key'];
			
			// Kann das Abo verlängert werden?
			$product_data_db = $this->shop->cache->loadProduct($this->shop->getProduktID($_REQUEST['product_key']));
			
			// Wie oft wurde das Abo zu dieser Bestellung bereits verlängert?
			$nAboBuyed = $this->db->fetchOne("SELECT `rebuy` FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($_REQUEST['order_id'])."' AND `product_key` = '".wpsg_q($_REQUEST['product_key'])."'");
									
			// Ist so ein Abo Produkt schon im Warenkorb?
			$nDrin = false;
			if (wpsg_isSizedArray($_SESSION['wpsg']['basket']))
			{
				
				foreach ($_SESSION['wpsg']['basket'] as $p_index => $p)
				{
					
					if ($p['id'] == $product_key) $nDrin = $p_index;
					
				}
				
			}		
			
			if ($nDrin !== false)
			{
				
				if ($product_data_db['wpsg_mod_abo_resell'] != '0' && $nAboBuyed + $_SESSION['wpsg']['basket'][$nDrin]['menge'] + 1 >= $product_data_db['wpsg_mod_abo_resell'])
				{

					// Abo kann nicht mehr verlängert werden
					$this->shop->addFrontendError(__('Das Abo kann nicht mehr verlängert werden. Sie müssen das Produkt erneut erwerben.', 'wpsg'));					
					$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_BASKET));
					
				}
							
				$_SESSION['wpsg']['basket'][$nDrin]['menge'] ++;
				
			}
			else
			{
				
				if ($product_data_db['wpsg_mod_abo_resell'] != '0' && $nAboBuyed + 1 > $product_data_db['wpsg_mod_abo_resell'])
				{
				
					// Abo kann nicht mehr verlängert werden
					$this->shop->addFrontendError(__('Das Abo kann nicht mehr verlängert werden. Sie müssen das Produkt erneut erwerben.', 'wpsg'));
					$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_BASKET));
						
				}
				
				if (!wpsg_isSizedArray($_SESSION['wpsg'])) $_SESSION['wpsg'] = array();
				if (!wpsg_isSizedArray($_SESSION['wpsg']['basket'])) $_SESSION['wpsg']['basket'] = array();
				
				$_SESSION['wpsg']['basket'][] = array(
					'menge' => '1',
					'id' => $product_key											
				);
				
				$product_data = $this->shop->loadProduktArray($this->shop->getProduktID($_REQUEST['product_key']));
				
				$this->shop->addFrontendMessage(wpsg_translate(__('Abo Verlängerung für Produkt #1# eingefügt', 'wpsg'), $product_data['name']));
				
			}
			
			$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_BASKET));
						
		} // public function wp_loaded()
		  
		public function basket_updateProduktFromSession(&$product_index, &$stock)
		{
			
			$product_key = $_SESSION['wpsg']['basket'][$product_index]['id'];
			
			$order_id = $this->getOrderIDFromKey($product_key);
			$product_id = $this->shop->getProduktID($product_key);
			$product_data = $this->shop->cache->loadProduct($product_id);
			
			$nAboBuyed = $this->db->fetchOne("SELECT `rebuy` FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_id)."' AND `product_key` = '".wpsg_q($produkt_id)."'");
				
			if ($nAboBuyed + $stock_neu > $product_data['wpsg_mod_abo_resell'] && $product_data['wpsg_mod_abo_resell'] != '0')
			{
			
				$this->shop->addFrontendError(__('Abo kann nicht mehr so oft verlängert werden!', 'wpsg'));
				$stock = 0;
			
			}
			
		}
				
		public function basket_toArray(&$produkt, $backend = false, $noMwSt = false)  
		{
			
			$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($produkt['id']));
			
			$country = $this->shop->getDefaultCountry();
			$mwst_value = $country->getTax($product_data['mwst_key']);
			
			if (substr($produkt['id'], 0, 3) == 'abo')
			{
		 
				// Produkt im Warenkorb ist eine Verlängerung
				if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO)
				{

					$produkt['preis_netto'] = $product_data['wpsg_mod_abo_price'];
					$produkt['preis_brutto'] = wpsg_calculatePreis($product_data['wpsg_mod_abo_price'], WPSG_BRUTTO, $mwst_value);
						
				}
				else
				{
						
					$produkt['preis_netto'] = wpsg_calculatePreis($product_data['wpsg_mod_abo_price'], WPSG_NETTO, $mwst_value);
					$produkt['preis_brutto'] = $product_data['wpsg_mod_abo_price'];
						
				}
				
			}
			
		} // public function basket_toArray(&$produkt, $backend, $noMwSt)
		
		public function basket_row(&$p, $i)
		{
			
			if (substr($p['id'], 0, 3) == 'abo')
			{
								
				$this->shop->view['wpsg_mod_abo']['order'] = $this->shop->cache->loadOrder($this->getOrderIDFromKey($p['id']));
				$this->shop->view['wpsg_mod_abo']['product'] = $this->shop->cache->loadProduct($this->shop->getProduktID($p['id']));
				$this->shop->view['wpsg_mod_abo']['wpsg_mod_abo_durration_menge'] = $p['menge'] * $this->shop->view['wpsg_mod_abo']['product']['wpsg_mod_abo_durration'];
				
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/basket_row.phtml');
				
			}
			
		} // public function basket_row(&$p, $i)
		
		public function overview_row(&$p, $i) 
		{ 
			
			if (substr($p['id'], 0, 3) == 'abo')
			{
			
				$this->shop->view['wpsg_mod_abo']['order'] = $this->shop->cache->loadOrder($this->getOrderIDFromKey($p['id']));
				$this->shop->view['wpsg_mod_abo']['product'] = $this->shop->cache->loadProduct($this->shop->getProduktID($p['id']));
				$this->shop->view['wpsg_mod_abo']['wpsg_mod_abo_durration_menge'] = $p['menge'] * $this->shop->view['wpsg_mod_abo']['product']['wpsg_mod_abo_durration'];
			
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/overview_row.phtml');
			
			}
			
		} // public function overview_row(&$p, $i)
		
		public function mail_row($index, $produkt)
		{
		
			if (substr($produkt['id'], 0, 3) == 'abo')
			{
		
				$this->shop->view['wpsg_mod_abo']['order'] = $this->shop->cache->loadOrder($this->getOrderIDFromKey($produkt['id']));
				$this->shop->view['wpsg_mod_abo']['product'] = $this->shop->cache->loadProduct($this->shop->getProduktID($produkt['id']));
				$this->shop->view['wpsg_mod_abo']['wpsg_mod_abo_durration_menge'] = $p['menge'] * $this->shop->view['wpsg_mod_abo']['product']['wpsg_mod_abo_durration'];
					
				if ($this->shop->htmlMail === true)
				{
					
					return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_row_html.phtml');
					
				}
				else
				{
				
					return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_row.phtml');
					
				}
		
			}
				
		} // public function mail_row($index, $produkt)
		
		public function order_view_row(&$p, $i)
		{
			
			if (substr($p['id'], 0, 3) == 'abo')
			{
				
				$this->shop->view['wpsg_mod_abo']['order'] = $this->shop->cache->loadOrder($this->getOrderIDFromKey($p['id']));
				$this->shop->view['wpsg_mod_abo']['product'] = $this->shop->cache->loadProduct($this->shop->getProduktID($p['id']));
				$this->shop->view['wpsg_mod_abo']['wpsg_mod_abo_durration_menge'] = $p['menge'] * $this->shop->view['wpsg_mod_abo']['product']['wpsg_mod_abo_durration'];
				
				return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/order_view_row.phtml');
				
			}
			else
			{
				
				$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($p['id']));
				
				if ($product_data['wpsg_mod_abo_activ'] == '1')
				{
					
					$this->shop->view['wpsg_mod_abo']['rebuy'] = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_ORDERPRODUCT."` WHERE `productkey` LIKE 'abo_".wpsg_q($this->shop->view['data']['id'])."_%'");

					foreach ($this->shop->view['wpsg_mod_abo']['rebuy'] as $k => $v)
					{
						
						$product_data = $this->shop->cache->loadProduct($v['p_id']);
						
						$this->shop->view['wpsg_mod_abo']['rebuy'][$k]['product'] = $product_data;
						$this->shop->view['wpsg_mod_abo']['rebuy'][$k]['order'] = $this->shop->cache->loadOrder($v['o_id']);
						$this->shop->view['wpsg_mod_abo']['rebuy'][$k]['tage'] = $v['menge'] * $product_data['wpsg_mod_abo_durration'];
						
					}
					
					return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/order_view_base.phtml');
					
				}
				
			}
			
		} // public function order_view_row(&$p, $i)
		
		/** Modulfunktionen */
		
		/**
		 * Gibt das Datum im MySQL Format zurück, wann das Abo abläuft wenn es heute gekauft wird
		 * @param int $product_id Produkt ID
		 * @param int $menge Anzahl an gekauften Produkten
		 */
		public function getAboExpiration($product_id, $menge, $start)
		{
			
			$product_data = $this->shop->cache->loadProduct($product_id);
			
			return wpsg_date('Y-m-d H:i:s', $start + $product_data['wpsg_mod_abo_durration'] * 24 * 60 * 60 * $menge);
			
		} // public function getAboExpiration($product_id, $menge)
		
		/**
		 * Gibt false zurück wenn die Bestellung keine Abo Bestellung ist
		 * 1 - Originalbestellung
		 * 2 - Folgebestellung
		 */
		public function isAboOrder($order_id)
		{
			
			// Bei Originalbestellungen gibt es einen eintrag in der Tabelle
			$nAboBestellung = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_id)."'");
			
			if ($nAboBestellung > 0) return 1;
			
			// Jetzt auf Folgebestellung testen
			$nFolgeBestellung = $this->db->fetchOne("SELECT COUNT(*) FROM `".WPSG_TBL_ORDERPRODUCT."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `productkey` REGEXP '^abo_[0-9]+_[0-9]+' ");
			
			if ($nFolgeBestellung > 0) return 2;
			
			return false;
			
		} // public function isAboOrder($order_id)
		
		/**
		 * Gibt die BestellID der Originalbestellung einer Verlängerung zurück
		 */
		public function getOriginOrder($order_id)
		{
			
			if ($this->isAboOrder($order_id) !== 2) return false;
			
			$productkeys = $this->db->fetchAssocField("SELECT `productkey` FROM `".WPSG_TBL_ORDERPRODUCT."` WHERE `o_id` = '".wpsg_q($order_id)."' ");
			
			foreach ($productkeys as $pk)
			{
				
				if (preg_match('/^abo_\d+_\d+$/', $pk))
				{
					
					$arAbo = explode('_', $pk);
					
					return $arAbo[1];
					
				}
				
			}
			
			return false;
			
		} // public function getOriginOrder($order_id)
		
		/**
		 * Gibt das Auslaufdatum einer Abobestellung zurück
		 * @param unknown_type $order_id
		 */
		public function getOrderAboExpiration($order_id)
		{
			
			$data = null;			
			$data = wpsg_fromDate($this->db->fetchOne("SELECT `expiration` FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_id)."'"), false);

			return $data;

		} // public function getOrderAboExpiration($order_id)
		
		/**
		 * Gibt die Benachrichtigungsurl für ein Produkt zurück
		 * @param int $product_id ProduktID
		 */
		public function getNotifyURL($product_id)
		{
			 
			$product_data = $this->shop->cache->loadProduct($product_id);
			
			if (wpsg_isSizedString($product_data['wpsg_mod_abo_url'])) return $product_data['wpsg_mod_abo_url'];
			else return $this->shop->get_option('wpsg_mod_abo_url');
			
		} // public function getNotifyURL($product_id)
		
		/**
		 * Sendet die Mail beim erstmaligen Kauf eines Abo Produktes
		 * @param int $order_key BestellID
		 * @param String $product_id ProduktKey
		 */
		public function sendAboFirstBuyMail($order_id, $product_key)
		{
			
			if ($this->shop->get_option('wpsg_mod_abo_wpsgmodabofirstbuy') != '1') return;
			
			$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($product_key));
			$order_data = $this->shop->cache->loadOrder($order_id);
			$customer_data = $this->shop->cache->loadKunden($order_data['k_id']);
			
			$this->shop->view['product'] = $product_data;
			$this->shop->view['customer'] = $customer_data;
			$this->shop->view['order'] = $order_data;	 
			$this->shop->view['rebuyLink'] = $this->getRebuyLink($order_id, $product_key);
			
			if ($this->shop->get_option('wpsg_htmlmail') === '1')
			{
				
				$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_firstbuy_html.phtml', false);
				
			}
			else 
			{

				$mail_html = false;
				
			}
			
			$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_firstbuy.phtml', false);
						
			$this->shop->sendMail($mail_text, $customer_data['email'], 'wpsgmodabofirstbuy', array(), $order_id, $customer_data['id'], $mail_html);
			
			return true;
			
		} // public function sendAboFirstBuyMail($order_id, $product_id)
				
		/**
		 * Sendet die Mail bei ablauf eines Abos
		 * @param int $order_key BestellID
		 * @param String $product_id ProduktKey
		 * @return boolean
		 */
		public function sendAboExpirationMail($order_id, $product_key)
		{
				
			if ($this->shop->get_option('wpsg_mod_abo_wpsgmodaboexpiration') != '1') return;
			
			$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($product_key));
			$order_data = $this->shop->cache->loadOrder($order_id);
			$customer_data = $this->shop->cache->loadKunden($order_data['k_id']);
			
			$this->shop->view['product'] = $product_data;
			$this->shop->view['customer'] = $customer_data;
			$this->shop->view['order'] = $order_data;				
			$this->shop->view['rebuyLink'] = $this->getRebuyLink($order_id, $product_key);				
			$this->shop->view['allowRebuy'] = $this->canReBuyAbo($order_id, $product_key); 
			
			if ($this->shop->get_option('wpsg_htmlmail') === '1')
			{
			
				$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_expiration_html.phtml');
				
			}
			else
			{
				
				$mail_html = false;
				
			}
				
			$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_expiration.phtml', false);
			 
			$this->shop->sendMail($mail_text, $customer_data['email'], 'wpsgmodaboexpiration', array(), $order_id, $customer_data['id'], $mail_html);
				
			return true;
				
		} // public function sendAboExpirationMail($order_id, $product_id)
		
		/**
		 * Sendet die Mail bei verlängerung eines Abos
		 * @param int $order_key BestellID
		 * @param String $product_id ProduktKey
		 * @return boolean
		 */
		public function sendAboRebuyMail($order_id, $product_key)
		{
			
			if ($this->shop->get_option('wpsg_mod_abo_wpsgmodabrebuy') != '1') return;
			
			$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($product_key));
			$order_data = $this->shop->cache->loadOrder($order_id);
			$customer_data = $this->shop->cache->loadKunden($order_data['k_id']);
				
			$this->shop->view['product'] = $product_data;
			$this->shop->view['customer'] = $customer_data;
			$this->shop->view['order'] = $order_data;
			$this->shop->view['rebuyLink'] = $this->getRebuyLink($order_id, $product_key);
			$this->shop->view['allowRebuy'] = $this->canReBuyAbo($order_id, $product_key);
			
			if ($this->shop->get_option('wpsg_htmlmail') === '1')
			{

				$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_rebuy_html.phtml', false);
				
			}
			else
			{
				
				$mail_html = false;
				
			}
			
			$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_abo/mail_rebuy.phtml', false);
						
			$this->shop->sendMail($mail_text, $customer_data['email'], 'wpsgmodabrebuy', array(), $order_id, $customer_data['id'], $mail_html);
			
			return true;
			
		} // public function sendAboRebuyMail($order_id, $product_key)
		
		/**
		 * Gibt false zurück wenn das Abo nicht mehr verlängert werden kann, ansonsten true oder die Anzahl wenn Anzahl beschränkt die noch möglich ist
		 * @param int $order_id BestellID
		 * @param String $product_key ProduktKey
		 */
		public function canReBuyAbo($order_id, $product_key)
		{
			
			$product_data = $this->shop->cache->loadProduct($this->shop->getProduktID($product_key));
			
			if ($product_data['wpsg_mod_abo_resell'] == '0')
			{
			
				return true;
			
			}
			else
			{
			
				$rebuy = $this->db->fetchOne("SELECT `rebuy` FROM `".WPSG_TBL_ABO."` WHERE `order_id` = '".wpsg_q($order_id)."' AND `product_key` = '".wpsg_q($product_key)."'");
			
				if ($rebuy < $product_data['wpsg_mod_abo_resell'])
				{
						
					return $product_data['wpsg_mod_abo_resell'] - $rebuy;
						
				}
			
			}
			
			return false;
			
		} // public function canReBuyAbo($order_id, $product_key)
		
		/**
		 * Gibt aus einem Produktschlüssel die BestellID zurück
		 * @param varchar ProduktKey
		 */
		public function getOrderIDFromKey($product_key)
		{
			
			$arData = explode('_', $product_key);
			
			return $arData[1];		
			
		} // public function getOrderIDFromKey($product_key)
						
		/**
		 * Gibt den Link zum wiederkauf eines Abos zurück
		 * @param int $order_id BestellID
		 * @param int $product_key ProduktKey
		 */
		public function getRebuyLink($order_id, $product_key)
		{
			
			$url = get_permalink($this->shop->get_option('wpsg_page_basket'));
			
			$url .= ((strpos($url, '?') === false)?'?mod=wpsg_mod_abo':'&mod=wpsg_mod_abo');
			$url .= ((strpos($url, '?') === false)?'?order_id=':'&order_id=').$order_id;
			$url .= ((strpos($url, '?') === false)?'?product_key=':'&product_key=').$product_key;
			
			return $url;
			
		} // public function getRebuyLink($order_id, $product_key)
				
	} // class wpsg_mod_abo extends wpsg_mod_basic

?>