<?php

	/**
	 * Kundengruppemodell
	 * @author Daschmi
	 */
	class wpsg_customergroup extends wpsg_model
	{
		
		/**
		 * Lädt die Daten der Kundengruppe
		 */
		public function load($customer_group_id)
		{
			
			parent::load($customer_group_id);
			
			$this->data = $this->db->fetchRow("
				SELECT 
					KG.*,
					(SELECT COUNT(*) FROM `".WPSG_TBL_KU."` AS K WHERE K.`group_id` = KG.`id`) AS `customercount` 
				FROM
					`".WPSG_TBL_KG."` AS KG
				WHERE
					KG.`id` = '".wpsg_q($customer_group_id)."'
			");
				
			if ($this->data['id'] != $customer_group_id || !wpsg_isSizedInt($customer_group_id)) return false;
			
			return true;
			
		} // public function __construct($customer_group_id)
		
		/**
		 * Löscht eine Kundengruppe
		 */
		public static function delete($customer_group_id)
		{
			
			if (!wpsg_isSizedInt($customer_group_id)) return false;
			
			// Kundengruppe löschen
			$GLOBALS['wpsg_db']->Query("DELETE FROM `".WPSG_TBL_KG."` WHERE `id` = '".wpsg_q($customer_group_id)."' ");
			
			// Kundengruppen ID in den Kunden auf Null setzen
			$GLOBALS['wpsg_db']->UpdateQuery(WPSG_TBL_KU, array(
				'group_id' => 'NULL'
			), " `group_id` = '".wpsg_q($customer_group_id)."' ");
			
			return true;
			
		} // public static function delete($customer_group_id)
		
		/**
		 * Gibt einen Array von Kundengruppen zurück, die auf den übergebenen Filter passen
		 * @param array $arFilter
		 */
		public static function find($arFilter = array())
		{
				
			$strQueryWHERE = "";
			$strQueryORDER = "";
				
			if (wpsg_isSizedString($arFilter['name']))
			{
				
				$strQueryWHERE .= " AND KG.`name` LIKE '%".wpsg_q($arFilter['name'])."%' ";
				
			}
			
			switch (strtolower($arFilter['order']))
			{
				
				case 'name': $strQueryORDER .= " KG.`name` "; break;
				case 'customercount': $strQueryORDER .= " `customercount` "; break;
				case 'calculation': $strQueryORDER .= " `calculation` "; break; 
				case 'id': 
				default: 
					$strQueryORDER .= " KG.`id` ";
								
			}
			
			switch (strtolower($arFilter['ascdesc']))
			{
				
				case 'asc': $strQueryORDER .= " ASC "; break;
				case 'desc': 
				default:
					$strQueryORDER .= " DESC ";
				
			}
				
			$strQuery = "
				SELECT
					KG.`id`,
					(SELECT COUNT(*) FROM `".WPSG_TBL_KU."` AS K WHERE K.`group_id` = KG.`id`) AS `customercount` 
				FROM
					`".WPSG_TBL_KG."` AS KG
				WHERE
					1
					".$strQueryWHERE."
				ORDER BY
					".$strQueryORDER." 
			";
		
			$arCustomerGroupID = $GLOBALS['wpsg_db']->fetchAssocField($strQuery);
			$arReturn = array();
				
			foreach ($arCustomerGroupID as $customer_group_id)
			{
		
				$oCustomerGroup = new wpsg_customergroup();
				$oCustomerGroup->load($customer_group_id);
				$arReturn[] = $oCustomerGroup;
		
			}
				
			return $arReturn;
				
		} // public static function find($arFilter = array())
		
	} // class wpsg_customergroup

?>