<?php
	
	/**
	 * Dieses Modul erlaubt die Verwaltung des Warenbestandes
	 *
	 */
	class wpsg_mod_stock extends wpsg_mod_basic 
	{
		
		var $id = 90;		
		var $lizenz = 1;
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Lagerbestand', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Erlaubt die Verwaltung des Lagerbestandes bei den Produkten.', 'wpsg');
						
		} // public function __construct()
		
		public function install() 
		{

			if ($this->shop->get_option('wpsg_mod_stock_template') === false || $this->shop->get_option('wpsg_mod_stock_template') == '')
			{
				$this->shop->update_option('wpsg_mod_stock_template', 'ausverkauft.phtml');
			}
						
			$this->shop->checkDefault('wpsg_mod_stock_showBackendStock', '1');
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');

			/**
			 * Produkttabelle erweitern
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_PRODUCTS." (
			  	stock int(11) NOT NULL,
			  	stock_count int(1) NOT NULL,
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
		} // public function install()
		
		public function settings_edit()
		{
			
			// Verfügbare Produkttemplates
			$this->shop->view['arTemplates'] = $this->shop->loadProduktTemplates();
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_stock/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function settings_save() 
		{
						
			$this->shop->update_option('wpsg_mod_stock_template', $_REQUEST['wpsg_mod_stock_template']);
			$this->shop->update_option('wpsg_mod_stock_notemplateswitch', $_REQUEST['wpsg_mod_stock_notemplateswitch']);			
			$this->shop->update_option('wpsg_mod_stock_allow', $_REQUEST['wpsg_mod_stock_allow']);
			$this->shop->update_option('wpsg_mod_stock_showBackendStock', $_REQUEST['wpsg_mod_stock_showBackendStock']);
			
			if ($this->shop->hasMod('wpsg_mod_productindex'))
			{
				$this->shop->update_option('wpsg_mod_stock_showProductindex', $_REQUEST['wpsg_mod_stock_showProductindex']);
			}
			
			$this->shop->update_option('wpsg_mod_stock_showProduct', $_REQUEST['wpsg_mod_stock_showProduct']);
			
			
		} // public function settings_save()
		
		public function produkt_ajax() { 
			
			if ($_REQUEST['wpsg_cmd'] == 'getVariInfo')
			{
				
				if ($this->shop->hasMod('wpsg_mod_varianten'))
				{
					
					$arVari = $this->shop->callMod('wpsg_mod_varianten', 'loadVarianten', array($_REQUEST['edit_id']));
					
					foreach ((array)$arVari as $var_id => $var)
					{
						
						echo '<b>'.__($var['name'], 'wpsg').':</b><br />';
						echo '<ul>';
						
						foreach ((array)$var['vari'] as $vari_id => $vari)
						{
							
							echo '<li>';
							echo __($vari['name'], 'wpsg').': '.((wpsg_isSizedString($vari['stock']))?$vari['stock']:__('Nicht angegeben!', 'wpsg'));
							echo '</li>';
							
						}
						
						echo '</ul>';
						
					}
					
				}
				else
				{
					
					die(wpsg_translate(__('Aufrufsfehler! Fehlercode:#1#', 'wpsg'), '90_1'));
					
				}
				
			}
			
		} // public function produkt_ajax()		 
		
		public function produkt_edit(&$data)
		{
			
			$data = wpsg_array_merge($data, $this->db->fetchRow("
				SELECT
					`stock`, `stock_count`
				FROM
					`".WPSG_TBL_PRODUCTS."`
				WHERE
					`id` = '".wpsg_q($data['id'])."'
			"));
												
		} // public function produkt_edit(&$data)
		
		public function produkt_save(&$produkt_id)
		{
		
			$this->db->UpdateQuery(WPSG_TBL_PRODUCTS, array(
				"stock" => wpsg_q($_REQUEST['wpsg_mod_stock_stock']),
				"stock_count" => wpsg_q($_REQUEST['wpsg_mod_stock_stock_count'])
			), "`id` = '".wpsg_q($produkt_id)."'");
						
		} // public function produkt_save(&$produkt_id)
		
		public function produkt_edit_sidebar(&$produkt_data)
		{
			
			if (isset($_REQUEST['wpsg_lang'])) return;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_stock/produkt_edit_sidebar.phtml');
			
		} // public function produkt_edit_sidebar(&$produkt_data)

		public function renderProdukt_templateSelect(&$produkt_data, &$template_file) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_stock_notemplateswitch') == '1') return;
			 
			if ($produkt_data['stock'] <= 0 && $this->shop->get_option('wpsg_mod_stock_template') != '-1')
			{
				
				$template_file = WPSG_PATH_PRODUKTTEMPLATES.$this->shop->get_option('wpsg_mod_stock_template');
				
			}
			
		} // public function renderProdukt_templateSelect(&$produkt_data, &$template_file)
		
		public function setOrderStatus($order_id, $status_id, $inform)
		{

			if (in_array($status_id, array(500)) || $this->shop->view['order']['status'] == 500)
			{
				
				// Entweder ist die Bestellvon von Storniert in einen anderen Status gewächselt oder in Storniert
				
				// Lagerbestand zurücksetzen
				$arProductsBuy = $this->db->fetchAssoc("
					SELECT 
						OP.*							
					FROM
						`".WPSG_TBL_ORDERPRODUCT."` AS OP
							LEFT JOIN `".WPSG_TBL_PRODUCTS."` AS P ON (P.`id` = OP.`p_id`)
					WHERE
						OP.`o_id` = '".wpsg_q($order_id)."' 
				");
 
				foreach ($arProductsBuy as $p)
				{
					
					// Bei gekauften Abo Verlängerungen nicht machen
					if (preg_match('/^abo_\d+(.*)/', $p['productkey'])) continue;
					
					if ($this->shop->hasMod('wpsg_mod_productgroups'))
					{
						
						// Verwaltung des Lagerbestandes in der Produktgruppe
						
						// Produktdaten laden um die Produktgruppe herauszufinden
						$product_data = $this->shop->cache->loadProduct($p['p_id']);
								 
						if (wpsg_isSizedInt($product_data['pgruppe']))
						{
					
							$pgruppe_stock_active = $this->db->fetchOne("SELECT `stock_aktiv` FROM `".WPSG_TBL_PRODUCTS_GROUP."` WHERE `id` = '".wpsg_q($product_data['pgruppe'])."' ");
				 
							if ($pgruppe_stock_active === '1')
							{
					
								if ($this->shop->view['order']['status'] == 500) /* war storniert */
								{
					
									$this->db->Query("
										UPDATE ".WPSG_TBL_PRODUCTS_GROUP." SET `stock_value` = `stock_value` - ".wpsg_q($p['menge'])." WHERE `id` = '".wpsg_q($product_data['pgruppe'])."'
									");
					
								}
								else
								{
					
									$this->db->Query("
										UPDATE ".WPSG_TBL_PRODUCTS_GROUP." SET `stock_value` = `stock_value` + ".wpsg_q($p['menge'])." WHERE `id` = '".wpsg_q($product_data['pgruppe'])."'
									");
					
								} 
									
							}
					
						}
						
					}
										
					// Verwaltung im Produkt oder Produktgruppenlagerbestand nicht aktiv
					$product_data =  $this->shop->cache->loadProduct($p['p_id']);
					
					if ($product_data['stock_count'] != '1') continue;
					
					$var_key = false;

					if ($this->shop->hasMod('wpsg_mod_varianten'))
					{
					
						if (wpsg_isSizedString($p['mod_vp_varkey']) && preg_match('/^vp_\d+(.*)/', $p['mod_vp_varkey']))
						{
							
							$var_key = $p['mod_vp_varkey'];
							
						}
						else if (wpsg_isSizedString($p['productkey']) && preg_match('/^vp_\d+(.*)/', $p['productkey']))
						{
							
							$var_key = $p['productkey'];
							
						}
						
					}
					 
					// Normales Produkt
										 
					if ($this->shop->view['order']['status'] == 500) /* war storniert */
					{
					
						$this->db->Query("
							UPDATE ".WPSG_TBL_PRODUCTS." SET `stock` = `stock` - ".wpsg_q($p['menge'])." WHERE `id` = '".wpsg_q($p['p_id'])."'
						");
													
					}
					else
					{
							
						$this->db->Query("
							UPDATE ".WPSG_TBL_PRODUCTS." SET `stock` = `stock` + ".wpsg_q($p['menge'])." WHERE `id` = '".wpsg_q($p['p_id'])."'
						");
							
					}
							 		
					if ($var_key !== false)
					{
						
						// Variantenprodukt
						
						if ($this->shop->view['order']['status'] == 500)
						{
						
							$this->shop->callMod('wpsg_mod_varianten', 'reduceStock', array($var_key, $p['menge'], true));

						}
						else
						{
							
							$this->shop->callMod('wpsg_mod_varianten', 'reduceStock', array($var_key, $p['menge'], false));
							
						}
						
					}	
					
				}
				
			}
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		public function basket_updateProduktFromSession(&$product_index, &$stock) 
		{ 
			
			$product_key = $_SESSION['wpsg']['basket'][$product_index]['id'];
			
			if (!$this->checkBestand($product_key, $stock))
			{
				
				/* Nicht mehr ausreichend im Lager */
				
				if ($this->shop->get_option('wpsg_mod_stock_allow') === '1')
				{
					
					/* Bestellungen mit negativem Lagerbestand verhindern ist aktiv */
					$stock = $this->getBestand($product_key);
					 
					$this->shop->addFrontendError(__('Menge wurde korrigiert, da sie den Warenbestand überschreitet!', 'wpsg'));
					
				}
				else 
				{
					
					$this->shop->addFrontendError(__('Menge überschreitet Warenbestand!', 'wpsg'));
					
				}
				
			}
			
		} // public function basket_updateProduktFromSession(&$product_key, &$stock)
		
		public function basket_produkttosession($product_key, &$amount_set, &$ses_data) 
		{ 
			 
			$ses_amount = max(array($this->getAmountSession($product_key), $this->getAmountSessionById($this->shop->getProduktId($product_key))));
			$check_amount = $amount_set + $ses_amount; 
			
 			if (!$this->checkBestand($product_key, $check_amount))
			{
								
				/* Nicht mehr ausreichend im Lager */
				
				if ($this->shop->get_option('wpsg_mod_stock_allow') === '1')
				{
					 
					/* Bestellungen mit negativem Lagerbestand verhindern ist aktiv */
					$amount_stock = $this->getBestand($product_key);
 
					$amount_set = $amount_stock - $ses_amount;
															
					$this->shop->addFrontendError(__('Menge wurde korrigiert, da sie den Warenbestand überschreitet!', 'wpsg'));
					
					if ($amount_set <= 0) return -2;
										
				}
				else
				{
					 
					$this->shop->addFrontendError(__('Menge überschreitet Warenbestand!', 'wpsg'));
						
				}
				
			}	
			
		}
		
		/* Modulfunktionen */
		
		/**
		 * Gibt den aktuellen Bestand für ein Produkt zurück
		 */
		public function getBestand($produkt_key)
		{
			 
			$arStock = array();
			
			if ($this->shop->hasMod('wpsg_mod_productgroups'))
			{
				
				$product_id = $this->shop->getProduktID($produkt_key);
				$product_data = $this->shop->cache->loadProduct($product_id);
				
				if (wpsg_isSizedInt($product_data['pgruppe']))
				{
					
					$pgroup = $this->db->fetchRow("SELECT `stock_aktiv`, `stock_value` FROM `".WPSG_TBL_PRODUCTS_GROUP."` WHERE `id` = '".wpsg_q($product_data['pgruppe'])."' ");
					
					if ($pgroup['stock_aktiv'] === '1')
					{
						
						$arStock[] = $pgroup['stock_value'];						
						
					}
					
				}
				
			}
			
			if (is_numeric($produkt_key))
			{
			
				// Lagerbestand in der Datenbank
				$arStock[] = $this->db->fetchOne("SELECT P.`stock` FROM `".WPSG_TBL_PRODUCTS."` AS P WHERE P.`id` = '".wpsg_q($produkt_key)."'");
					 				
			}
			else if ($this->shop->hasMod('wpsg_mod_varianten'))
			{
				
				$arStock[] = $this->shop->callMod('wpsg_mod_varianten', 'getStockForVarianten', array($produkt_key)); 
				 				
			}
			
			if (!wpsg_isSizedArray($arStock)) return 0;
			else return min($arStock);
			
		} // public function getBestand($produkt_id)
		
		/**
		 * Gibt die aktuelle Menge eines Produktes aus der Session zurück
		 */
		public function getAmountSession($product_key)
		{
			
			$amount_ses = 0;
			
			if (wpsg_isSizedArray($_SESSION['wpsg']['basket']))
			{
				
				foreach ($_SESSION['wpsg']['basket'] as $product_index => $product_data)
				{
					
					if ($product_key == $product_data['id']) $amount_ses += $product_data['menge'];
					
				}
				
			}
 
			return $amount_ses;
			
		} // public function getAmountSession($product_key)
		
		/**
		 * Gibt die aktuelle Menge eines Produktes aus der Session zurück
		 * Betrachtet dabei den Gesamt Produktbestand (Für Varianten)
		 */
		public function getAmountSessionById($product_id)
		{
			
			$amount_ses = 0;
			
			if (wpsg_isSizedArray($_SESSION['wpsg']['basket']))
			{
				
				foreach ($_SESSION['wpsg']['basket'] as $product_index => $product_data)
				{
					
					if ($this->shop->getProduktId($product_data['id']) == $product_id) $amount_ses += $product_data['menge']; 
					
				}
				
			}
			
			return $amount_ses;
			
		} // public function getAmountSessionById($product_id)
		
		/**
		 * Überprüft ob der Bestand eines Produktes noch ausreichend ist
		 * @return true|false
		 */
		public function checkBestand($produkt_key, $menge) 
		{
			
			if (substr($produkt_key, 0, 3) == 'abo') return;
			
			$product_id = $this->shop->getProduktID($produkt_key);
			$product_data = $this->shop->cache->loadProduct($produkt_id);
									
			if ($this->shop->hasMod('wpsg_mod_productgroups'))
			{
				
				if (wpsg_isSizedInt($product_data['pgruppe']))
				{
					
					$pgroup = $this->db->fetchRow("SELECT `stock_aktiv`, `stock_value` FROM `".WPSG_TBL_PRODUCTS_GROUP."` WHERE `id` = '".wpsg_q($product_data['pgruppe'])."' ");
					
					if ($pgroup['stock_aktiv'] === '1')
					{
						
						$stock = $pgroup['stock_value'];
						
						/* Lagerbestand der Produktgruppe ist aktiv */						
						if ($menge > $stock)
						{

							return false;
							
						}
						
					}
					
				}
				
			}
						
			$product_stock = $this->getBestand($produkt_key);
			 
			if ($menge > $product_stock)
			{
				
				return false;
				
			}
			
			return true;
			
						
		} // public function checkBestand(&$produkt_key, $menge)
		
		public function basket_save_product(&$data, &$product_data_db, $finish_order) 
		{ 

			if ($finish_order !== true) return;
			
			$product_id = $this->shop->getProduktID($data['productkey']);
			$product_data = $this->shop->cache->loadProduct($product_id);
			$stock = $data['menge'];
			  
			/* Produktgruppe runterzählen */
			if ($this->shop->hasMod('wpsg_mod_productgroups'))
			{
			
				$pgroup = $this->db->fetchRow("SELECT `stock_aktiv`, `stock_value` FROM `".WPSG_TBL_PRODUCTS_GROUP."` WHERE `id` = '".wpsg_q($product_data['pgruppe'])."' ");
			
				if ($pgroup['stock_aktiv'] == '1')
				{
						
					$this->db->Query("
						UPDATE `".WPSG_TBL_PRODUCTS_GROUP."` SET `stock_value` = `stock_value` - '".wpsg_q($stock)."' WHERE `id` = '".wpsg_q($product_data['pgruppe'])."' 
					");
				}
			
			}
				
			// Produkt runterzählen
				
			// Wenn Zählung im Produkt deaktiviert, dann breche ich hier ab
			if ($product_data['stock_count'] != '1') return;
			 
			if ($this->shop->hasMod('wpsg_mod_varianten') && preg_match('/^vp_(.*)/', $data['productkey']))
			{
					
				// Bestand der Variationen runterzählen
				$this->shop->callMod('wpsg_mod_varianten', 'reduceStock', array($data['productkey'], $stock));
					
			}
				
			// Im Produkt selbst runterzählen
			$this->db->Query("
				UPDATE `".WPSG_TBL_PRODUCTS."` SET `stock` = `stock` - '".wpsg_q($stock)."' WHERE `id` = '".wpsg_q($product_id)."' 
			");
			
		} // public function basket_save_product(&$data, &$product_data)
				
	} // class wpsg_mod_stock extends wpsg_mod_basic

?>